From ae03a93f981c731f857ac5c71fd75f20aff3f64c Mon Sep 17 00:00:00 2001 From: Benjamin Hardy Date: Wed, 30 Sep 2026 23:17:55 +0200 Subject: [PATCH] Implemented front end for stem conversion --- CLAUDE.md | 22 + backend/konduktor/stems/convert.py | 8 +- frontend/src/App.tsx | 139 +++++- frontend/src/api.ts | 79 ++++ frontend/src/components/ContextMenu.tsx | 9 +- .../src/components/ConvertStemsDialog.tsx | 445 ++++++++++++++++++ frontend/src/components/SaveBar.tsx | 13 + frontend/src/components/SettingsMenu.tsx | 15 +- frontend/src/components/StatusBar.tsx | 7 +- frontend/src/components/StemReportDialog.tsx | 55 +++ frontend/src/components/StemsSettings.tsx | 248 ++++++++++ frontend/src/components/Toast.tsx | 15 +- 12 files changed, 1043 insertions(+), 12 deletions(-) create mode 100644 frontend/src/components/ConvertStemsDialog.tsx create mode 100644 frontend/src/components/StemReportDialog.tsx create mode 100644 frontend/src/components/StemsSettings.tsx diff --git a/CLAUDE.md b/CLAUDE.md index 9f67e52..dcaa1e6 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -596,6 +596,28 @@ Two independent apps that talk over HTTP: flushSync-driven measurement — which is why playlists were once a separate, non-virtualized `PlaylistTable`. Fixed 44 px rows make the drop index just pointer-y / ROW_HEIGHT. dnd-kit still reorders the header's columns.) + `ConvertStemsDialog` (**Convert to Stems**, one dialog — decided: Where = + Replace the originals (its option STATES that Save deletes them, since + the choice is remembered and may be preselected) or Save to a folder; In + the collection = point at the stem file / add as new tracks + playlist + (folder mode only); a live preview from `POST /api/tracks/stems/preview` + — N to convert, skipped ▸ with reasons, a time estimate from measured + real-time factors, space; the engine download INLINE, offering the GPU + engine when `nvidia` is set, which keeps running if the dialog closes + (App shows it in the status bar). Every option persists as `stemConvert`), + `StemReportDialog` (the Details behind a finished run's toast — every + skipped/failed track with its reason), `StemsSettings` (Settings → Stems: + engine status / download / install from a folder / remove, compute device + `stemDevice`, the remembered defaults, originals awaiting Save). App + follows a finished run's `{old: new}` ids with the deck and the selection, + picks a running conversion back up from `/api/state.stem_job` after a + reload, and reports `stem_recovery` once. The menu item is shown DISABLED + with a reason (`MenuItem.title` — rendered `aria-disabled`, not + `disabled`, since browsers show no tooltip on a disabled button) where the + platform cannot play stem files as stems. SaveBar adds "Saving deletes N + original files" while conversions are pending (decided: the consequence is + shown where Save is pressed). `Toast` takes an optional `action`; + `StatusJob.unit: 'bytes'` shows a download in MB. `AutoCueDialog` (the Auto Hotcues slot template: event + beat offset per slot, a per-slot Replace tick for occupied slots — never remembered, since overwriting is a decision about THIS track — and the template itself diff --git a/backend/konduktor/stems/convert.py b/backend/konduktor/stems/convert.py index 33cfa8f..040545a 100644 --- a/backend/konduktor/stems/convert.py +++ b/backend/konduktor/stems/convert.py @@ -77,7 +77,13 @@ class Plan: def as_dict(self) -> dict: return {"convert": [{"track_id": p.track_id, "title": p.title, "target": str(p.target), "reuse": p.reuse is not None} for p in self.items], - "skipped": self.skipped, "space": self.space, "blocked": self.blocked} + "skipped": self.skipped, "space": self.space, "blocked": self.blocked, + # For the dialog's estimate: audio still to SEPARATE (reused + # leftovers cost nothing), and what the new files will take. + "seconds": sum(p.seconds for p in self.items if p.reuse is None), + "bytes": sum(e["bytes"] for e in self.space), + # What Save would delete in Replace mode — the dialog says so. + "original_bytes": sum(p.source.stat().st_size for p in self.items if p.source.exists())} def _title(track) -> str: diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 224c9c2..ffc07ea 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -4,7 +4,7 @@ import type { ColumnSizingState, SortingState, VisibilityState } from '@tanstack import { CapabilitiesContext, slotLabeller } from './lib/capabilities' import { writeHint } from './lib/platformCopy' import { invalidateTrackLists } from './lib/trackQueries' -import { api, type CueBatchResult, type GridBatchResult, type AutoCueSlot, type PlaylistNode, type Track, type TrackOrigin } from './api' +import { api, type CueBatchResult, type GridBatchResult, type AutoCueSlot, type PlaylistNode, type StemBatchResult, type Track, type TrackOrigin } from './api' import { confirmDiscardUnsaved } from './lib/unsaved' import { COLUMN_MENU, @@ -28,6 +28,8 @@ import { HistoryPanel } from './components/HistoryPanel' import { PrepStrip } from './components/PrepStrip' import { ImportDialog } from './components/ImportDialog' import { AddFilesDialog, type AddTarget } from './components/AddFilesDialog' +import { ConvertStemsDialog } from './components/ConvertStemsDialog' +import { StemReportDialog } from './components/StemReportDialog' import { Icon } from './lib/icons' function applyFilters(tracks: Track[], f: Filters): Track[] { @@ -86,7 +88,12 @@ export default function App() { { ids: string[]; existing: number; locked: number } | null >(null) const [cueBatch, setCueBatch] = useState<{ ids: string[]; withoutGrid: number } | null>(null) - const [batchJob, setBatchJob] = useState<{ id: string; kind: 'grid' | 'cues' } | null>(null) + const [batchJob, setBatchJob] = useState<{ id: string; kind: 'grid' | 'cues' | 'stems' } | null>(null) + // Convert to Stems: the dialog's selection, a finished run's Details, and a + // running engine download (which outlives the dialog — decided). + const [stemDialog, setStemDialog] = useState(null) + const [stemReport, setStemReport] = useState(null) + const [engineJob, setEngineJob] = useState(null) const [batchCancelling, setBatchCancelling] = useState(false) const [cuesRefresh, setCuesRefresh] = useState(0) // bump → deck re-reads its cues // Every Remove ▸ action (and the playlist Delete key) confirms first. @@ -184,8 +191,8 @@ export default function App() { const libraryName = collection.data?.library?.display_name ?? null const writeHintText = save ? writeHint(save) : 'save to write it to disk' - const notify = useCallback((kind: ToastMsg['kind'], text: string) => { - setToast({ id: Date.now(), kind, text }) + const notify = useCallback((kind: ToastMsg['kind'], text: string, action?: ToastMsg['action']) => { + setToast({ id: Date.now(), kind, text, action }) }, []) const onError = useCallback((msg: string) => notify('error', msg), [notify]) @@ -513,6 +520,10 @@ export default function App() { const kind = batchJob.kind setBatchJob(null) setBatchCancelling(false) + if (kind === 'stems') { + finishStemBatch(job.state, job.result as unknown as StemBatchResult | null, job.error) + return + } if (job.state === 'failed') { const what = kind === 'grid' ? 'Grid analysis' : 'Auto Hotcues' onError(`${what} failed: ${job.error ?? 'unknown error'}`) @@ -567,6 +578,78 @@ export default function App() { qc.invalidateQueries() // refetch everything for the newly-opened collection } + // ---- Convert to Stems ------------------------------------------------------ + const canStems = canEdit && !viewForeign && !!capabilities.data?.tracks.stem_convertible + const finishStemBatch = (state: string, r: StemBatchResult | null, error: string | null) => { + qc.invalidateQueries({ queryKey: ['state'] }) + if (state === 'failed' || !r) { + onError(`Converting to stems failed: ${error ?? 'unknown error'}`) + return + } + if (r.cancelled) { + notify('warning', 'Conversion cancelled — nothing was changed') + return + } + invalidateTrackLists(qc) + qc.invalidateQueries({ queryKey: ['playlists'] }) + qc.invalidateQueries({ queryKey: ['export-contents'] }) + qc.invalidateQueries({ queryKey: ['facets'] }) + // A repointed track's id IS its location, so it changed: follow it with the + // deck and the selection instead of leaving them on an id that is gone. + const renamed = r.renamed + if (prepTrack && renamed[prepTrack.id]) { + setPrepTrack({ ...prepTrack, id: renamed[prepTrack.id], media_kind: 'stem' }) + setCuesRefresh((n) => n + 1) + } + setSelected((sel) => new Set([...sel].map((id) => renamed[id] ?? id))) + const n = r.converted.length + const parts = [ + `${n} converted to stems`, + r.skipped.length ? `${r.skipped.length} skipped` : '', + r.failed.length ? `${r.failed.length} failed` : '', + ].filter(Boolean) + const text = parts.join(' · ') + (n ? ' — Save to keep them' : '') + const details = r.skipped.length || r.failed.length ? { label: 'Details', onClick: () => setStemReport(r) } : undefined + notify(n ? 'success' : 'error', text, details) + } + // A conversion keeps running if the page reloads; find it again. + const editState = useQuery({ queryKey: ['state'], queryFn: api.state, enabled: loaded, retry: false }) + useEffect(() => { + const id = editState.data?.stem_job + if (id && !batchJob) setBatchJob({ id, kind: 'stems' }) + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [editState.data?.stem_job]) + // Tell the user once what crash recovery did about an interrupted conversion. + const recovery = editState.data?.stem_recovery + const recoveryShown = useRef(null) + useEffect(() => { + if (!recovery || recoveryShown.current === recovery) return + recoveryShown.current = recovery + const bits = [ + recovery.restored ? `${recovery.restored} original${recovery.restored === 1 ? '' : 's'} put back` : '', + recovery.committed ? `${recovery.committed} saved conversion${recovery.committed === 1 ? '' : 's'} finished` : '', + recovery.kept ? `${recovery.kept} converted file${recovery.kept === 1 ? '' : 's'} kept for next time` : '', + ].filter(Boolean) + if (bits.length) notify('warning', `An interrupted stem conversion was tidied up: ${bits.join(' · ')}`) + }, [recovery, notify]) + const engineJobStatus = useQuery({ + queryKey: ['job', engineJob], + queryFn: () => api.job(engineJob!), + enabled: !!engineJob, + refetchInterval: (q) => (q.state.data && q.state.data.state !== 'running' ? false : 500), + }) + useEffect(() => { + const job = engineJobStatus.data + if (!job || job.state === 'running' || job.id !== engineJob) return + setEngineJob(null) + qc.invalidateQueries({ queryKey: ['stem-engine'] }) + if (job.state === 'done') notify('success', 'The stem engine is installed') + else if (job.state === 'failed') onError(job.error || 'The stem engine download failed') + }, [engineJobStatus.data, engineJob, qc, notify, onError]) + + // Hooks must all run BEFORE the early returns below (picker / loading), + // or the first render with a library has more hooks than the last one and + // React throws — the whole window goes blank. if (collection.isLoading || (loaded && !capabilities.data)) { return (
@@ -641,6 +724,7 @@ export default function App() { } const canAutoCue = canEdit && !viewForeign && (capabilities.data?.cues.hotcue_slots ?? 0) > 0 + // ---- Remove ▸ ----------------------------------------------------------- const nTracks = (n: number) => `${n} track${n === 1 ? '' : 's'}` const trackNoun = (ids: string[]) => { @@ -885,6 +969,25 @@ export default function App() { }, ] : []), + // Shown disabled WITH a reason where the platform cannot play stem + // files as stems, rather than hidden: a missing item reads as a bug. + ...(canEdit && !viewForeign + ? [ + canStems + ? { + label: 'Convert to Stems…', + hint: batchJob ? 'busy' : menu.ids.length > 1 ? String(menu.ids.length) : undefined, + disabled: !!batchJob, + onClick: () => setStemDialog(menu.ids), + } + : { + label: 'Convert to Stems…', + disabled: true, + title: 'This library\'s DJ app does not play native-instruments stem files as stems', + onClick: () => {}, + }, + ] + : []), // A device's track ids belong to the stick, not the collection, so // there is nothing they could be added to. A folder's files CAN be // added — through the add dialog, which puts them in the @@ -925,6 +1028,19 @@ export default function App() { onClose={() => setHeaderMenu(null)} /> )} + {stemDialog && ( + setStemDialog(null)} + onStarted={(job) => { + setBatchCancelling(false) + setBatchJob({ id: job.id, kind: 'stems' }) + }} + onDownloading={(job) => setEngineJob(job.id)} + onError={onError} + /> + )} + {stemReport && setStemReport(null)} />} {editing && ( onError((e as Error).message)) }, } - : null + : engineJob + ? { + label: 'Downloading the stem engine', + unit: 'bytes', + done: engineJobStatus.data?.done ?? 0, + total: engineJobStatus.data?.total ?? 0, + detail: engineJobStatus.data?.message, + onCancel: () => { + api.cancelJob(engineJob).catch((e) => onError((e as Error).message)) + }, + } + : null } loading={loading} collectionName={capabilities.data ? libraryName : null} diff --git a/frontend/src/api.ts b/frontend/src/api.ts index 3ca7cb1..e4d8696 100644 --- a/frontend/src/api.ts +++ b/frontend/src/api.ts @@ -434,6 +434,73 @@ export interface CueBatchResult { failed: { title: string; reason: string }[] } +/** Convert to Stems: where the files go and what the collection does. */ +export interface StemConvertOptions { + /** `replace`: the stem file supersedes the original where it lives (the + * original is parked, and Save deletes it). `destination`: a chosen folder; + * the originals are never touched. */ + mode: 'replace' | 'destination' + destination?: string | null + /** `repoint`: the entry names the stem file. `add`: a new entry beside it + * (destination mode only). */ + collection: 'repoint' | 'add' + playlist_id?: string | null + new_playlist?: string | null +} + +export interface StemSkip { + track_id: string + title: string + reason: string +} + +/** What a conversion would do (`POST /api/tracks/stems/preview`). */ +export interface StemPlan { + convert: { track_id: string; title: string; target: string; reuse: boolean }[] + skipped: StemSkip[] + space: { volume: string; folder: string; bytes: number; free: number | null }[] + /** Set when the batch cannot run at all (not enough space). */ + blocked: string | null + /** Audio still to separate, in seconds (reused leftovers excluded). */ + seconds: number + /** What the new stem files will take on disk. */ + bytes: number + /** The originals' size — what Save deletes in Replace mode. */ + original_bytes: number +} + +/** A stem conversion job's `result`. */ +export interface StemBatchResult { + converted: { track_id: string; new_id: string; title: string }[] + /** Old id → new id, for entries repointed at their stem file. */ + renamed: Record + /** Original id → the NEW entry added beside it. */ + added: Record + skipped: StemSkip[] + failed: StemSkip[] + cancelled: boolean + playlist_missing?: boolean +} + +export type StemTarget = 'macos-arm64' | 'windows-x64-cpu' | 'windows-x64-cuda' + +/** `GET /api/stems/engine`: the engine and weights on this computer. */ +export interface StemEngineStatus { + supported: boolean + required_version: string + installed: { version: string; target: StemTarget; size: number | null } | null + offered_targets: StemTarget[] + download_sizes: Partial> + manifest_available: boolean + nvidia: { name: string; driver: string; capability: number } | null + weights: { installed: boolean; size: number; revision: string } + root: string + /** `auto` | `cpu` | `gpu`, from prefs (`stemDevice`). */ + device: string + /** A running download's job id. */ + install_job: string | null +} + export interface SourceCandidate { path: string /** What a person recognises, e.g. "OneLibrary — Hardy". */ @@ -826,6 +893,18 @@ export const api = { /** Remove tracks from the library and every playlist. Audio files stay. */ removeTracks: (trackIds: string[]) => send<{ removed: number }>('POST', '/api/tracks/remove', { track_ids: trackIds }), + stemPreview: (trackIds: string[], opts: StemConvertOptions) => + send('POST', '/api/tracks/stems/preview', { track_ids: trackIds, ...opts }), + /** Starts a `stem-conversion` job; its `result` is a `StemBatchResult`. */ + stemConvert: (trackIds: string[], opts: StemConvertOptions) => + send('POST', '/api/tracks/stems/convert', { track_ids: trackIds, ...opts }), + stemEngine: () => getJSON('/api/stems/engine'), + /** Starts a `stem-engine-install` job, counting bytes (engine + weights). */ + stemEngineInstall: (target?: StemTarget | null) => + send('POST', '/api/stems/engine/install', { target: target ?? null, weights: true }), + stemSideload: (path: string, kind: 'engine' | 'weights') => + send('POST', '/api/stems/engine/sideload', { path, kind }), + stemEngineRemove: () => send('DELETE', '/api/stems/engine'), autoGridBatch: (trackIds: string[], replaceExisting: boolean) => send('POST', '/api/tracks/grid/auto-batch', { track_ids: trackIds, diff --git a/frontend/src/components/ContextMenu.tsx b/frontend/src/components/ContextMenu.tsx index 0e46c5e..d5294b6 100644 --- a/frontend/src/components/ContextMenu.tsx +++ b/frontend/src/components/ContextMenu.tsx @@ -5,7 +5,9 @@ import { Icon } from '../lib/icons' /** One row of a menu: an action, a submenu (`label ▸`), or a section heading. */ export type MenuItem = - | { label: string; onClick: () => void; danger?: boolean; hint?: string; icon?: ReactNode; disabled?: boolean } + // `title` explains a disabled item (shown on hover). Such an item is NOT a + // disabled + , + )} + + + {opts.mode === 'destination' && ( +
+
+ In the collection +
+ {radio( + 'stem-collection', + opts.collection === 'repoint', + () => set({ collection: 'repoint' }), + 'Point each track at its stem file', + 'The track keeps its playlists, cues and history. The original file stays where it is.', + )} + {radio( + 'stem-collection', + opts.collection === 'add', + () => set({ collection: 'add' }), + 'Add the stem files as new tracks', + 'With the same cues, grid and tags. The original tracks stay as they are.', + )} + {opts.collection === 'add' && ( +
+ + {opts.playlist === 'new' && ( + set({ playlistName: e.target.value })} + className="well min-w-0 flex-1 rounded-md px-2 py-1 text-text" + placeholder="Playlist name" + /> + )} +
+ )} +
+ )} + + {!ready && st && ( +
+ {!st.supported ? ( +
There is no stem engine for this computer.
+ ) : downloading && install.data ? ( +
+
{install.data.message || 'Downloading…'}
+
+
+
+
+ {size(install.data.done)} of {size(install.data.total || needBytes)} · closing this keeps it + going +
+
+ ) : !st.manifest_available && !st.installed ? ( +
+ The stem engine is a one-time download, and it cannot be reached right now. Check the internet + connection — or install it from a file in Settings → Stems. +
+ ) : ( +
+
+ The stem engine is a one-time download ({size(needBytes)}). +
+ {offered.length > 1 && !st.installed && ( +
+ {offered.map((t) => ( + + ))} +
+ )} + +
+ )} +
+ )} + + {preview.isError &&
{(preview.error as Error).message}
} + {plan && ( +
+
+ {n} to convert + {plan.skipped.length > 0 && ( + <> + {' · '} + + + )} +
+ {skippedOpen && ( +
    + {plan.skipped.map((s) => ( +
  • + + {s.title} + + {s.reason} +
  • + ))} +
+ )} + {n > 0 && ( +
+ {plan.seconds > 0 && rtf ? `About ${duration(plan.seconds / rtf)} on this computer · ` : ''} + {plan.seconds === 0 && allReused ? 'Already converted earlier — nothing to separate · ' : ''} + {size(plan.bytes)} of stem files +
+ )} + {plan.blocked &&
{plan.blocked}
} +
+ )} +
+ )} + +
+ + +
+ + + , + document.body, + ) +} diff --git a/frontend/src/components/SaveBar.tsx b/frontend/src/components/SaveBar.tsx index cdd79cf..2e1ba13 100644 --- a/frontend/src/components/SaveBar.tsx +++ b/frontend/src/components/SaveBar.tsx @@ -56,6 +56,7 @@ export function SaveBar({ onError, trailing, onDiscarded }: Props) { const caps = useCaps() const warning = overwriteWarning(caps.save) const dirty = state?.dirty ?? false + const pending = state?.pending_stems const readOnly = readOnlyNotice(caps) // A read-only library has no save to offer, and saying so plainly is the whole @@ -80,6 +81,18 @@ export function SaveBar({ onError, trailing, onDiscarded }: Props) { {warning} )} + {/* Decided: the consequence is shown where Save is pressed, not only in + the Stems panel — Save deletes what a Replace conversion parked. */} + {pending && pending.parked > 0 && ( +
+ + + Saving deletes {pending.parked} original file{pending.parked === 1 ? '' : 's'} ( + {pending.bytes >= 1e9 ? `${(pending.bytes / 1e9).toFixed(1)} GB` : `${Math.round(pending.bytes / 1e6)} MB`} + ) replaced by stem files. Discard to keep them. + +
+ )}
+
)} {showShortcuts && setShowShortcuts(false)} />} + {showStems && setShowStems(false)} />} ) } diff --git a/frontend/src/components/StatusBar.tsx b/frontend/src/components/StatusBar.tsx index 58c1c33..307bcd4 100644 --- a/frontend/src/components/StatusBar.tsx +++ b/frontend/src/components/StatusBar.tsx @@ -9,6 +9,8 @@ export interface StatusJob { detail?: string cancelling?: boolean onCancel: () => void + /** `bytes`: done/total are byte counts (a download), shown in MB. */ + unit?: 'bytes' } interface Props { @@ -60,7 +62,10 @@ export function StatusBar({
{job.cancelling ? 'Cancelling…' : job.label} - {job.total > 0 && ` ${Math.min(job.done + 1, job.total)}/${job.total}`} + {job.total > 0 && + (job.unit === 'bytes' + ? ` ${Math.round(job.done / 1e6)}/${Math.round(job.total / 1e6)} MB` + : ` ${Math.min(job.done + 1, job.total)}/${job.total}`)} void }) { + useEffect(() => { + const onKey = (e: KeyboardEvent) => e.key === 'Escape' && onClose() + window.addEventListener('keydown', onKey) + return () => window.removeEventListener('keydown', onKey) + }, [onClose]) + + const rows = [ + ...result.failed.map((s) => ({ ...s, failed: true })), + ...result.skipped.map((s) => ({ ...s, failed: false })), + ] + const n = result.converted.length + return createPortal( +
+
e.stopPropagation()}> +
+ {n} converted to stems · {result.skipped.length} skipped · {result.failed.length} failed +
+
    + {rows.map((r) => ( +
  • + + {r.title} + + + {r.failed ? 'failed: ' : ''} + {r.reason} + +
  • + ))} +
+
+ {n ? 'Save to keep the converted tracks.' : ''} + +
+
+
, + document.body, + ) +} diff --git a/frontend/src/components/StemsSettings.tsx b/frontend/src/components/StemsSettings.tsx new file mode 100644 index 0000000..4c00385 --- /dev/null +++ b/frontend/src/components/StemsSettings.tsx @@ -0,0 +1,248 @@ +import { createPortal } from 'react-dom' +import { useEffect, useState } from 'react' +import { useQuery, useQueryClient } from '@tanstack/react-query' +import { api, type StemTarget } from '../api' +import { askConfirm } from '../lib/confirm' +import { FolderPicker } from './FolderPicker' +import { size } from './ConvertStemsDialog' + +/** + * Settings → Stems (decided contents): the engine (status, download, install + * from files for offline machines, remove), the compute device, the conversion + * defaults the Convert dialog remembers, and the originals awaiting Save. + */ + +interface Props { + onClose: () => void +} + +export function StemsSettings({ onClose }: Props) { + const qc = useQueryClient() + const engine = useQuery({ queryKey: ['stem-engine'], queryFn: api.stemEngine }) + const state = useQuery({ queryKey: ['state'], queryFn: api.state, retry: false }) + const prefs = useQuery({ queryKey: ['prefs'], queryFn: api.getPrefs }) + const [busy, setBusy] = useState(false) + const [error, setError] = useState(null) + const [picking, setPicking] = useState(null) + + const st = engine.data + const installJob = st?.install_job ?? null + const install = useQuery({ + queryKey: ['job', installJob], + queryFn: () => api.job(installJob!), + enabled: !!installJob, + refetchInterval: (q) => (q.state.data && q.state.data.state !== 'running' ? false : 500), + }) + useEffect(() => { + if (install.data && install.data.state !== 'running') { + if (install.data.state === 'failed') setError(install.data.error || 'The download failed') + qc.invalidateQueries({ queryKey: ['stem-engine'] }) + } + }, [install.data, qc]) + + useEffect(() => { + const onKey = (e: KeyboardEvent) => e.key === 'Escape' && !picking && onClose() + window.addEventListener('keydown', onKey) + return () => window.removeEventListener('keydown', onKey) + }, [onClose, picking]) + + const act = async (fn: () => Promise) => { + setBusy(true) + setError(null) + try { + await fn() + qc.invalidateQueries({ queryKey: ['stem-engine'] }) + } catch (e) { + setError((e as Error).message) + } finally { + setBusy(false) + } + } + + const device = st?.device ?? 'auto' + const setDevice = (d: string) => + api.patchPrefs({ stemDevice: d }).then((p) => { + qc.setQueryData(['prefs'], p) + qc.invalidateQueries({ queryKey: ['stem-engine'] }) + }) + const defaults = (prefs.data as { stemConvert?: { mode?: string; destination?: string; collection?: string } }) + ?.stemConvert + const pending = state.data?.pending_stems + const downloading = install.data?.state === 'running' + const targetLabel = (t: StemTarget) => + t === 'macos-arm64' ? 'Apple silicon (GPU)' : t === 'windows-x64-cuda' ? 'NVIDIA GPU' : 'processor only' + + return createPortal( + <> + {picking && ( + void act(() => api.stemSideload(path, picking))} + onClose={() => setPicking(null)} + /> + )} +
+
e.stopPropagation()} + > +
+

