Implemented front end for stem conversion

This commit is contained in:
patben8 committed 2026-10-01 10:55:09 +02:00
1 parent c560876c02
commit ae03a93f98
12 files changed
+1043 -12

No files matched your search

+22
View File
@@ -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
+7 -1
View File
@@ -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:
+133 -6
View File
@@ -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<string[] | null>(null)
const [stemReport, setStemReport] = useState<StemBatchResult | null>(null)
const [engineJob, setEngineJob] = useState<string | null>(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<unknown>(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 (
<div className="flex h-screen w-screen items-center justify-center text-muted">
@@ -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 && (
<ConvertStemsDialog
trackIds={stemDialog}
onClose={() => setStemDialog(null)}
onStarted={(job) => {
setBatchCancelling(false)
setBatchJob({ id: job.id, kind: 'stems' })
}}
onDownloading={(job) => setEngineJob(job.id)}
onError={onError}
/>
)}
{stemReport && <StemReportDialog result={stemReport} onClose={() => setStemReport(null)} />}
{editing && (
<EditTagsDialog
track={editing}
@@ -1341,7 +1457,7 @@ export default function App() {
job={
batchJob
? {
label: batchJob.kind === 'grid' ? 'Analyzing grids' : 'Placing hotcues',
label: batchJob.kind === 'grid' ? 'Analyzing grids' : batchJob.kind === 'stems' ? 'Converting to stems' : 'Placing hotcues',
done: batchJobStatus.data?.done ?? 0,
total: batchJobStatus.data?.total ?? 0,
detail: batchJobStatus.data?.message,
@@ -1351,7 +1467,18 @@ export default function App() {
api.cancelJob(batchJob.id).catch((e) => 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}
+79
View File
@@ -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<string, string>
/** Original id → the NEW entry added beside it. */
added: Record<string, string>
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<Record<StemTarget, number | null>>
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<StemPlan>('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<JobStatus>('POST', '/api/tracks/stems/convert', { track_ids: trackIds, ...opts }),
stemEngine: () => getJSON<StemEngineStatus>('/api/stems/engine'),
/** Starts a `stem-engine-install` job, counting bytes (engine + weights). */
stemEngineInstall: (target?: StemTarget | null) =>
send<JobStatus>('POST', '/api/stems/engine/install', { target: target ?? null, weights: true }),
stemSideload: (path: string, kind: 'engine' | 'weights') =>
send<StemEngineStatus>('POST', '/api/stems/engine/sideload', { path, kind }),
stemEngineRemove: () => send<StemEngineStatus>('DELETE', '/api/stems/engine'),
autoGridBatch: (trackIds: string[], replaceExisting: boolean) =>
send<JobStatus>('POST', '/api/tracks/grid/auto-batch', {
track_ids: trackIds,
+7 -2
View File
@@ -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 <button>, because browsers show no tooltip on one.
| { label: string; onClick: () => void; danger?: boolean; hint?: string; icon?: ReactNode; disabled?: boolean; title?: string }
| { label: string; submenu: MenuItem[] }
// Toggles in place and leaves the menu open, so several can be flipped in one go.
| { label: string; checked: boolean; onToggle: () => void }
@@ -189,9 +191,12 @@ function MenuPanel({
return (
<button
key={i}
disabled={item.disabled}
disabled={item.disabled && !item.title}
aria-disabled={item.disabled || undefined}
title={item.title}
onMouseEnter={() => setOpen(null)}
onClick={() => {
if (item.disabled) return
item.onClick()
onClose()
}}
@@ -0,0 +1,445 @@
import { createPortal } from 'react-dom'
import { useEffect, useMemo, useState, type ReactNode } from 'react'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import {
api,
type JobStatus,
type PlaylistNode,
type StemConvertOptions,
type StemEngineStatus,
type StemTarget,
} from '../api'
import { FolderPicker } from './FolderPicker'
/**
* Convert to Stems — one dialog (decided, see the stem-conversion discussion
* log): where the files go, what the collection does, a live preview, Convert.
*
* Every option is REMEMBERED (`stemConvert` in prefs) — unlike Add Files'
* ask-every-time — so Replace may be the preselected mode; that is why its
* consequence is stated in the option itself, not only at Save.
*
* When the engine is missing the dialog downloads it inline; closing it lets
* the download carry on (App shows it in the status bar via `onDownloading`).
*/
interface Remembered {
mode: 'replace' | 'destination'
destination: string
collection: 'repoint' | 'add'
playlist: 'none' | 'existing' | 'new'
playlistId: string
playlistName: string
}
const DEFAULTS: Remembered = {
mode: 'replace',
destination: '~/Music/Stems',
collection: 'repoint',
playlist: 'new',
playlistId: '',
playlistName: 'Stems',
}
/** Real-time factors (seconds of audio per second of work), measured on an M3
* Pro for MPS and CPU; the Windows figures are estimates until measured. */
const SPEED: Record<string, number> = {
'macos-arm64:gpu': 5.4,
'macos-arm64:cpu': 1.2,
'windows-x64-cuda:gpu': 8,
'windows-x64-cuda:cpu': 0.8,
'windows-x64-cpu:cpu': 0.8,
}
export function size(bytes: number): string {
if (bytes >= 1e9) return `${(bytes / 1e9).toFixed(1)} GB`
if (bytes >= 1e6) return `${Math.round(bytes / 1e6)} MB`
return `${Math.max(1, Math.round(bytes / 1e3))} kB`
}
function duration(seconds: number): string {
const m = Math.round(seconds / 60)
if (m < 1) return 'under a minute'
if (m < 90) return `${m} min`
return `${(seconds / 3600).toFixed(1)} h`
}
function flatten(nodes: PlaylistNode[], path = ''): { id: string; label: string }[] {
return nodes.flatMap((n) => [
...(n.can_add_tracks && n.kind === 'playlist' ? [{ id: n.id, label: path + n.name }] : []),
...flatten(n.children ?? [], `${path}${n.name} / `),
])
}
interface Props {
trackIds: string[]
onClose: () => void
/** The conversion job started — App tracks it in the status bar. */
onStarted: (job: JobStatus) => void
/** An engine download started — App shows it in the status bar. */
onDownloading: (job: JobStatus) => void
onError: (msg: string) => void
}
export function ConvertStemsDialog({ trackIds, onClose, onStarted, onDownloading, onError }: Props) {
const qc = useQueryClient()
const prefs = useQuery({ queryKey: ['prefs'], queryFn: api.getPrefs })
const [opts, setOpts] = useState<Remembered | null>(null)
const [browsing, setBrowsing] = useState(false)
const [showSkipped, setShowSkipped] = useState(false)
const [starting, setStarting] = useState(false)
const [target, setTarget] = useState<StemTarget | null>(null)
useEffect(() => {
if (opts || !prefs.isSuccess) return
const saved = (prefs.data as { stemConvert?: Partial<Remembered> }).stemConvert
setOpts({ ...DEFAULTS, ...(saved ?? {}) })
}, [prefs.isSuccess, prefs.data, opts])
const engine = useQuery({ queryKey: ['stem-engine'], queryFn: api.stemEngine })
const installJobId = engine.data?.install_job ?? null
const install = useQuery({
queryKey: ['job', installJobId],
queryFn: () => api.job(installJobId!),
enabled: !!installJobId,
refetchInterval: (q) => (q.state.data && q.state.data.state !== 'running' ? false : 400),
})
useEffect(() => {
if (install.data && install.data.state !== 'running') {
if (install.data.state === 'failed') onError(install.data.error || 'The download failed')
qc.invalidateQueries({ queryKey: ['stem-engine'] })
}
}, [install.data, qc, onError])
const playlists = useQuery({ queryKey: ['playlists'], queryFn: api.playlists })
const choices = useMemo(() => flatten(playlists.data ?? []), [playlists.data])
const body: StemConvertOptions | null = opts && {
mode: opts.mode,
destination: opts.mode === 'destination' ? opts.destination : null,
collection: opts.mode === 'replace' ? 'repoint' : opts.collection,
playlist_id:
opts.mode === 'destination' && opts.collection === 'add' && opts.playlist === 'existing'
? opts.playlistId || null
: null,
new_playlist:
opts.mode === 'destination' && opts.collection === 'add' && opts.playlist === 'new'
? opts.playlistName.trim() || 'Stems'
: null,
}
const preview = useQuery({
queryKey: ['stem-preview', trackIds, body],
queryFn: () => api.stemPreview(trackIds, body!),
enabled: !!body,
staleTime: 0,
gcTime: 0,
})
const set = (patch: Partial<Remembered>) => setOpts((o) => (o ? { ...o, ...patch } : o))
const st: StemEngineStatus | undefined = engine.data
const ready = !!st?.installed && !!st?.weights.installed
const downloading = install.data?.state === 'running'
const offered = st?.offered_targets ?? []
const chosenTarget = target ?? (offered.includes('windows-x64-cuda') ? 'windows-x64-cuda' : offered[0])
const needBytes =
(st?.installed ? 0 : (chosenTarget && st?.download_sizes[chosenTarget]) || 0) +
(st?.weights.installed ? 0 : st?.weights.size ?? 0)
const plan = preview.data
const n = plan?.convert.length ?? 0
const allReused = !!plan && plan.convert.every((c) => c.reuse)
const device = (st?.device ?? 'auto') === 'cpu' ? 'cpu' : 'gpu'
const rtf = st?.installed ? SPEED[`${st.installed.target}:${device}`] ?? SPEED[`${st.installed.target}:cpu`] : null
const canConvert = !!plan && n > 0 && !plan.blocked && (ready || allReused) && !starting
// With nothing to convert the reasons ARE the answer: show them without a click.
const skippedOpen = showSkipped || (!!plan && n === 0 && plan.skipped.length > 0)
const whyNot = !plan
? undefined
: n === 0
? 'Nothing to convert — see why each track is skipped'
: plan.blocked
? plan.blocked
: !ready && !allReused
? 'The stem engine is not installed yet'
: undefined
const download = async () => {
try {
const job = await api.stemEngineInstall(chosenTarget ?? null)
onDownloading(job)
qc.invalidateQueries({ queryKey: ['stem-engine'] })
} catch (e) {
onError((e as Error).message)
}
}
const convert = async () => {
if (!body || !opts) return
setStarting(true)
try {
api.patchPrefs({ stemConvert: opts }).then((p) => qc.setQueryData(['prefs'], p)).catch(() => {})
onStarted(await api.stemConvert(trackIds, body))
onClose()
} catch (e) {
onError((e as Error).message)
setStarting(false)
}
}
const radio = (
name: string,
checked: boolean,
onPick: () => void,
label: string,
detail: ReactNode,
disabled = false,
) => (
<label
className={`flex gap-3 rounded-lg px-3 py-2 ${disabled ? 'opacity-40' : 'cursor-pointer'} ${
checked ? 'is-selected' : disabled ? '' : 'hover:bg-ink-850'
}`}
>
<input
type="radio"
name={name}
checked={checked}
disabled={disabled}
onChange={onPick}
className="mt-0.5 accent-accent"
/>
<span className="min-w-0 flex-1">
<span className="block text-text">{label}</span>
<span className="block text-xs text-faint">{detail}</span>
</span>
</label>
)
const count = trackIds.length
return createPortal(
<>
{browsing && opts && (
<FolderPicker value={opts.destination} onChange={(path) => set({ destination: path })} onClose={() => setBrowsing(false)} />
)}
<div
aria-modal="true"
className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4 backdrop-blur-[3px]"
onKeyDown={(e) => e.key === 'Escape' && !starting && onClose()}
>
<div className="flex max-h-[90vh] w-full max-w-lg flex-col overflow-hidden glass-overlay">
<div className="border-b border-line px-5 py-3">
<h2 className="text-sm font-semibold text-text">
Convert {count} track{count === 1 ? '' : 's'} to stems
</h2>
</div>
{!opts ? (
<div className="px-5 py-6 text-sm text-faint">Loading…</div>
) : (
<div className="min-h-0 flex-1 space-y-4 overflow-y-auto px-5 py-4 text-sm">
<section className="space-y-1">
<div className="px-1 text-[11px] font-semibold uppercase tracking-wider text-faint">Where</div>
{radio(
'stem-mode',
opts.mode === 'replace',
() => set({ mode: 'replace' }),
'Replace the originals',
<>
<span className="block">Track.mp3 becomes Track.stem.m4a, in the same folder.</span>
{opts.mode === 'replace' && (
<span className="mt-1 block text-gold">
Saving deletes the {n || ''} original file{n === 1 ? '' : 's'}
{plan?.original_bytes ? ` (${size(plan.original_bytes)})` : ''} for good — and any
other app or older collection version using them loses them. Discard keeps them.
</span>
)}
</>,
)}
{radio(
'stem-mode',
opts.mode === 'destination',
() => set({ mode: 'destination' }),
'Save to a folder',
<span className="flex items-center gap-2">
<span className="min-w-0 truncate font-mono" dir="rtl" title={opts.destination}>
{`‎${opts.destination}‎`}
</span>
<button
onClick={(e) => {
e.preventDefault()
setBrowsing(true)
}}
className="shrink-0 text-accent hover:underline"
>
Change…
</button>
</span>,
)}
</section>
{opts.mode === 'destination' && (
<section className="space-y-1">
<div className="px-1 text-[11px] font-semibold uppercase tracking-wider text-faint">
In the collection
</div>
{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' && (
<div className="flex items-center gap-2 pl-10 text-xs">
<select
value={opts.playlist === 'existing' ? `pl:${opts.playlistId}` : opts.playlist}
onChange={(e) => {
const v = e.target.value
if (v.startsWith('pl:')) set({ playlist: 'existing', playlistId: v.slice(3) })
else set({ playlist: v as Remembered['playlist'] })
}}
className="well rounded-md px-2 py-1 text-text"
>
<option value="none">No playlist</option>
<option value="new">New playlist…</option>
{choices.map((c) => (
<option key={c.id} value={`pl:${c.id}`}>
{c.label}
</option>
))}
</select>
{opts.playlist === 'new' && (
<input
value={opts.playlistName}
onChange={(e) => set({ playlistName: e.target.value })}
className="well min-w-0 flex-1 rounded-md px-2 py-1 text-text"
placeholder="Playlist name"
/>
)}
</div>
)}
</section>
)}
{!ready && st && (
<section className="rounded-lg well px-3 py-3 text-xs">
{!st.supported ? (
<div className="text-pink">There is no stem engine for this computer.</div>
) : downloading && install.data ? (
<div className="space-y-2">
<div className="text-text">{install.data.message || 'Downloading…'}</div>
<div className="h-2 overflow-hidden rounded-full bg-ink-800">
<div
className="h-full bg-accent transition-[width] duration-200"
style={{ width: `${install.data.total ? (install.data.done / install.data.total) * 100 : 0}%` }}
/>
</div>
<div className="text-faint">
{size(install.data.done)} of {size(install.data.total || needBytes)} · closing this keeps it
going
</div>
</div>
) : !st.manifest_available && !st.installed ? (
<div className="text-muted">
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.
</div>
) : (
<div className="space-y-2">
<div className="text-text">
The stem engine is a one-time download ({size(needBytes)}).
</div>
{offered.length > 1 && !st.installed && (
<div className="space-y-1">
{offered.map((t) => (
<label key={t} className="flex items-center gap-2 text-muted">
<input
type="radio"
name="stem-target"
checked={chosenTarget === t}
onChange={() => setTarget(t)}
className="accent-accent"
/>
{t === 'windows-x64-cuda'
? `Use the ${st.nvidia?.name ?? 'NVIDIA'} GPU (${size(st.download_sizes[t] ?? 0)}) — much faster`
: `Processor only (${size(st.download_sizes[t] ?? 0)})`}
</label>
))}
</div>
)}
<button onClick={download} className="btn-primary rounded-full px-3 py-1 text-xs font-semibold">
Download
</button>
</div>
)}
</section>
)}
{preview.isError && <div className="text-pink">{(preview.error as Error).message}</div>}
{plan && (
<section className="space-y-1 text-xs">
<div className="text-text">
{n} to convert
{plan.skipped.length > 0 && (
<>
{' · '}
<button onClick={() => setShowSkipped((v) => !v)} className="text-muted hover:text-text">
{plan.skipped.length} skipped {skippedOpen ? '▾' : '▸'}
</button>
</>
)}
</div>
{skippedOpen && (
<ul className="max-h-32 space-y-0.5 overflow-y-auto rounded-md well px-3 py-2">
{plan.skipped.map((s) => (
<li key={s.track_id} className="flex gap-2">
<span className="min-w-0 flex-1 truncate text-muted" title={s.title}>
{s.title}
</span>
<span className="shrink-0 text-faint">{s.reason}</span>
</li>
))}
</ul>
)}
{n > 0 && (
<div className="text-faint">
{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
</div>
)}
{plan.blocked && <div className="text-pink">{plan.blocked}</div>}
</section>
)}
</div>
)}
<div className="flex justify-end gap-2 border-t border-line px-5 py-3">
<button
onClick={onClose}
disabled={starting}
className="btn-glass rounded-full px-3 py-1.5 text-sm text-muted hover:text-text"
>
{downloading ? 'Close' : 'Cancel'}
</button>
<button
disabled={!canConvert}
onClick={convert}
title={whyNot}
className="btn-primary rounded-full px-3 py-1.5 text-sm font-semibold disabled:opacity-40"
>
{starting ? 'Starting…' : `Convert${n ? ` ${n}` : ''}`}
</button>
</div>
</div>
</div>
</>,
document.body,
)
}
+13
View File
@@ -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) {
<span>{warning}</span>
</div>
)}
{/* 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 && (
<div className="mb-2 flex gap-1.5 rounded-xl bg-gold/10 px-2.5 py-1.5 text-[11px] leading-snug text-gold">
<Icon name="warning" size={13} className="mt-px shrink-0" />
<span>
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.
</span>
</div>
)}
<div className="flex items-stretch gap-2">
<button
disabled={!dirty || save.isPending}
+14 -1
View File
@@ -1,5 +1,6 @@
import { useEffect, useRef, useState } from 'react'
import { ShortcutsDialog } from './ShortcutsDialog'
import { StemsSettings } from './StemsSettings'
interface Props {
onOpenPathMapping: () => void
@@ -8,11 +9,12 @@ interface Props {
}
/** Overflow menu for low-frequency, collection-level settings. Currently holds
* path remapping and the shortcut list; the natural home for future advanced
* path remapping, Stems and the shortcut list; the natural home for future advanced
* settings. The shortcuts dialog is owned here, since nothing else opens it. */
export function SettingsMenu({ onOpenPathMapping, up = false }: Props) {
const [open, setOpen] = useState(false)
const [showShortcuts, setShowShortcuts] = useState(false)
const [showStems, setShowStems] = useState(false)
const ref = useRef<HTMLDivElement>(null)
useEffect(() => {
@@ -66,6 +68,16 @@ export function SettingsMenu({ onOpenPathMapping, up = false }: Props) {
Point the collection at moved or relocated files
</span>
</button>
<button
onClick={() => {
setShowStems(true)
setOpen(false)
}}
className={item}
>
<span className="text-sm text-text">Stems…</span>
<span className="text-[11px] text-faint">The stem engine, device and conversion defaults</span>
</button>
<button
onClick={() => {
setShowShortcuts(true)
@@ -79,6 +91,7 @@ export function SettingsMenu({ onOpenPathMapping, up = false }: Props) {
</div>
)}
{showShortcuts && <ShortcutsDialog onClose={() => setShowShortcuts(false)} />}
{showStems && <StemsSettings onClose={() => setShowStems(false)} />}
</div>
)
}
+6 -1
View File
@@ -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({
<div className="ml-auto flex min-w-0 items-center gap-2">
<span className="shrink-0 tabular-nums text-text">
{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}`)}
</span>
<span className="well h-1.5 w-32 shrink-0 overflow-hidden rounded-full">
<span
@@ -0,0 +1,55 @@
import { createPortal } from 'react-dom'
import { useEffect } from 'react'
import type { StemBatchResult } from '../api'
/**
* The Details behind a finished conversion's toast: every track that was
* skipped or failed, with its reason (decided: a long skip list must not vanish
* into a toast).
*/
export function StemReportDialog({ result, onClose }: { result: StemBatchResult; onClose: () => 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(
<div
aria-modal="true"
className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4 backdrop-blur-[3px]"
onClick={onClose}
>
<div className="flex max-h-[80vh] w-full max-w-lg flex-col overflow-hidden glass-overlay" onClick={(e) => e.stopPropagation()}>
<div className="border-b border-line px-5 py-3 text-sm font-semibold text-text">
{n} converted to stems · {result.skipped.length} skipped · {result.failed.length} failed
</div>
<ul className="min-h-0 flex-1 space-y-1 overflow-y-auto px-5 py-3 text-xs">
{rows.map((r) => (
<li key={`${r.failed}-${r.track_id}`} className="flex gap-3">
<span className="min-w-0 flex-1 truncate text-text" title={r.title}>
{r.title}
</span>
<span className={`shrink-0 ${r.failed ? 'text-pink' : 'text-faint'}`}>
{r.failed ? 'failed: ' : ''}
{r.reason}
</span>
</li>
))}
</ul>
<div className="flex items-center justify-between gap-2 border-t border-line px-5 py-3">
<span className="text-xs text-faint">{n ? 'Save to keep the converted tracks.' : ''}</span>
<button onClick={onClose} className="btn-glass rounded-full px-3 py-1.5 text-sm text-muted hover:text-text">
Close
</button>
</div>
</div>
</div>,
document.body,
)
}
+248
View File
@@ -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<string | null>(null)
const [picking, setPicking] = useState<null | 'engine' | 'weights'>(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<unknown>) => {
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 && (
<FolderPicker
value=""
onChange={(path) => void act(() => api.stemSideload(path, picking))}
onClose={() => setPicking(null)}
/>
)}
<div
aria-modal="true"
className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-6 backdrop-blur-[3px]"
onClick={onClose}
>
<div
className="flex max-h-[85vh] w-full max-w-lg flex-col overflow-hidden glass-overlay"
onClick={(e) => e.stopPropagation()}
>
<div className="flex items-center justify-between border-b border-line px-5 py-3">
<h2 className="text-sm font-semibold text-text">Stems</h2>
<button onClick={onClose} className="rounded px-1.5 text-faint hover:text-text" aria-label="Close">
×
</button>
</div>
<div className="min-h-0 flex-1 space-y-5 overflow-y-auto px-5 py-4 text-sm">
<section className="space-y-2">
<h3 className="text-[11px] font-semibold uppercase tracking-wider text-faint">Stem engine</h3>
{!st ? (
<div className="text-faint">Loading…</div>
) : !st.supported ? (
<div className="text-muted">There is no stem engine for this computer.</div>
) : (
<>
<div className="text-muted">
{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'}
</div>
{downloading && install.data && (
<div className="space-y-1">
<div className="h-2 overflow-hidden rounded-full well">
<div
className="h-full bg-accent transition-[width] duration-200"
style={{ width: `${install.data.total ? (install.data.done / install.data.total) * 100 : 0}%` }}
/>
</div>
<div className="text-xs text-faint">
{install.data.message} {size(install.data.done)} of {size(install.data.total)}
</div>
</div>
)}
<div className="flex flex-wrap gap-2">
{!(st.installed && st.weights.installed) && !downloading &&
st.offered_targets.map((t) => (
<button
key={t}
disabled={busy || !st.manifest_available}
onClick={() => void act(() => api.stemEngineInstall(t))}
className="btn-primary rounded-full px-3 py-1 text-xs font-semibold disabled:opacity-40"
>
Download ({targetLabel(t)},{' '}
{size((st.installed ? 0 : st.download_sizes[t] ?? 0) + (st.weights.installed ? 0 : st.weights.size))})
</button>
))}
<button
disabled={busy || downloading}
onClick={() => setPicking('engine')}
className="btn-glass rounded-full px-3 py-1 text-xs text-muted hover:text-text disabled:opacity-40"
title="A folder holding the engine file(s) downloaded from the release page"
>
Install engine from a folder…
</button>
<button
disabled={busy || downloading}
onClick={() => setPicking('weights')}
className="btn-glass rounded-full px-3 py-1 text-xs text-muted hover:text-text disabled:opacity-40"
title="A folder holding htdemucs_ft.yaml and its four .safetensors files"
>
Install model from a folder…
</button>
{(st.installed || st.weights.installed) && (
<button
disabled={busy || downloading}
onClick={async () => {
const ok = await askConfirm({
title: 'Remove the stem engine?',
body: 'The engine and its model are deleted from this computer. Converting again needs the download.',
confirmLabel: 'Remove',
})
if (ok) void act(api.stemEngineRemove)
}}
className="rounded-full px-3 py-1 text-xs text-faint hover:text-pink disabled:opacity-40"
>
Remove…
</button>
)}
</div>
{!st.manifest_available && !st.installed && (
<div className="text-xs text-faint">The download cannot be reached right now.</div>
)}
</>
)}
</section>
<section className="space-y-2">
<h3 className="text-[11px] font-semibold uppercase tracking-wider text-faint">Compute device</h3>
<div className="flex gap-2">
{[
['auto', 'Automatic'],
['gpu', 'GPU'],
['cpu', 'Processor only'],
].map(([value, label]) => (
<button
key={value}
onClick={() => void setDevice(value)}
className={`rounded-full px-3 py-1 text-xs ${
device === value ? 'is-selected text-text' : 'btn-glass text-muted hover:text-text'
}`}
>
{label}
</button>
))}
</div>
<div className="text-xs text-faint">
Automatic uses the fastest available. The GPU is several times faster; without one, conversion runs on
the processor.
</div>
</section>
<section className="space-y-1">
<h3 className="text-[11px] font-semibold uppercase tracking-wider text-faint">Conversion defaults</h3>
<div className="text-xs text-muted">
{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'}
</div>
<div className="text-xs text-faint">The Convert to Stems dialog remembers what you chose last.</div>
{defaults && (
<button
onClick={() =>
api.patchPrefs({ stemConvert: null }).then((p) => qc.setQueryData(['prefs'], p))
}
className="text-xs text-accent hover:underline"
>
Reset to Replace
</button>
)}
</section>
<section className="space-y-1">
<h3 className="text-[11px] font-semibold uppercase tracking-wider text-faint">Originals awaiting Save</h3>
<div className="text-xs text-muted">
{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.'}
</div>
</section>
{error && <div className="text-xs text-pink">{error}</div>}
</div>
</div>
</div>
</>,
document.body,
)
}
+14 -1
View File
@@ -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<ToastMsg['kind'], string> = {
@@ -16,7 +18,7 @@ const KIND_CLS: Record<ToastMsg['kind'], string> = {
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. */}
<span className={`h-2 w-2 shrink-0 rounded-full ${KIND_CLS[toast.kind]}`} />
{toast.text}
{toast.action && (
<button
onClick={() => {
toast.action!.onClick()
onClose()
}}
className="shrink-0 rounded-full px-2 py-0.5 text-xs font-semibold text-accent hover:bg-ink-800"
>
{toast.action.label}
</button>
)}
</div>
</div>,
document.body,