Stems

+ +
+
+
+

Stem engine

+ {!st ? ( +
Loading…
+ ) : !st.supported ? ( +
There is no stem engine for this computer.
+ ) : ( + <> +
+ {st.installed + ? `Installed — version ${st.installed.version}, ${targetLabel(st.installed.target)}${ + st.installed.size ? `, ${size(st.installed.size)}` : '' + }` + : 'Not installed'} + {' · '} + {st.weights.installed ? `model installed (${size(st.weights.size)})` : 'model not installed'} +
+ {downloading && install.data && ( +
+
+
+
+
+ {install.data.message} {size(install.data.done)} of {size(install.data.total)} +
+
+ )} +
+ {!(st.installed && st.weights.installed) && !downloading && + st.offered_targets.map((t) => ( + + ))} + + + {(st.installed || st.weights.installed) && ( + + )} +
+ {!st.manifest_available && !st.installed && ( +
The download cannot be reached right now.
+ )} + + )} +
+ +
+

Compute device

+
+ {[ + ['auto', 'Automatic'], + ['gpu', 'GPU'], + ['cpu', 'Processor only'], + ].map(([value, label]) => ( + + ))} +
+
+ Automatic uses the fastest available. The GPU is several times faster; without one, conversion runs on + the processor. +
+
+ +
+

Conversion defaults

+
+ {defaults + ? defaults.mode === 'destination' + ? `Save to ${defaults.destination ?? 'a folder'}, ${ + defaults.collection === 'add' ? 'added as new tracks' : 'the track pointed at its stem file' + }` + : 'Replace the originals' + : 'Replace the originals'} +
+
The Convert to Stems dialog remembers what you chose last.
+ {defaults && ( + + )} +
+ +
+

Originals awaiting Save

+
+ {pending && pending.parked + ? `${pending.parked} original file${pending.parked === 1 ? '' : 's'} (${size(pending.bytes)}) kept beside their stem files. Saving deletes them; Discard puts them back.` + : 'None.'} +
+
+ + {error &&
{error}
} +
+
+
+ , + document.body, + ) +} diff --git a/frontend/src/components/Toast.tsx b/frontend/src/components/Toast.tsx index 8b15948..0e94de8 100644 --- a/frontend/src/components/Toast.tsx +++ b/frontend/src/components/Toast.tsx @@ -5,6 +5,8 @@ export interface ToastMsg { id: number kind: 'success' | 'error' | 'warning' text: string + /** A button in the toast, e.g. "Details". Keeps the toast up longer. */ + action?: { label: string; onClick: () => void } } const KIND_CLS: Record = { @@ -16,7 +18,7 @@ const KIND_CLS: Record = { export function Toast({ toast, onClose }: { toast: ToastMsg | null; onClose: () => void }) { useEffect(() => { if (!toast) return - const t = setTimeout(onClose, toast.kind === 'success' ? 4000 : 6000) + const t = setTimeout(onClose, toast.action ? 10000 : toast.kind === 'success' ? 4000 : 6000) return () => clearTimeout(t) }, [toast, onClose]) @@ -29,6 +31,17 @@ export function Toast({ toast, onClose }: { toast: ToastMsg | null; onClose: () {/* The glass carries no colour; a lit dot says which kind this is. */} {toast.text} + {toast.action && ( + + )}
, document.body,