Split any YouTube song into stems
TypeScript
Ship v0.1.0: app icon, Windows support, bundled ffmpeg, GitHub Actions releases
Daniel Ravina9b72fb074319
diff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlnew file mode 100644index 0000000..ec03072--- /dev/null+++ b/.github/workflows/release.yml@@ -0,0 +1,75 @@+name: release++on:+ push:+ tags:+ - 'v*'+ workflow_dispatch:++permissions:+ contents: write++jobs:+ build:+ strategy:+ fail-fast: false+ matrix:+ include:+ - os: macos-latest+ platform: mac+ - os: windows-latest+ platform: win+ runs-on: ${{ matrix.os }}+ steps:+ - name: Checkout+ uses: actions/checkout@v4++ - name: Setup Node 20+ uses: actions/setup-node@v4+ with:+ node-version: 20++ - name: Install dependencies+ id: install+ run: npm ci+ continue-on-error: true++ - name: Install dependencies (fallback)+ if: steps.install.outcome == 'failure'+ run: npm install++ - name: Fetch ffmpeg (mac)+ if: matrix.platform == 'mac'+ run: bash scripts/fetch-ffmpeg.sh++ - name: Fetch ffmpeg (win)+ if: matrix.platform == 'win'+ shell: powershell+ run: powershell -ExecutionPolicy Bypass -File scripts/fetch-ffmpeg.ps1++ - name: Build app bundles+ run: npx electron-vite build++ - name: Package (release)+ if: startsWith(github.ref, 'refs/tags/v')+ env:+ GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}+ CSC_IDENTITY_AUTO_DISCOVERY: 'false'+ run: npx electron-builder --${{ matrix.platform }} --publish always++ - name: Package (on demand)+ if: github.event_name == 'workflow_dispatch'+ env:+ CSC_IDENTITY_AUTO_DISCOVERY: 'false'+ run: npx electron-builder --${{ matrix.platform }} --publish never++ - name: Upload artifacts+ if: github.event_name == 'workflow_dispatch'+ uses: actions/upload-artifact@v4+ with:+ name: stemkit-${{ matrix.platform }}+ path: |+ release/*.dmg+ release/*.exe+ release/*.zip+ if-no-files-found: errordiff --git a/.gitignore b/.gitignoreindex 2aece7d..7b003b9 100644--- a/.gitignore+++ b/.gitignore@@ -1,5 +1,6 @@node_modulesoutrelease+extras*.log.DS_Storediff --git a/README.md b/README.mdindex 4ac8072..e5081cd 100644--- a/README.md+++ b/README.md@@ -1,53 +1,74 @@# StemKit-Split any YouTube song into **vocals / drums / bass / other** — right on your Mac.-The video plays at the top (muted), perfectly synced local stems play underneath.+Split any YouTube song into **vocals / drums / bass / other / guitar / piano** — right on your machine.+The video plays in a corner (muted), perfectly synced local stems play underneath — and the audio is the boss.- + ## Features-- Paste a YouTube URL → get 4 separated stems-- Video and stems stay in sync (drift-corrected at 60 Hz)+- Search YouTube built-in (no API keys) or paste a link+- Pick instruments individually — the right separation engine is chosen for you+- Audio-leads sync engine: seeks are instant, video follows- One-click presets: **All · Karaoke · Acapella · Drums + Bass**-- Per-stem mute, solo, volume, waveform with click-to-seek-- Persistent library — reopen any song instantly-- Everything runs locally: separation uses Meta's `htdemucs` via Apple MPS acceleration+- Per-stem mute/solo/volume, waveforms with click-to-seek+- Parallel background splitting with live progress+- Export any stem (or all) as WAV+- Everything local: `htdemucs` via Apple MPS / CPU, bundled ffmpeg-## Requirements+## Download++Grab installers from [Releases](https://github.com/danielravina/stemkit/releases):+- **macOS** (Apple Silicon): `StemKit-x.y.z-mac-arm64.dmg`+- **Windows**: `StemKit-Setup-x.y.z.exe` (installer) or portable `.zip`++First launch creates a private Python environment and downloads the separation engine (~2 GB, one time) plus model weights (~80 MB). ffmpeg is bundled — nothing else to install.++> Unsigned builds: macOS requires right-click → Open on first run; Windows SmartScreen shows a warning.-- macOS (Apple Silicon recommended)-- Python 3.9+ (native arm64 preferred; auto-detected)-- ffmpeg (`brew install ffmpeg`)+## Requirements-First launch installs the engine into a private venv (~2 GB, one time) and downloads the model (~80 MB).+- **macOS 12+** (Apple Silicon) or **Windows 10/11** (x64)+- Python 3.9+ available on PATH or in a standard install location (auto-detected)+- Node.js 20+ only for building from source## Develop```bashnpm install-npm run dev # launch the app with hot reload+npm run dev```-## Package+Node version mismatch? `npm run *` scripts auto-relaunch with a suitable Node (nvm / nvm-windows).++## Build & release```bash-npm run dist # builds dmg into release/+bash scripts/fetch-ffmpeg.sh # mac (one time)+powershell scripts/fetch-ffmpeg.ps1 # windows (one time)++npm run dist # mac dmg -> release/+npm run dist:win # windows nsis+zip -> release/+npm run dist:all # both (on the matching OS)```+Releases are built by GitHub Actions:+- push a tag `v*` → binaries attach to a draft GitHub Release+- `workflow_dispatch` ("Run workflow") → on-demand artifacts on the run page+## How it works```-YouTube URL ──► yt-dlp (venv) ──► ffmpeg ──► demucs htdemucs ──► stems/*.wav- │-Electron renderer ◄── IPC progress ──┘-video iframe (muted) + Web Audio API stem playback, master clock = YouTube time+YouTube URL ──► yt-dlp (+JS runtime) ──► bundled ffmpeg ──► demucs htdemucs ──► stems/*.wav+ │+Electron renderer ◄──── IPC events ─────┘+video iframe (muted) + Web Audio stem playback · master clock = the audio itself```## Notes-- Downloading audio from YouTube is against their ToS for public-facing products — keep this for personal use.-- yt-dlp breaks occasionally when YouTube changes things. If a video fails to load, the error dialog offers a one-click update.+- Downloading audio from YouTube violates their ToS for public products — keep this personal.+- yt-dlp breaks occasionally when YouTube changes things; the error dialog offers a one-click update (updates `yt-dlp` + the challenge solver together).## Layout@@ -56,5 +77,6 @@ src/main Electron main process (pipeline, env bootstrap, library)src/preload IPC bridgesrc/renderer React UI (player, sync engine, waveforms)python/ separate.py — demucs wrapper with JSON progress output+scripts/ node runner, ffmpeg fetchers+build/ icon sources```-# stemkitdiff --git a/build/icon.png b/build/icon.pngnew file mode 100644index 0000000..b29965aBinary files /dev/null and b/build/icon.png differdiff --git a/build/icon.svg b/build/icon.svgnew file mode 100644index 0000000..a63ee13--- /dev/null+++ b/build/icon.svg@@ -0,0 +1,36 @@+<svg width="1024" height="1024" viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">+ <defs>+ <linearGradient id="bg" x1="0" y1="0" x2="1024" y2="1024" gradientUnits="userSpaceOnUse">+ <stop offset="0" stop-color="#7C3AED"/>+ <stop offset="0.55" stop-color="#5B21B6"/>+ <stop offset="1" stop-color="#065F46"/>+ </linearGradient>+ <linearGradient id="sheen" x1="0" y1="0" x2="0" y2="1024" gradientUnits="userSpaceOnUse">+ <stop offset="0" stop-color="#ffffff" stop-opacity="0.18"/>+ <stop offset="0.45" stop-color="#ffffff" stop-opacity="0"/>+ </linearGradient>+ <linearGradient id="barHot" x1="0" y1="0" x2="1" y2="0" gradientUnits="objectBoundingBox">+ <stop offset="0" stop-color="#C4B5FD"/>+ <stop offset="1" stop-color="#EDE9FE"/>+ </linearGradient>+ </defs>++ <rect x="0" y="0" width="1024" height="1024" rx="232" fill="url(#bg)"/>+ <rect x="0" y="0" width="1024" height="1024" rx="232" fill="url(#sheen)"/>++ <g stroke-linecap="round">+ <line x1="212" y1="372" x2="212" y2="652" stroke="#A78BFA" stroke-width="58" opacity="0.55"/>+ <line x1="342" y1="288" x2="342" y2="736" stroke="#F87171" stroke-width="58"/>+ <line x1="472" y1="352" x2="472" y2="672" stroke="#60A5FA" stroke-width="58"/>+ <line x1="602" y1="252" x2="602" y2="772" stroke="#FBBF24" stroke-width="58"/>+ <line x1="732" y1="404" x2="732" y2="620" stroke="#34D399" stroke-width="58" opacity="0.9"/>+ <line x1="842" y1="468" x2="842" y2="556" stroke="#E7E7EF" stroke-width="44" opacity="0.5"/>+ </g>++ <g stroke="#0B0B10" stroke-width="14" opacity="0.22" stroke-linecap="round">+ <line x1="342" y1="180" x2="342" y2="238"/>+ <line x1="342" y1="786" x2="342" y2="844"/>+ <line x1="602" y1="160" x2="602" y2="202"/>+ <line x1="602" y1="822" x2="602" y2="864"/>+ </g>+</svg>diff --git a/electron-builder.yml b/electron-builder.ymlindex 6d3c7e8..11d9357 100644--- a/electron-builder.yml+++ b/electron-builder.yml@@ -4,14 +4,30 @@ directories:output: releasefiles:- out/**/*+asar: true+artifactName: ${productName}-${version}-${os}-${arch}.${ext}extraResources:- from: pythonto: python-asar: truemac:category: public.app-category.music+ icon: build/icon.png+ identity: nulltarget:- target: dmgarch:- arm64- identity: null+ extraResources:+ - from: extras/ffmpeg-mac/ffmpeg+ to: ffmpeg/ffmpeg+win:+ icon: build/icon.png+ target:+ - target: nsis+ - target: zip+ extraResources:+ - from: extras/ffmpeg-win/ffmpeg.exe+ to: ffmpeg/ffmpeg.exe+nsis:+ oneClick: true+ perMachine: falsediff --git a/package.json b/package.jsonindex 04bf2c9..52df501 100644--- a/package.json+++ b/package.json@@ -15,7 +15,9 @@"typecheck:node": "node scripts/run.cjs typecheck:node","typecheck:web": "node scripts/run.cjs typecheck:web","typecheck": "node scripts/run.cjs typecheck",- "dist": "node scripts/run.cjs dist"+ "dist": "node scripts/run.cjs dist",+ "dist:win": "node scripts/run.cjs dist:win",+ "dist:all": "node scripts/run.cjs dist:all"},"dependencies": {},"devDependencies": {diff --git a/python/separate.py b/python/separate.pyindex 68e1393..dcf74a3 100644--- a/python/separate.py+++ b/python/separate.py@@ -58,6 +58,7 @@ def main():parser.add_argument("--device", default="auto")parser.add_argument("--shifts", type=int, default=1)parser.add_argument("--overlap", type=float, default=0.25)+ parser.add_argument("--only", default="")args = parser.parse_args()import torch@@ -160,10 +161,22 @@ def main():import os+ wanted = None+ if args.only:+ wanted = [s.strip() for s in args.only.split(",") if s.strip()]+ unknown = [s for s in wanted if s not in model.sources]+ if unknown:+ fail(f"unknown stems requested: {', '.join(unknown)}")+ if not wanted:+ fail("no valid stems requested")+ emit(type="progress", stage="separate", pct=0, message=f"writing {len(wanted)} stems")+os.makedirs(args.out, exist_ok=True)out_cpu = sources[0].cpu().numpy()written = []for i, name in enumerate(model.sources):+ if wanted is not None and name not in wanted:+ continuepath = os.path.join(args.out, f"{name}.wav")save_wav(path, out_cpu[i], sr)written.append(name)diff --git a/scripts/fetch-ffmpeg.ps1 b/scripts/fetch-ffmpeg.ps1new file mode 100644index 0000000..543e250--- /dev/null+++ b/scripts/fetch-ffmpeg.ps1@@ -0,0 +1,31 @@+$ErrorActionPreference = "Stop"++$root = Split-Path -Parent $PSScriptRoot+$out = Join-Path $root "extras\ffmpeg-win"+New-Item -ItemType Directory -Force -Path $out | Out-Null++$existing = Join-Path $out "ffmpeg.exe"+if (Test-Path $existing) {+ Write-Host "ffmpeg already present: $existing"+ & $existing -version | Select-Object -First 1+ exit 0+}++$zip = Join-Path $env:TEMP "ffmpeg-essentials.zip"+$tmpExtract = Join-Path $env:TEMP "ffmpeg-extract"++Write-Host "downloading static ffmpeg for Windows x64..."+Invoke-WebRequest -Uri "https://www.gyan.dev/ffmpeg/builds/ffmpeg-release-essentials.zip" -OutFile $zip++if (Test-Path $tmpExtract) { Remove-Item -Recurse -Force $tmpExtract }+Expand-Archive -Path $zip -DestinationPath $tmpExtract -Force++$exe = Get-ChildItem $tmpExtract -Recurse -Filter "ffmpeg.exe" | Select-Object -First 1+if (-not $exe) { throw "ffmpeg.exe not found inside archive" }++Copy-Item $exe.FullName $existing -Force+Remove-Item -Recurse -Force $tmpExtract+Remove-Item -Force $zip++& $existing -version | Select-Object -First 1+Write-Host "saved to $existing"diff --git a/scripts/fetch-ffmpeg.sh b/scripts/fetch-ffmpeg.shnew file mode 100755index 0000000..e6325d3--- /dev/null+++ b/scripts/fetch-ffmpeg.sh@@ -0,0 +1,29 @@+#!/usr/bin/env bash+set -euo pipefail++ROOT="$(cd "$(dirname "$0")/.." && pwd)"+OS="$(uname -s)"+mkdir -p "$ROOT/extras"++if [[ "$OS" == "Darwin" ]]; then+ OUT="$ROOT/extras/ffmpeg-mac"+ if [[ -x "$OUT/ffmpeg" ]]; then+ echo "ffmpeg already present: $OUT/ffmpeg"+ "$OUT/ffmpeg" -version | head -1+ exit 0+ fi+ mkdir -p "$OUT"+ echo "downloading static ffmpeg for macOS..."+ curl -fsSL -o "$ROOT/extras/ffmpeg-mac.zip" "https://evermeet.cx/ffmpeg/get/ffmpeg/zip"+ unzip -oq "$ROOT/extras/ffmpeg-mac.zip" -d "$OUT"+ rm -f "$ROOT/extras/ffmpeg-mac.zip"+ chmod +x "$OUT/ffmpeg"+ "$OUT/ffmpeg" -version | head -1+ echo "saved to $OUT/ffmpeg"+elif [[ "$OS" == "MINGW"* || "$OS" == "MSYS"* || "$OS" == "CYGWIN"* ]]; then+ echo "on Windows, run instead: powershell -ExecutionPolicy Bypass -File scripts/fetch-ffmpeg.ps1"+ exit 1+else+ echo "unsupported OS: $OS"+ exit 1+fidiff --git a/scripts/run.cjs b/scripts/run.cjsindex c275f92..c415839 100644--- a/scripts/run.cjs+++ b/scripts/run.cjs@@ -1,9 +1,11 @@#!/usr/bin/env nodeconst { spawnSync } = require('child_process')const fs = require('fs')+const os = require('os')const path = require('path')const ROOT = path.join(__dirname, '..')+const IS_WIN = process.platform === 'win32'function readRequiredMajor() {try {@@ -31,17 +33,42 @@ function cmpSemver(a, b) {return 0}-function findNvmNode(requiredMajor) {- const rootDir = path.join(process.env.HOME || '', '.nvm', 'versions', 'node')+function findNode(requiredMajor) {+ const candidates = []+ if (IS_WIN) {+ const programFiles = process.env['ProgramFiles'] || 'C:\\Program Files'+ candidates.push(path.join(programFiles, 'nodejs', 'node.exe'))+ const nvmHome =+ process.env.NVM_HOME || path.join(process.env.APPDATA || path.join(os.homedir(), 'AppData', 'Roaming'), 'nvm')+ try {+ for (const ver of fs.readdirSync(nvmHome)) {+ if (majorOf(ver) < requiredMajor) continue+ const nodeBin = path.join(nvmHome, ver, 'node.exe')+ if (fs.existsSync(nodeBin)) candidates.push(nodeBin)+ }+ } catch {}+ } else {+ candidates.push('/opt/homebrew/bin/node', '/usr/local/bin/node')+ const nvmRoot = path.join(os.homedir(), '.nvm', 'versions', 'node')+ try {+ for (const ver of fs.readdirSync(nvmRoot)) {+ if (majorOf(ver) < requiredMajor) continue+ const nodeBin = path.join(nvmRoot, ver, 'bin', 'node')+ if (fs.existsSync(nodeBin)) candidates.push(nodeBin)+ }+ } catch {}+ }+let best = null- try {- for (const ver of fs.readdirSync(rootDir)) {- if (majorOf(ver) < requiredMajor) continue- const nodeBin = path.join(rootDir, ver, 'bin', 'node')- if (!fs.existsSync(nodeBin)) continue- if (!best || cmpSemver(ver, best.version) > 0) best = { version: ver, nodeBin }- }- } catch {}+ for (const nodeBin of candidates) {+ if (!fs.existsSync(nodeBin)) continue+ try {+ const out = spawnSync(nodeBin, ['-v'], { encoding: 'utf8' })+ const version = cleanVersion((out.stdout || '').trim())+ if (majorOf(version) < requiredMajor) continue+ if (!best || cmpSemver(version, best.version) > 0) best = { version, nodeBin }+ } catch {}+ }return best}@@ -54,16 +81,21 @@ const STEPS = {],'typecheck:node': [['tsc', '--noEmit', '-p', 'tsconfig.node.json']],'typecheck:web': [['tsc', '--noEmit', '-p', 'tsconfig.web.json']],- dist: [['electron-vite', 'build'], ['electron-builder', '--mac']]+ dist: [['electron-vite', 'build'], ['electron-builder', '--mac']],+ 'dist:win': [['electron-vite', 'build'], ['electron-builder', '--win']],+ 'dist:all': [['electron-vite', 'build'], ['electron-builder', '--mac', '--win']]}function resolveBin(name) {- const local = path.join(ROOT, 'node_modules', '.bin', name)+ const ext = IS_WIN ? '.cmd' : ''+ const local = path.join(ROOT, 'node_modules', '.bin', name + ext)if (fs.existsSync(local)) return local- for (const dir of (process.env.PATH || '').split(':')) {+ for (const dir of (process.env.PATH || '').split(path.delimiter)) {if (!dir) continue- const candidate = path.join(dir, name)- if (fs.existsSync(candidate)) return candidate+ for (const suffix of IS_WIN ? ['.cmd', '.exe', ''] : ['']) {+ const candidate = path.join(dir, name + suffix)+ if (fs.existsSync(candidate)) return candidate+ }}console.error(`Cannot find ${name} — run npm install first`)process.exit(1)@@ -71,7 +103,11 @@ function resolveBin(name) {function runSteps(steps) {for (const [bin, ...args] of steps) {- const r = spawnSync(resolveBin(bin), args, { stdio: 'inherit' })+ const resolved = resolveBin(bin)+ const r = spawnSync(resolved, args, {+ stdio: 'inherit',+ shell: IS_WIN && resolved.toLowerCase().endsWith('.cmd')+ })if (r.status !== 0) process.exit(r.status ?? 1)}}@@ -86,15 +122,15 @@ function main() {const required = readRequiredMajor()if (majorOf(process.versions.node) < required) {- const found = findNvmNode(required)+ const found = findNode(required)if (!found) {console.error(- `StemKit needs Node ${required}+ but you have ${process.versions.node}, and no matching nvm install was found.\nInstall one with: nvm install ${required}`+ `StemKit needs Node ${required}+ but you have ${process.versions.node}, and no matching Node install was found.\nInstall Node ${required} or newer from https://nodejs.org`)process.exit(1)}console.log(- `> StemKit needs Node ${required}+ (active: ${process.versions.node}) — using nvm ${found.version}`+ `> StemKit needs Node ${required}+ (active: ${process.versions.node}) — using ${found.version} at ${found.nodeBin}`)const r = spawnSync(found.nodeBin, [__filename, ...process.argv.slice(2)], {stdio: 'inherit'diff --git a/src/main/env.ts b/src/main/env.tsindex 1e01a8d..6710a0b 100644--- a/src/main/env.ts+++ b/src/main/env.ts@@ -31,16 +31,35 @@ export function userDataDir(): string {return app.getPath('userData')}+const IS_WIN = process.platform === 'win32'+const EXE = IS_WIN ? '.exe' : ''+const VENV_BIN = IS_WIN ? 'Scripts' : 'bin'+export function venvDir(): string {return join(userDataDir(), 'venv')}export function venvPython(): string {- return join(venvDir(), 'bin', 'python')+ return join(venvDir(), VENV_BIN, 'python' + EXE)}export function venvYtDlp(): string {- return join(venvDir(), 'bin', 'yt-dlp')+ return join(venvDir(), VENV_BIN, 'yt-dlp' + EXE)+}++function venvPip(): string {+ return join(venvDir(), VENV_BIN, 'pip' + EXE)+}++export function bundledFfmpeg(): string | null {+ const name = 'ffmpeg' + EXE+ const candidates = app.isPackaged+ ? [join(process.resourcesPath, 'ffmpeg', name)]+ : [join(app.getAppPath(), 'extras', IS_WIN ? 'ffmpeg-win' : 'ffmpeg-mac', name)]+ for (const c of candidates) {+ if (existsSync(c)) return c+ }+ return null}export function separateScript(): string {@@ -55,28 +74,48 @@ function cleanVersion(version: string): string {}async function detectJsRuntime(): Promise<void> {- const denoPaths = [- '/opt/homebrew/bin/deno',- '/usr/local/bin/deno',- join(homedir(), '.deno/bin/deno')- ]- for (const p of denoPaths) {+ const denoPaths = IS_WIN+ ? [+ join(homedir(), '.deno', 'bin', 'deno.exe'),+ join(process.env.LOCALAPPDATA ?? '', 'Programs', 'deno', 'deno.exe')+ ]+ : ['/opt/homebrew/bin/deno', '/usr/local/bin/deno', join(homedir(), '.deno/bin/deno')]+ for (const p of denoPaths.filter((p): p is string => !!p && p.length > 0)) {if (existsSync(p)) {state.jsRuntime = { kind: 'deno', path: p }return}}- const nodeCandidates = ['/opt/homebrew/bin/node', '/usr/local/bin/node']- const nvmRoot = join(homedir(), '.nvm/versions/node')- try {- for (const ver of readdirSync(nvmRoot)) {- const major = parseInt(cleanVersion(ver).split('.')[0], 10)- if (!Number.isNaN(major) && major >= 18) {- nodeCandidates.push(join(nvmRoot, ver, 'bin', 'node'))+ const nodeCandidates: string[] = []+ if (IS_WIN) {+ nodeCandidates.push(+ join(process.env['ProgramFiles'] ?? 'C:\\Program Files', 'nodejs', 'node.exe'),+ join(process.env['LOCALAPPDATA'] ?? '', 'Programs', 'nodejs', 'node.exe')+ )+ const nvmHome =+ process.env.NVM_HOME ??+ join(process.env.APPDATA ?? join(homedir(), 'AppData', 'Roaming'), 'nvm')+ try {+ for (const ver of readdirSync(nvmHome)) {+ const major = parseInt(cleanVersion(ver).split('.')[0], 10)+ if (!Number.isNaN(major) && major >= 18) {+ nodeCandidates.push(join(nvmHome, ver, 'node.exe'))+ }}- }- } catch {}+ } catch {}+ } else {+ nodeCandidates.push('/opt/homebrew/bin/node', '/usr/local/bin/node')+ const nvmRoot = join(homedir(), '.nvm/versions/node')+ try {+ for (const ver of readdirSync(nvmRoot)) {+ const major = parseInt(cleanVersion(ver).split('.')[0], 10)+ if (!Number.isNaN(major) && major >= 18) {+ nodeCandidates.push(join(nvmRoot, ver, 'bin', 'node'))+ }+ }+ } catch {}+ }let best: { path: string; version: string } | null = nullfor (const p of nodeCandidates) {@@ -108,6 +147,23 @@ export function ytDlpRuntimeArgs(): string[] {}function pyCandidates(): string[] {+ if (IS_WIN) {+ const localAppData = process.env.LOCALAPPDATA ?? join(homedir(), 'AppData', 'Local')+ const programFiles = process.env['ProgramFiles'] ?? 'C:\\Program Files'+ return [+ process.env.STEMKIT_PYTHON,+ join(localAppData, 'Programs', 'Python', 'Python312', 'python.exe'),+ join(localAppData, 'Programs', 'Python', 'Python311', 'python.exe'),+ join(localAppData, 'Programs', 'Python', 'Python310', 'python.exe'),+ join(localAppData, 'Programs', 'Python', 'Python39', 'python.exe'),+ join(programFiles, 'Python312', 'python.exe'),+ join(programFiles, 'Python311', 'python.exe'),+ join(programFiles, 'Python310', 'python.exe'),+ join(programFiles, 'Python39', 'python.exe'),+ join(localAppData, 'Microsoft', 'WindowsApps', 'python3.exe'),+ join(localAppData, 'Microsoft', 'WindowsApps', 'python.exe')+ ].filter((p): p is string => !!p)+ }const home = homedir()return [process.env.STEMKIT_PYTHON,@@ -124,6 +180,15 @@ function pyCandidates(): string[] {}function ffCandidates(): string[] {+ if (IS_WIN) {+ const localAppData = process.env.LOCALAPPDATA ?? join(homedir(), 'AppData', 'Local')+ return [+ process.env.STEMKIT_FFMPEG,+ join(localAppData, 'Microsoft', 'WinGet', 'Links', 'ffmpeg.exe'),+ 'C:\\ffmpeg\\bin\\ffmpeg.exe',+ join(process.env['ProgramFiles'] ?? 'C:\\Program Files', 'ffmpeg', 'bin', 'ffmpeg.exe')+ ].filter((p): p is string => !!p)+ }const home = homedir()return [process.env.STEMKIT_FFMPEG,@@ -179,14 +244,19 @@ export async function detectTools(): Promise<void> {state.python = { found: true, path: best.path, version: best.version }}- for (const candidate of ffCandidates()) {- if (!existsSync(candidate)) continue- try {- await runCapture(candidate, ['-version'])- state.ffmpeg = { found: true, path: candidate }- break- } catch {- continue+ const bundled = bundledFfmpeg()+ if (bundled) {+ state.ffmpeg = { found: true, path: bundled }+ } else {+ for (const candidate of ffCandidates()) {+ if (!existsSync(candidate)) continue+ try {+ await runCapture(candidate, ['-version'])+ state.ffmpeg = { found: true, path: candidate }+ break+ } catch {+ continue+ }}}@@ -216,7 +286,7 @@ export async function bootstrap(): Promise<boolean> {try {const venv = venvDir()- const pip = join(venv, 'bin', 'pip')+ const pip = venvPip()sendEnvEvent(`Creating virtual environment with ${state.python.path}`)await new Promise<void>((resolve, reject) => {@@ -297,7 +367,7 @@ export async function updateYtDlp(): Promise<boolean> {try {sendEnvEvent('Updating yt-dlp...')await new Promise<void>((resolve, reject) => {- const child = spawn(venvDir() ? join(venvDir(), 'bin', 'pip') : 'pip', [+ const child = spawn(venvPip(), ['install','-q','-U',diff --git a/src/main/index.ts b/src/main/index.tsindex 3a2c270..6d57d80 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -9,7 +9,7 @@ import {getStatus} from './env'import { loadSongs, removeSong, stemBuffers, stemsDir, stemsFor } from './library'-import { startJob, cancelJob } from './pipeline'+import { startJob, cancelJob, searchYouTube } from './pipeline'let mainWindow: BrowserWindow | null = null@@ -32,7 +32,8 @@ function createWindow(): void {preload: join(__dirname, '../preload/index.js'),contextIsolation: true,nodeIntegration: false,- sandbox: false+ sandbox: false,+ backgroundThrottling: false}})@@ -73,11 +74,11 @@ app.whenReady().then(async () => {return stemBuffers(videoId, song?.stems)})- ipcMain.handle('jobs:start', async (_e, url: string, model?: string) => {- void startJob(url, model)+ ipcMain.handle('jobs:start', async (_e, url: string, model?: string, stems?: string[]) => {+ void startJob(url, model, stems)return { started: true }})- ipcMain.handle('jobs:cancel', () => cancelJob())+ ipcMain.handle('jobs:cancel', (_e, videoId?: string) => cancelJob(videoId))ipcMain.handle('stem:export', async (_e, videoId: string, stem: string) => {const song = loadSongs().find((s) => s.videoId === videoId)@@ -114,6 +115,7 @@ app.whenReady().then(async () => {return { saved: true, path: target, count: list.length }})+ ipcMain.handle('search:youtube', (_e, query: string) => searchYouTube(query))ipcMain.handle('open-external', (_e, url: string) => {if (/^https:\/\/(www\.)?(youtube\.com|youtu\.be)\//.test(url)) {shell.openExternal(url)diff --git a/src/main/pipeline.ts b/src/main/pipeline.tsindex e687f1d..19d21b5 100644--- a/src/main/pipeline.ts+++ b/src/main/pipeline.ts@@ -26,11 +26,34 @@ import { parseVideoId } from '../shared/url'interface ActiveJob {videoId: stringtitle?: string- proc?: ChildProcess+ model: stringcancelled: boolean+ proc?: ChildProcess+}++const jobs = new Map<string, ActiveJob>()++const MAX_CONCURRENT_SEPARATIONS = 2+let activeSeparations = 0+const separationWaiters: Array<() => void> = []++function acquireSeparation(): Promise<() => void> {+ if (activeSeparations < MAX_CONCURRENT_SEPARATIONS) {+ activeSeparations+++ return Promise.resolve(releaseSeparation)+ }+ return new Promise((resolve) => {+ separationWaiters.push(() => {+ activeSeparations+++ resolve(releaseSeparation)+ })+ })}-let current: ActiveJob | null = null+function releaseSeparation(): void {+ activeSeparations--+ separationWaiters.shift()?.()+}function send(ev: JobEvent): void {for (const win of BrowserWindow.getAllWindows()) {@@ -39,120 +62,87 @@ function send(ev: JobEvent): void {}function progress(- videoId: string,+ job: ActiveJob,stage: JobStage,pct: number,- message?: string,- model?: string+ message?: string): void {- if (!current || current.videoId !== videoId) return- send({ kind: 'progress', data: { videoId, stage, pct, message, title: current.title, model } })-}--function fail(message: string): never {- const videoId = current?.videoId ?? 'unknown'- const err = new Error(message)- ;(err as NodeJS.ErrnoException & { videoId?: string }).videoId = videoId- throw err-}--export function extractVideoId(url: string): string {- const id = parseVideoId(url)- if (!id) fail('Could not parse a YouTube URL or video id out of that')- return id as string-}--function spawnEnv(): NodeJS.ProcessEnv {- return { ...process.env }-}--function runProcess(- cmd: string,- args: string[],- opts: { onStdout?: (chunk: string) => void; onLine?: (line: string) => void } = {}-): Promise<void> {- return new Promise((resolve, reject) => {- if (!current) return reject(new Error('cancelled'))- if (current.cancelled) return reject(new Error('cancelled'))- const child = spawn(cmd, args, { env: spawnEnv() })- current.proc = child-- let stdoutTail = ''- let stderrTail = ''-- child.stdout?.on('data', (chunk: Buffer) => {- const text = chunk.toString()- stdoutTail = (stdoutTail + text).slice(-2000)- opts.onStdout?.(text)- })- child.stderr?.on('data', (chunk: Buffer) => {- stderrTail = (stderrTail + chunk.toString()).slice(-2000)- })-- if (opts.onLine && child.stdout) {- const rl = createInterface({ input: child.stdout })- rl.on('line', (line) => opts.onLine?.(line))- }-- child.on('error', reject)- child.on('close', (code) => {- if (!current || current.cancelled) return reject(new Error('cancelled'))- if (code === 0) return resolve()- const detail =- stderrTail.split('\n').filter(Boolean).slice(-2).join(' — ') ||- stdoutTail.split('\n').filter(Boolean).slice(-1).join('')- reject(new Error(detail ? `${cmd.split('/').pop()} exited (${code}): ${detail}` : `exited with code ${code}`))- })+ if (!jobs.has(job.videoId) || job.cancelled) return+ send({+ kind: 'progress',+ data: { videoId: job.videoId, stage, pct, message, title: job.title, model: job.model }})}-async function fetchMetadata(url: string): Promise<{ title: string; duration: number }> {- let raw = ''- await runProcess(venvYtDlp(), [...ytDlpRuntimeArgs(), '-J', '--no-playlist', '--skip-download', url], {- onStdout: (chunk) => {- raw += chunk- }- })- try {- const meta = JSON.parse(raw)- return {- title: typeof meta.title === 'string' ? meta.title : 'Unknown title',- duration: typeof meta.duration === 'number' ? Math.round(meta.duration) : 0- }- } catch {- fail('Could not read video metadata')- }+export function extractVideoId(url: string): string | null {+ return parseVideoId(url)}-export async function startJob(rawUrl: string, model = 'htdemucs'): Promise<void> {- if (current) fail('A job is already running')-+export async function startJob(+ rawUrl: string,+ model = 'htdemucs',+ stems?: string[]+): Promise<void> {const url = rawUrl.trim()- const videoId = extractVideoId(url)-- const existing = loadSongs().find((s) => s.videoId === videoId)- if (existing && existing.model === model && stemsPresent(videoId, stemsFor(existing))) {- send({ kind: 'done', data: { videoId, song: existing } })+ const videoId = parseVideoId(url)+ if (!videoId) {+ send({ kind: 'failed', data: { videoId: '', message: 'Could not parse a YouTube URL or video id out of that' } })return}- if (existing && existing.model !== model) {- rmSync(songDir(videoId), { recursive: true, force: true })+ if (jobs.has(videoId)) {+ send({ kind: 'failed', data: { videoId, message: 'This song is already being processed' } })+ return}- current = { videoId, cancelled: false }+ const job: ActiveJob = { videoId, model, cancelled: false }+ jobs.set(videoId, job)++ const bail = (message: string): never => {+ throw Object.assign(new Error(message), { videoId })+ }try {+ const existing = loadSongs().find((s) => s.videoId === videoId)+ const covered =+ existing &&+ existing.model === model &&+ !!existing.stems?.length &&+ (stems?.length ? stems.every((s) => existing.stems!.includes(s)) : true)+ if (covered && stemsPresent(videoId, stemsFor(existing))) {+ send({ kind: 'done', data: { videoId, song: existing } })+ return+ }+ if (existing && (existing.model !== model || !stemsPresent(videoId, stemsFor(existing)))) {+ rmSync(songDir(videoId), { recursive: true, force: true })+ }+mkdirSync(songDir(videoId), { recursive: true })- progress(videoId, 'metadata', 0, 'Reading video info', model)+ progress(job, 'metadata', 0, 'Reading video info')- const meta = await fetchMetadata(url)- if (!current || current.videoId !== videoId) return- current.title = meta.title- progress(videoId, 'metadata', 100, meta.title, model)+ let raw = ''+ await runProcess(job, venvYtDlp(), [...ytDlpRuntimeArgs(), '-J', '--no-playlist', '--skip-download', url], {+ onStdout: (chunk) => {+ raw += chunk+ }+ })+ let meta: { title: string; duration: number }+ try {+ const parsed = JSON.parse(raw)+ meta = {+ title: typeof parsed.title === 'string' ? parsed.title : 'Unknown title',+ duration: typeof parsed.duration === 'number' ? Math.round(parsed.duration) : 0+ }+ } catch {+ bail('Could not read video metadata')+ }+ if (job.cancelled || !jobs.has(videoId)) return+ job.title = meta!.title+ progress(job, 'metadata', 100, meta!.title)- progress(videoId, 'download', 0, 'Downloading audio from YouTube', model)+ progress(job, 'download', 0, 'Downloading audio from YouTube')let maxPct = 0await runProcess(+ job,venvYtDlp(),[...ytDlpRuntimeArgs(),@@ -171,24 +161,24 @@ export async function startJob(rawUrl: string, model = 'htdemucs'): Promise<voidconst pct = parseFloat(m[1])if (pct > maxPct && pct <= 100) {maxPct = pct- progress(videoId, 'download', pct, undefined, model)+ progress(job, 'download', pct)}}}}})- if (!current || current.cancelled) return+ if (job.cancelled || !jobs.has(videoId)) returnconst dir = songDir(videoId)const rawFile = readdirSync(dir).find((f) => f.startsWith('raw.'))- if (!rawFile) fail('Download produced no file')+ if (!rawFile) bail('Download produced no file')const rawPath = join(dir, rawFile as string)- progress(videoId, 'convert', 0, 'Converting to WAV')+ progress(job, 'convert', 0, 'Converting to WAV')const ffmpeg = getStatus().ffmpeg.path- if (!ffmpeg) fail('ffmpeg not found — install it with: brew install ffmpeg')- await runProcess(ffmpeg, [+ if (!ffmpeg) bail('ffmpeg not found — install it with: brew install ffmpeg')+ await runProcess(job, ffmpeg as string, ['-y','-i',rawPath,@@ -201,98 +191,228 @@ export async function startJob(rawUrl: string, model = 'htdemucs'): Promise<voidmixWavPath(videoId)])rmSync(rawPath, { force: true })- progress(videoId, 'convert', 100, undefined, model)+ if (job.cancelled || !jobs.has(videoId)) return+ progress(job, 'convert', 100)mkdirSync(stemsDir(videoId), { recursive: true })progress(- videoId,+ job,'separate',0,- model === 'htdemucs_6s'- ? 'Separating 6 stems incl. piano & guitar'- : 'Separating stems (first run also downloads the model)',- model+ job.model === 'htdemucs_6s'+ ? 'Waiting for a free engine slot…'+ : 'Waiting for a free engine slot… (first runs also download models)')- let scriptError: string | null = null- let producedStems: string[] | null = null- await runProcess(- venvPython(),- [- separateScript(),- '--input',- mixWavPath(videoId),- '--out',- stemsDir(videoId),- '--model',- model,- '--device',- 'auto'- ],- {- onLine: (line) => {- let parsed: Record<string, unknown>- try {- parsed = JSON.parse(line)- } catch {- return- }- if (parsed.type === 'progress') {- progress(- videoId,- 'separate',- Number(parsed.pct ?? 0),- typeof parsed.message === 'string' ? parsed.message : undefined,- model- )- } else if (parsed.type === 'error') {- scriptError = `Separation failed: ${String(parsed.message)}`- } else if (parsed.type === 'done' && Array.isArray(parsed.stems)) {- producedStems = (parsed.stems as unknown[]).map(String)++ const release = await acquireSeparation()+ try {+ if (job.cancelled || !jobs.has(videoId)) return+ progress(job, 'separate', 0, 'Separating stems')+ let scriptError: string | null = null+ let producedStems: string[] | null = null+ await runProcess(+ job,+ venvPython(),+ [+ separateScript(),+ '--input',+ mixWavPath(videoId),+ '--out',+ stemsDir(videoId),+ '--model',+ job.model,+ '--device',+ 'auto',+ ...(stems?.length ? ['--only', stems.join(',')] : [])+ ],+ {+ onLine: (line) => {+ let parsed: Record<string, unknown>+ try {+ parsed = JSON.parse(line)+ } catch {+ return+ }+ if (parsed.type === 'progress') {+ progress(+ job,+ 'separate',+ Number(parsed.pct ?? 0),+ typeof parsed.message === 'string' ? parsed.message : undefined+ )+ } else if (parsed.type === 'error') {+ scriptError = `Separation failed: ${String(parsed.message)}`+ } else if (parsed.type === 'done' && Array.isArray(parsed.stems)) {+ producedStems = (parsed.stems as unknown[]).map(String)+ }}}- }- )- if (!current || current.cancelled) return- if (scriptError) fail(scriptError)+ )+ if (job.cancelled || !jobs.has(videoId)) return+ if (scriptError) bail(scriptError)- const finalStems = producedStems ?? []- if (!stemsPresent(videoId, finalStems)) fail('Separation finished but stem files are missing')+ const finalStems = producedStems ?? []+ if (!stemsPresent(videoId, finalStems)) bail('Separation finished but stem files are missing')- progress(videoId, 'finalize', 100, 'Adding to library', model)- const songs = upsertSong({- videoId,- title: meta.title,- duration: meta.duration,- addedAt: existing?.addedAt ?? Date.now(),- model,- stems: finalStems- })- send({ kind: 'done', data: { videoId, song: songs[0] } })+ progress(job, 'finalize', 100, 'Adding to library')+ const songs = upsertSong({+ videoId,+ title: meta!.title,+ duration: meta!.duration,+ addedAt: existing?.addedAt ?? Date.now(),+ model: job.model,+ stems: finalStems+ })+ send({ kind: 'done', data: { videoId, song: songs[0] } })+ } finally {+ release()+ }} catch (err) {- const message =- err instanceof Error ? err.message : String(err)- if (message === 'cancelled') {- rmSync(songDir(videoId), { recursive: true, force: true })- } else {+ const message = err instanceof Error ? err.message : String(err)+ if (message !== 'cancelled') {send({ kind: 'failed', data: { videoId, message } })}} finally {- current = null+ jobs.delete(videoId)}}-export function cancelJob(): void {- if (!current) return- current.cancelled = true+function runProcess(+ job: ActiveJob,+ cmd: string,+ args: string[],+ opts: { onStdout?: (chunk: string) => void; onLine?: (line: string) => void } = {}+): Promise<void> {+ return new Promise((resolve, reject) => {+ if (job.cancelled || !jobs.has(job.videoId)) return reject(new Error('cancelled'))+ const child = spawn(cmd, args, { env: { ...process.env } })+ job.proc = child++ let stdoutTail = ''+ let stderrTail = ''++ child.stdout?.on('data', (chunk: Buffer) => {+ const text = chunk.toString()+ stdoutTail = (stdoutTail + text).slice(-2000)+ opts.onStdout?.(text)+ })+ child.stderr?.on('data', (chunk: Buffer) => {+ stderrTail = (stderrTail + chunk.toString()).slice(-2000)+ })++ if (opts.onLine && child.stdout) {+ const rl = createInterface({ input: child.stdout })+ rl.on('line', (line) => opts.onLine?.(line))+ }++ child.on('error', reject)+ child.on('close', (code) => {+ if (job.cancelled || !jobs.has(job.videoId)) return reject(new Error('cancelled'))+ if (code === 0) return resolve()+ const detail =+ stderrTail.split('\n').filter(Boolean).slice(-2).join(' — ') ||+ stdoutTail.split('\n').filter(Boolean).slice(-1).join('')+ reject(+ new Error(+ detail+ ? `${cmd.split('/').pop()} exited (${code}): ${detail}`+ : `${cmd.split('/').pop()} exited with code ${code}`+ )+ )+ })+ })+}++export async function searchYouTube(query: string): Promise<+ Array<{ videoId: string; title: string; channel?: string; duration?: number }>+> {+ const trimmed = query.trim()+ if (!trimmed) return []+ const results = await new Promise<string>((resolve, reject) => {+ const child = spawn(+ venvYtDlp(),+ [+ ...ytDlpRuntimeArgs(),+ '--no-warnings',+ '-J',+ '--flat-playlist',+ '--no-playlist',+ `ytsearch15:${trimmed}`+ ],+ { env: { ...process.env } }+ )+ let out = ''+ let err = ''+ child.stdout?.on('data', (c: Buffer) => {+ out += c.toString()+ })+ child.stderr?.on('data', (c: Buffer) => {+ err = (err + c.toString()).slice(-1000)+ })+ const timer = setTimeout(() => {+ try {+ child.kill('SIGKILL')+ } catch {}+ reject(new Error('Search timed out'))+ }, 30000)+ child.on('error', (e) => {+ clearTimeout(timer)+ reject(e)+ })+ child.on('close', (code) => {+ clearTimeout(timer)+ if (code === 0) resolve(out)+ else reject(new Error(err.split('\n').filter(Boolean).slice(-1).join('') || `search exited ${code}`))+ })+ })+try {- current.proc?.kill('SIGKILL')- } catch {}- const id = current.videoId- current = null- rmSync(songDir(id), { recursive: true, force: true })- send({ kind: 'failed', data: { videoId: id, message: 'Cancelled' } })+ const data = JSON.parse(results)+ const entries = Array.isArray(data.entries) ? data.entries : []+ return entries+ .filter((e: Record<string, unknown>) => typeof e.id === 'string' && typeof e.title === 'string')+ .map((e: Record<string, unknown>) => ({+ videoId: e.id as string,+ title: e.title as string,+ channel:+ typeof e.uploader === 'string'+ ? e.uploader+ : typeof e.channel === 'string'+ ? e.channel+ : undefined,+ duration: typeof e.duration === 'number' ? Math.round(e.duration) : undefined+ }))+ } catch {+ return []+ }+}++function killTree(proc: ChildProcess): void {+ if (!proc.pid) return+ if (process.platform === 'win32') {+ try {+ spawn('taskkill', ['/pid', String(proc.pid), '/T', '/F'])+ } catch {}+ } else {+ try {+ proc.kill('SIGKILL')+ } catch {}+ }+}++export function cancelJob(videoId?: string): void {+ const targets = videoId+ ? ([jobs.get(videoId)].filter(Boolean) as ActiveJob[])+ : Array.from(jobs.values())+ for (const job of targets) {+ job.cancelled = true+ killTree(job.proc as ChildProcess)+ jobs.delete(job.videoId)+ rmSync(songDir(job.videoId), { recursive: true, force: true })+ send({ kind: 'failed', data: { videoId: job.videoId, message: 'Cancelled' } })+ }}export function isBusy(): boolean {- return current !== null+ return jobs.size > 0}diff --git a/src/preload/index.ts b/src/preload/index.tsindex d5f3c0b..5732ad7 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -18,8 +18,9 @@ const api: StemKitApi = {getBuffers: (videoId) => ipcRenderer.invoke('song:buffers', videoId),exportStem: (videoId, stem) => ipcRenderer.invoke('stem:export', videoId, stem),exportAllStems: (videoId) => ipcRenderer.invoke('stems:export-all', videoId),- startJob: (url, model) => ipcRenderer.invoke('jobs:start', url, model),- cancelJob: () => ipcRenderer.invoke('jobs:cancel'),+ searchYouTube: (query) => ipcRenderer.invoke('search:youtube', query),+ startJob: (url, model, stems) => ipcRenderer.invoke('jobs:start', url, model, stems),+ cancelJob: (videoId?: string) => ipcRenderer.invoke('jobs:cancel', videoId),openExternal: (url) => ipcRenderer.invoke('open-external', url),onJobEvent: (cb) => subscribe<JobEvent>('job:event', cb),onEnvEvent: (cb) => subscribe<EnvEvent>('env:event', cb)diff --git a/src/renderer/src/App.tsx b/src/renderer/src/App.tsxindex c0ff52b..deb59b8 100644--- a/src/renderer/src/App.tsx+++ b/src/renderer/src/App.tsx@@ -28,12 +28,17 @@ function stageLabel(stage: JobStage, pct: number): string {}}+function withoutKey<T>(map: Record<string, T>, key: string): Record<string, T> {+ const { [key]: _drop, ...rest } = map+ return rest+}+export default function App(): React.ReactElement {const [status, setStatus] = useState<EnvStatus | null>(null)const [songs, setSongs] = useState<Song[]>([])const [activeId, setActiveId] = useState<string | null>(null)- const [job, setJob] = useState<JobProgress | null>(null)- const [jobError, setJobError] = useState<{ videoId: string; message: string } | null>(null)+ const [jobs, setJobs] = useState<Record<string, JobProgress>>({})+ const [errors, setErrors] = useState<Record<string, string>>({})const [lastUrl, setLastUrl] = useState('')const [lastModel, setLastModel] = useState('htdemucs')const [envLogs, setEnvLogs] = useState<EnvLog[]>([])@@ -43,15 +48,17 @@ export default function App(): React.ReactElement {void window.stemkit.listSongs().then(setSongs)const offJob = window.stemkit.onJobEvent((ev) => {if (ev.kind === 'progress') {- setJobError(null)- setJob(ev.data)+ setJobs((prev) => ({ ...prev, [ev.data.videoId]: ev.data }))+ setErrors((prev) => (prev[ev.data.videoId] ? withoutKey(prev, ev.data.videoId) : prev))} else if (ev.kind === 'done') {- setJob(null)- setJobError(null)+ setJobs((prev) => withoutKey(prev, ev.data.videoId))+ setErrors((prev) => withoutKey(prev, ev.data.videoId))void window.stemkit.listSongs().then(setSongs)- setActiveId((cur) => cur ?? ev.data.song.videoId)+ } else if (ev.data.message === 'Cancelled') {+ setJobs((prev) => withoutKey(prev, ev.data.videoId))} else {- setJobError({ videoId: ev.data.videoId, message: ev.data.message })+ setJobs((prev) => withoutKey(prev, ev.data.videoId))+ setErrors((prev) => ({ ...prev, [ev.data.videoId]: ev.data.message }))}})const offEnv = window.stemkit.onEnvEvent((e) =>@@ -69,20 +76,30 @@ export default function App(): React.ReactElement {}}, [status?.ready])- const startUrl = useCallback(async (url: string, model = 'htdemucs'): Promise<void> => {- setLastUrl(url)- setLastModel(model)- setJobError(null)- const vid = parseVideoId(url)- setJob({ videoId: vid ?? '', stage: 'metadata', pct: 0, message: 'Starting…', model })- await window.stemkit.startJob(url, model)- }, [])+ const startUrl = useCallback(+ async (url: string, model = 'htdemucs', stems?: string[]): Promise<void> => {+ const vid = parseVideoId(url)+ if (!vid) return+ setLastUrl(url)+ setLastModel(model)+ setErrors((prev) => withoutKey(prev, vid))+ setJobs((prev) =>+ prev[vid]+ ? prev+ : { ...prev, [vid]: { videoId: vid, stage: 'metadata', pct: 0, message: 'Starting…', model } }+ )+ await window.stemkit.startJob(url, model, stems)+ },+ []+ )- const cancelJob = useCallback((): void => {- void window.stemkit.cancelJob()- setJob(null)- setJobError(null)- }, [])+ const cancelSelectedJob = useCallback(+ (videoId: string): void => {+ void window.stemkit.cancelJob(videoId)+ setJobs((prev) => withoutKey(prev, videoId))+ },+ []+ )const retryJob = useCallback((): void => {if (lastUrl) void startUrl(lastUrl, lastModel)@@ -93,13 +110,16 @@ export default function App(): React.ReactElement {if (lastUrl) void startUrl(lastUrl, lastModel)}, [lastUrl, lastModel, startUrl])- const deleteSong = useCallback(async (videoId: string): Promise<void> => {- if (job?.videoId === videoId) return- if (jobError?.videoId === videoId) setJobError(null)- await window.stemkit.deleteSong(videoId)- setSongs(await window.stemkit.listSongs())- setActiveId((cur) => (cur === videoId ? null : cur))- }, [job, jobError])+ const deleteSong = useCallback(+ async (videoId: string): Promise<void> => {+ if (jobs[videoId]) return+ setErrors((prev) => withoutKey(prev, videoId))+ await window.stemkit.deleteSong(videoId)+ setSongs(await window.stemkit.listSongs())+ setActiveId((cur) => (cur === videoId ? null : cur))+ },+ [jobs]+ )const activeSong = useMemo(() => songs.find((s) => s.videoId === activeId) ?? null,@@ -107,46 +127,50 @@ export default function App(): React.ReactElement {)const selectedJob = useMemo(- () => (job && job.videoId && job.videoId === activeId ? job : null),- [job, activeId]+ () => (activeId ? jobs[activeId] ?? null : null),+ [jobs, activeId])const selectedError = useMemo(- () => (jobError && jobError.videoId === activeId ? jobError.message : null),- [jobError, activeId]+ () => (activeId ? errors[activeId] ?? null : null),+ [errors, activeId])const pendingMap = useMemo(() => {const map: Record<string, { label: string; error?: boolean }> = {}- if (job && job.videoId) {- map[job.videoId] = { label: stageLabel(job.stage, job.pct) }+ for (const j of Object.values(jobs)) {+ map[j.videoId] = { label: stageLabel(j.stage, j.pct) }}- if (jobError) {- map[jobError.videoId] = { label: 'failed', error: true }+ for (const [id, message] of Object.entries(errors)) {+ if (!map[id]) {+ map[id] = { label: /already being processed/.test(message) ? 'queued' : 'failed', error: true }+ }}return map- }, [job, jobError])+ }, [jobs, errors])const displaySongs = useMemo(() => {const known = new Set(songs.map((s) => s.videoId))const top: Song[] = []- if (job?.videoId && !known.has(job.videoId)) {- top.push({- videoId: job.videoId,- title: job.title ?? '',- duration: 0,- addedAt: 0,- model: job.model- })+ for (const j of Object.values(jobs)) {+ if (!known.has(j.videoId)) {+ top.push({+ videoId: j.videoId,+ title: j.title ?? '',+ duration: 0,+ addedAt: 0,+ model: j.model+ })+ known.add(j.videoId)+ }}- if (- jobError &&- !known.has(jobError.videoId) &&- jobError.videoId !== job?.videoId- ) {- top.push({ videoId: jobError.videoId, title: '', duration: 0, addedAt: 0 })+ for (const id of Object.keys(errors)) {+ if (!known.has(id)) {+ top.push({ videoId: id, title: '', duration: 0, addedAt: 0 })+ known.add(id)+ }}return [...top, ...songs]- }, [songs, job, jobError])+ }, [songs, jobs, errors])if (!status) {return (@@ -168,8 +192,6 @@ export default function App(): React.ReactElement {)}- const busyVideoId = job?.videoId || jobError?.videoId || null-const selectedIsBusy = !!(selectedJob || selectedError)let main: React.ReactElement@@ -181,7 +203,7 @@ export default function App(): React.ReactElement {botSuspected={!!selectedError && /sign in|bot|confirm|unavailable|private/i.test(selectedError)}- onCancel={cancelJob}+ onCancel={() => activeId && cancelSelectedJob(activeId)}onRetry={retryJob}onUpdateYtDlp={() => void updateYtDlp()}/>@@ -189,7 +211,15 @@ export default function App(): React.ReactElement {} else if (activeSong) {main = <Player key={activeSong.videoId} song={activeSong} />} else {- main = <Home busy={!!job} hasSongs={displaySongs.length > 0} onStart={(u, m) => void startUrl(u, m)} />+ main = (+ <Home+ hasSongs={displaySongs.length > 0}+ songs={displaySongs}+ pending={pendingMap}+ onStart={(u, m, s) => void startUrl(u, m, s)}+ onSelect={(id) => setActiveId(id)}+ />+ )}return (@@ -197,7 +227,6 @@ export default function App(): React.ReactElement {<Sidebarsongs={displaySongs}activeId={activeId}- busyVideoId={busyVideoId}pending={pendingMap}onSelect={(id) => setActiveId(id)}onDelete={(id) => void deleteSong(id)}diff --git a/src/renderer/src/components/Home.tsx b/src/renderer/src/components/Home.tsxindex 41aefd2..08db208 100644--- a/src/renderer/src/components/Home.tsx+++ b/src/renderer/src/components/Home.tsx@@ -1,106 +1,273 @@-import { useState } from 'react'-import { MODEL_STANDARD, MODEL_EXTENDED, type StemId } from '../../../shared/types'-import { STEM_INFO } from '../lib/stems'--const STANDARD_IDS: StemId[] = ['vocals', 'drums', 'bass', 'other']-const EXTENDED_IDS: StemId[] = ['vocals', 'drums', 'bass', 'guitar', 'piano', 'other']+import { useEffect, useRef, useState } from 'react'+import {+ MODEL_STANDARD,+ MODEL_EXTENDED,+ DEFAULT_STEMS,+ type SearchResult,+ type Song,+ type StemId+} from '../../../shared/types'+import { parseVideoId } from '../../../shared/url'+import { STEM_INFO, PREFERRED_ORDER } from '../lib/stems'+import { fmtTime } from '../lib/format'interface Props {- busy: booleanhasSongs: boolean- onStart: (url: string, model: string) => void+ songs: Song[]+ pending?: Record<string, { label: string; error?: boolean }>+ onStart: (url: string, model: string, stems?: string[]) => void+ onSelect: (videoId: string) => void}-export function Home({ busy, hasSongs, onStart }: Props): React.ReactElement {- const [url, setUrl] = useState('')- const [model, setModel] = useState(MODEL_STANDARD)+const ALL_STEMS = PREFERRED_ORDER++export function Home({ hasSongs, songs, pending = {}, onStart, onSelect }: Props): React.ReactElement {+ const [query, setQuery] = useState('')+ const [selected, setSelected] = useState<Set<StemId>>(new Set<StemId>(DEFAULT_STEMS as StemId[]))+ const [results, setResults] = useState<SearchResult[]>([])+ const [searching, setSearching] = useState(false)+ const [searchError, setSearchError] = useState<string | null>(null)+ const [searchedFor, setSearchedFor] = useState('')+ const seqRef = useRef(0)+ const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null)++ const usesExtended = [...selected].some((id) => id === 'guitar' || id === 'piano')+ const derivedModel = usesExtended ? MODEL_EXTENDED : MODEL_STANDARD+ const orderedSelection = ALL_STEMS.filter((id) => selected.has(id))++ const toggleStem = (id: StemId): void => {+ setSelected((prev) => {+ const next = new Set(prev)+ if (next.has(id)) next.delete(id)+ else next.add(id)+ return next+ })+ }++ const startWithSelection = (videoIdOrUrl: string): void => {+ onStart(+ videoIdOrUrl.startsWith('http') ? videoIdOrUrl : `https://www.youtube.com/watch?v=${videoIdOrUrl}`,+ derivedModel,+ orderedSelection+ )+ }++ useEffect(() => {+ return () => {+ if (debounceRef.current) clearTimeout(debounceRef.current)+ }+ }, [])++ const runSearch = async (q: string): Promise<void> => {+ const seq = ++seqRef.current+ setSearching(true)+ setSearchError(null)+ try {+ const res = await window.stemkit.searchYouTube(q)+ if (seqRef.current === seq) {+ setResults(res)+ setSearchedFor(q)+ }+ } catch (err) {+ if (seqRef.current === seq) {+ setSearchError(err instanceof Error ? err.message : String(err))+ setResults([])+ }+ } finally {+ if (seqRef.current === seq) setSearching(false)+ }+ }++ const handleInput = (value: string): void => {+ setQuery(value)+ if (debounceRef.current) clearTimeout(debounceRef.current)+ const trimmed = value.trim()+ if (!trimmed || parseVideoId(trimmed)) {+ setResults([])+ setSearchError(null)+ setSearching(false)+ return+ }+ debounceRef.current = setTimeout(() => void runSearch(trimmed), 450)+ }const submit = (): void => {- const trimmed = url.trim()- if (!trimmed || busy) return- onStart(trimmed, model)- setUrl('')+ const trimmed = query.trim()+ if (!trimmed || selected.size === 0) return+ if (parseVideoId(trimmed)) {+ startWithSelection(trimmed)+ setQuery('')+ setResults([])+ return+ }+ if (searching) return+ void runSearch(trimmed)}- const chipsFor = (ids: StemId[]): React.ReactElement => (- <span className="flex items-center gap-1.5 flex-wrap">- {ids.map((id) => (- <span key={id} className="flex items-center gap-1 text-[10px]">- <span- className="w-1.5 h-1.5 rounded-full"- style={{ background: STEM_INFO[id].color }}- />- <span className={model === id ? '' : ''}>{STEM_INFO[id].label}</span>- </span>- ))}- </span>- )+ const startResult = (r: SearchResult): void => {+ startWithSelection(r.videoId)+ }return (- <div className="h-full flex flex-col items-center justify-center px-8">- <div className="w-full max-w-xl rise-in">- <h1 className="text-center text-[34px] font-bold tracking-tight leading-tight bg-gradient-to-r from-violet-300 via-white to-emerald-200 bg-clip-text text-transparent">+ <div className="h-full flex flex-col items-center px-8 pt-[8vh] pb-6 overflow-y-auto">+ <div className="w-full max-w-2xl">+ <h1 className="text-center text-[30px] font-bold tracking-tight leading-tight bg-gradient-to-r from-violet-300 via-white to-emerald-200 bg-clip-text text-transparent">Turn any YouTube track into stems.</h1>- <p className="text-center text-white/45 mt-3 text-[15px]">- Vocals, drums, bass and everything else — separated locally, synced to the video.+ <p className="text-center text-white/45 mt-2.5 text-[14px]">+ Search YouTube or paste a link — separated locally, synced to the video.</p>- <div className="mt-8 flex gap-2">+ <div className="mt-6 flex gap-2"><input- value={url}- onChange={(e) => setUrl(e.target.value)}+ autoFocus+ value={query}+ onChange={(e) => handleInput(e.target.value)}onKeyDown={(e) => e.key === 'Enter' && submit()}- placeholder="Paste a YouTube link…"+ placeholder="Search YouTube or paste a link…"spellCheck={false}- className="no-drag flex-1 glass rounded-xl px-4 py-3.5 text-sm outline-none placeholder:text-white/25 focus:ring-2 focus:ring-violet-400/60 transition-shadow"+ className="no-drag flex-1 glass rounded-xl px-4 py-3 text-sm outline-none placeholder:text-white/25 focus:ring-2 focus:ring-violet-400/60 transition-shadow"/><buttononClick={submit}- disabled={busy || !url.trim()}- className="no-drag px-6 rounded-xl bg-white text-black text-sm font-semibold hover:bg-white/90 active:scale-[0.98] transition-all disabled:opacity-40 disabled:hover:bg-white disabled:active:scale-100"+ disabled={!query.trim() || selected.size === 0}+ className="no-drag px-5 rounded-xl bg-white text-black text-sm font-semibold hover:bg-white/90 active:scale-[0.98] transition-all disabled:opacity-40 disabled:hover:bg-white disabled:active:scale-100">- {busy ? 'Working…' : 'Split'}+ {parseVideoId(query) ? 'Split' : 'Search'}</button></div>- <div className="mt-4 flex justify-center">- <div className="no-drag flex items-stretch gap-1 glass rounded-2xl p-1">- {[- { id: MODEL_STANDARD, label: 'Standard', ids: STANDARD_IDS },- { id: MODEL_EXTENDED, label: 'Extended · all instruments', ids: EXTENDED_IDS }- ].map((opt) => (- <button- key={opt.id}- onClick={() => setModel(opt.id)}- className={`px-4 py-2.5 rounded-xl text-[13px] font-medium transition-all text-left ${- model === opt.id- ? 'bg-white/90 text-black'- : 'text-white/55 hover:text-white hover:bg-white/5'- }`}- >- <span className="block">{opt.label}</span>- <span className={`block mt-1 ${model === opt.id ? 'opacity-70' : 'opacity-50'}`}>- {chipsFor(opt.ids)}- </span>- </button>- ))}+ <div className="mt-3.5 glass rounded-2xl px-4 py-3">+ <div className="flex items-center justify-between mb-2.5">+ <span className="text-[11px] font-semibold uppercase tracking-widest text-white/30">+ Instruments+ </span>+ <span className="text-[11px] text-white/30 font-medium">+ {selected.size === 0+ ? 'select at least one'+ : usesExtended+ ? `6-source engine · ${selected.size} stems`+ : `4-source engine · ${selected.size} stems`}+ </span>+ </div>+ <div className="flex items-center gap-1.5 flex-wrap">+ {ALL_STEMS.map((id) => {+ const info = STEM_INFO[id]+ const on = selected.has(id)+ return (+ <button+ key={id}+ onClick={() => toggleStem(id)}+ className={`no-drag flex items-center gap-1.5 rounded-full px-3 py-1.5 text-[12px] font-medium capitalize border transition-all ${+ on+ ? 'border-transparent'+ : 'border-white/[0.08] bg-white/[0.03] text-white/35 hover:text-white/60 hover:border-white/20'+ }`}+ style={+ on+ ? {+ background: `${info.color}1f`,+ color: info.color,+ boxShadow: `inset 0 0 0 1px ${info.color}55`+ }+ : undefined+ }+ >+ <span+ className="w-1.5 h-1.5 rounded-full transition-opacity"+ style={{ background: info.color, opacity: on ? 1 : 0.3 }}+ />+ {info.label}+ </button>+ )+ })}</div></div>- <div className="mt-6 flex items-center justify-center gap-2 flex-wrap">- {['Karaoke mode', 'Acapella', 'Instrumental', 'Runs on your machine'].map((chip) => (- <span- key={chip}- className="text-[12px] text-white/40 glass rounded-full px-3 py-1"- >- {chip}- </span>- ))}- </div>+ {(searching || searchError || results.length > 0) && (+ <div className="mt-6">+ {searching && (+ <div className="space-y-2">+ {[...Array(4)].map((_, i) => (+ <div key={i} className="glass rounded-xl h-[52px] animate-pulse" style={{ animationDelay: `${i * 120}ms` }} />+ ))}+ </div>+ )}+ {!searching && searchError && (+ <div className="rounded-xl bg-rose-500/10 border border-rose-400/20 px-4 py-3 text-[13px] text-rose-200">+ Search failed: {searchError}+ </div>+ )}+ {!searching && !searchError && results.length > 0 && (+ <div className="space-y-1 rise-in">+ <p className="text-[11px] uppercase tracking-widest text-white/30 font-semibold mb-2">+ Results for “{searchedFor}”+ </p>+ {results.map((r) => {+ const p = pending[r.videoId]+ const inProgress = !!p && !p.error+ const failed = !!p?.error+ const saved = !p && songs.some((s) => s.videoId === r.videoId)+ return (+ <button+ key={r.videoId}+ onClick={() => (inProgress || failed || saved ? onSelect(r.videoId) : startResult(r))}+ title={+ inProgress+ ? 'View splitting progress'+ : failed+ ? 'View error'+ : saved+ ? 'Open from your library'+ : 'Split into stems'+ }+ className={`no-drag group w-full flex items-center gap-3 rounded-xl px-2 py-1.5 text-left hover:bg-white/[0.06] transition-colors ${+ inProgress || failed || saved ? '' : 'cursor-pointer'+ }`}+ >+ <span className="relative shrink-0">+ <img+ src={`https://i.ytimg.com/vi/${r.videoId}/default.jpg`}+ alt=""+ className="w-[67px] h-[38px] rounded-md object-cover bg-white/5"+ draggable={false}+ />+ {typeof r.duration === 'number' && r.duration > 0 && (+ <span className="absolute bottom-1 right-1 bg-black/80 rounded text-[9px] font-mono px-1">+ {fmtTime(r.duration)}+ </span>+ )}+ </span>+ <span className="min-w-0 flex-1">+ <span className="block text-[13px] truncate text-white/85">{r.title}</span>+ <span className="block text-[11px] text-white/35 mt-0.5">{r.channel}</span>+ </span>+ {inProgress ? (+ <span className="shrink-0 flex items-center gap-2 pr-2 text-violet-300">+ <span className="text-[11px] font-medium max-w-[120px] truncate">{p!.label}</span>+ <span className="w-3 h-3 rounded-full border-2 border-white/20 border-t-violet-300 animate-spin" />+ </span>+ ) : failed ? (+ <span className="shrink-0 pr-2 text-[11px] font-medium text-rose-300">failed — view</span>+ ) : saved ? (+ <span className="shrink-0 pr-2 text-[11px] font-medium text-emerald-300 group-hover:text-emerald-200 transition-colors">+ ✓ In library+ </span>+ ) : (+ <span className="shrink-0 text-[11px] font-medium text-violet-300 opacity-0 group-hover:opacity-100 transition-opacity pr-2 cursor-pointer">+ Split →+ </span>+ )}+ </button>+ )+ })}+ </div>+ )}+ </div>+ )}- {!hasSongs && (- <p className="mt-10 text-center text-xs text-white/25 leading-relaxed">+ {!hasSongs && results.length === 0 && !searching && (+ <p className="mt-8 text-center text-xs text-white/25 leading-relaxed">First run installs the separation engine (~2 GB, one time).<br />After that, a 4-minute song takes about a minute to split.diff --git a/src/renderer/src/components/Player.tsx b/src/renderer/src/components/Player.tsxindex b7bccb7..a6a467b 100644--- a/src/renderer/src/components/Player.tsx+++ b/src/renderer/src/components/Player.tsx@@ -36,6 +36,10 @@ export function Player({ song }: Props): React.ReactElement {const hostRef = useRef<YouTubeHost | null>(null)const posRef = useRef(0)const playingRef = useRef(false)+ const videoSyncAtRef = useRef(0)++ const VIDEO_DRIFT_LIMIT = 0.4+ const VIDEO_RESYNC_COOLDOWN = 2000const [ytReady, setYtReady] = useState(false)const [decoding, setDecoding] = useState(true)@@ -64,6 +68,7 @@ export function Player({ song }: Props): React.ReactElement {posRef.current = 0setPlaying(false)playingRef.current = false+ videoSyncAtRef.current = 0setYtReady(false)setDecodeError(null)setBuffers({})@@ -82,6 +87,8 @@ export function Player({ song }: Props): React.ReactElement {setBuffers(decoded)engine.setBuffers(decoded)setVols(Object.fromEntries(Object.keys(decoded).map((id) => [id, 1])))+ const d = engine.trackDuration()+ if (d > 0) setDuration(d)setDecoding(false)}).catch((err) => {@@ -110,16 +117,10 @@ export function Player({ song }: Props): React.ReactElement {.mount(container, song.videoId, (state: YTState) => {if (disposed || !engine.hasBuffers()) returnif (state === 'playing') {- engine.rate = host.rate() || 1- engine.setPlaying(true, host.time())- playingRef.current = true- setPlaying(true)- } else if (state === 'paused' || state === 'ended') {- const t = host.time()- posRef.current = t- engine.setPlaying(false, t)- playingRef.current = false- setPlaying(false)+ videoSyncAtRef.current = 0+ if (!playingRef.current) {+ host.pause()+ }}}).then(() => {@@ -138,13 +139,39 @@ export function Player({ song }: Props): React.ReactElement {useEffect(() => {if (!playing) returnlet raf = 0+ const tick = (): void => {+ posRef.current = engine.expected()++ const dur = engine.trackDuration()+ if (dur > 0 && posRef.current >= dur - 0.03) {+ posRef.current = dur+ engine.stopAll()+ playingRef.current = false+ setPlaying(false)+ hostRef.current?.pause()+ setBump((n) => n + 1)+ return+ }++ const now = performance.now()+ if (now - videoSyncAtRef.current > VIDEO_RESYNC_COOLDOWN) {+ const v = hostRef.current?.time() ?? 0+ if (Math.abs(v - posRef.current) > VIDEO_DRIFT_LIMIT) {+ videoSyncAtRef.current = now+ hostRef.current?.seek(posRef.current)+ }+ }+ }const loop = (): void => {- const t = hostRef.current?.time() ?? 0- posRef.current = engine.tick(t)+ tick()raf = requestAnimationFrame(loop)}raf = requestAnimationFrame(loop)- return () => cancelAnimationFrame(raf)+ const backup = setInterval(tick, 400)+ return () => {+ cancelAnimationFrame(raf)+ clearInterval(backup)+ }}, [playing])useEffect(() => {@@ -158,13 +185,18 @@ export function Player({ song }: Props): React.ReactElement {}, [])const togglePlay = useCallback((): void => {- const host = hostRef.current- if (!host || decoding || decodeError) return+ if (decoding || decodeError) returnif (playingRef.current) {- host.pause()+ playingRef.current = false+ engine.setPlaying(false, posRef.current)+ hostRef.current?.pause()+ setPlaying(false)} else {+ playingRef.current = trueengine.resume()- host.play()+ engine.setPlaying(true, posRef.current)+ hostRef.current?.play()+ setPlaying(true)}}, [decoding, decodeError])@@ -172,8 +204,9 @@ export function Player({ song }: Props): React.ReactElement {(t: number): void => {const clamped = Math.max(0, Math.min(duration > 0 ? duration - 0.05 : t, t))posRef.current = clamped- hostRef.current?.seek(clamped)engine.setPlaying(playingRef.current, clamped)+ videoSyncAtRef.current = performance.now()+ hostRef.current?.seek(clamped)setBump((n) => n + 1)},[duration]@@ -218,7 +251,14 @@ export function Player({ song }: Props): React.ReactElement {const toggleMute = (id: StemId): void => {setPreset('custom')- setSolos(new Set())+ const turningOn = !mutes.has(id)+ if (turningOn && solos.has(id)) {+ setSolos((prev) => {+ const next = new Set(prev)+ next.delete(id)+ return next+ })+ }setMutes((prev) => {const next = new Set(prev)if (next.has(id)) next.delete(id)@@ -229,7 +269,14 @@ export function Player({ song }: Props): React.ReactElement {const toggleSolo = (id: StemId): void => {setPreset('custom')- setMutes(new Set())+ const turningOn = !solos.has(id)+ if (turningOn && mutes.has(id)) {+ setMutes((prev) => {+ const next = new Set(prev)+ next.delete(id)+ return next+ })+ }setSolos((prev) => {const next = new Set(prev)if (next.has(id)) next.delete(id)@@ -249,80 +296,65 @@ export function Player({ song }: Props): React.ReactElement {<div className="flex-1 min-h-0 overflow-y-auto px-6 pb-6"><div className="max-w-6xl mx-auto">- <div className="flex items-start gap-5">- <div className="relative w-full max-w-xl shrink">- <div className="absolute -inset-6 bg-violet-500/10 blur-3xl rounded-full pointer-events-none" />- <div className="relative aspect-video rounded-2xl overflow-hidden ring-1 ring-white/10 bg-black shadow-2xl shadow-black/60">+ <div className="flex items-stretch gap-4 h-[200px]">+ <div className="relative w-[356px] shrink-0">+ <div className="absolute -inset-4 bg-violet-500/10 blur-3xl rounded-full pointer-events-none" />+ <div className="absolute inset-0 rounded-xl overflow-hidden ring-1 ring-white/10 bg-black shadow-2xl shadow-black/60"><div ref={containerRef} className="absolute inset-0 [&_iframe]:w-full [&_iframe]:h-full" />{!ytReady && (<div className="absolute inset-0 flex items-center justify-center animate-pulse">- <span className="text-xs text-white/40 tracking-widest uppercase">loading video…</span>+ <span className="text-[10px] text-white/40 tracking-widest uppercase">loading…</span></div>)}- {(decoding || decodeError) && (- <div className="absolute inset-x-4 bottom-4 flex justify-center rise-in">- <div className={`glass rounded-xl px-4 py-2 text-sm ${decodeError ? 'text-rose-300' : ''}`}>- {decodeError ?? (- <span className="flex items-center gap-2">- <span className="w-3 h-3 rounded-full border-2 border-white/30 border-t-white animate-spin" />- decoding stems…- </span>- )}+ {decodeError && (+ <div className="absolute inset-x-3 bottom-3 flex justify-center rise-in">+ <div className="glass rounded-lg px-3 py-1.5 text-xs text-rose-300 break-words">+ {decodeError}</div></div>)}</div></div>- <aside className="flex-1 min-w-0 glass rounded-2xl p-5 rise-in">- <div className="flex gap-4">+ <aside className="flex-1 min-w-0 glass rounded-2xl px-5 py-4 rise-in flex flex-col justify-center gap-3">+ <div className="flex items-center gap-3.5"><imgsrc={`https://i.ytimg.com/vi/${song.videoId}/mqdefault.jpg`}alt=""- className="w-28 h-[63px] rounded-lg object-cover bg-white/5 shrink-0"+ className="w-16 h-9 rounded-md object-cover bg-white/5 shrink-0"draggable={false}/>- <div className="min-w-0">- <h3 className="text-[15px] font-semibold leading-snug line-clamp-2">{song.title}</h3>- <p className="text-xs text-white/40 mt-1.5 font-mono">- {fmtTime(song.duration)} · added {addedLabel}+ <div className="min-w-0 flex-1">+ <h3 className="text-[14px] font-semibold leading-snug truncate">{song.title}</h3>+ <p className="text-[11px] text-white/40 mt-0.5 font-mono truncate">+ {fmtTime(song.duration)} · added {addedLabel} ·{' '}+ {song.model === 'htdemucs_6s' ? '6-source engine' : '4-source engine'}</p></div>- </div>-- <div className="mt-4 flex items-center gap-2 flex-wrap">- <span className="text-[11px] px-2.5 py-1 rounded-full bg-violet-400/15 text-violet-200 font-medium">- {song.model === 'htdemucs_6s' ? 'Extended · 6-stem model' : 'Standard · 4-stem model'}- </span>- <span className="text-[11px] px-2.5 py-1 rounded-full bg-white/5 text-white/50 font-medium">+ <span className="shrink-0 text-[11px] px-2.5 py-1 rounded-full bg-white/5 text-white/50 font-medium">{stemMeta.length} stems</span></div>- <div className="mt-5">- <span className="text-[11px] font-semibold uppercase tracking-widest text-white/30">Stems</span>- <div className="mt-2 grid grid-cols-2 gap-x-4 gap-y-1.5">- {stemMeta.map((meta) => (- <span key={meta.id} className="flex items-center gap-2 text-[13px] text-white/70">- <span className="w-2 h-2 rounded-full shrink-0" style={{ background: meta.color }} />- <span className="capitalize">{meta.label}</span>- </span>- ))}- </div>- </div>-- <div className="mt-5 grid grid-cols-2 gap-2">+ <div className="mt-3 flex items-center gap-x-4 gap-y-1.5 flex-wrap">+ {stemMeta.map((meta) => (+ <span key={meta.id} className="flex items-center gap-1.5 text-[12px] text-white/70">+ <span className="w-2 h-2 rounded-full shrink-0" style={{ background: meta.color }} />+ <span className="capitalize">{meta.label}</span>+ </span>+ ))}+ <span className="flex-1" /><buttononClick={exportAllStems}disabled={decoding || !!decodeError}- className="no-drag glass rounded-xl px-4 py-2.5 text-[13px] text-white/70 hover:text-white hover:bg-white/10 transition-colors flex items-center justify-center gap-2 disabled:opacity-40"+ className="no-drag glass rounded-lg px-3 py-2 text-[12px] text-white/70 hover:text-white hover:bg-white/10 transition-colors flex items-center gap-1.5 disabled:opacity-40"><DownloadIcon className="w-3.5 h-3.5" />Export all</button><buttononClick={() => window.stemkit.openExternal(youtubeUrl)}- className="no-drag glass rounded-xl px-4 py-2.5 text-[13px] text-white/70 hover:text-white hover:bg-white/10 transition-colors text-center"+ className="no-drag glass rounded-lg px-3 py-2 text-[12px] text-white/70 hover:text-white hover:bg-white/10 transition-colors">YouTube</button>diff --git a/src/renderer/src/components/Sidebar.tsx b/src/renderer/src/components/Sidebar.tsxindex d0c549d..1463ddf 100644--- a/src/renderer/src/components/Sidebar.tsx+++ b/src/renderer/src/components/Sidebar.tsx@@ -5,7 +5,6 @@ import { LogoMark, TrashIcon, PlusIcon } from './Icons'interface Props {songs: Song[]activeId: string | null- busyVideoId: string | nullpending?: Record<string, { label: string; error?: boolean }>onSelect: (videoId: string) => voidonDelete: (videoId: string) => void@@ -15,7 +14,6 @@ interface Props {export function Sidebar({songs,activeId,- busyVideoId,pending = {},onSelect,onDelete,diff --git a/src/renderer/src/components/StemLane.tsx b/src/renderer/src/components/StemLane.tsxindex 9cf09a6..c1d16d6 100644--- a/src/renderer/src/components/StemLane.tsx+++ b/src/renderer/src/components/StemLane.tsx@@ -110,6 +110,7 @@ export function StemLane({}, [peaks, duration, getPosition, meta.color])const handleSeek = (e: React.MouseEvent<HTMLCanvasElement>): void => {+ if (!peaks || duration <= 0) returnconst rect = e.currentTarget.getBoundingClientRect()const frac = (e.clientX - rect.left) / rect.widthonSeek(Math.max(0, Math.min(1, frac)) * duration)@@ -153,15 +154,6 @@ export function StemLane({>S</button>- {onExport && (- <button- onClick={onExport}- title="Export stem as WAV"- className="no-drag w-6 h-6 rounded-md bg-white/5 hover:bg-white/10 text-white/40 hover:text-white flex items-center justify-center transition-colors"- >- <DownloadIcon className="w-3.5 h-3.5" />- </button>- )}<canvasref={canvasRef}@@ -181,6 +173,16 @@ export function StemLane({background: `linear-gradient(to right, ${meta.color} ${volume * 100}%, rgba(255,255,255,0.14) ${volume * 100}%)`}}/>++ {onExport && (+ <button+ onClick={onExport}+ title="Export stem as WAV"+ className="no-drag w-6 h-6 rounded-md bg-white/5 hover:bg-white/10 text-white/40 hover:text-white flex items-center justify-center transition-colors shrink-0"+ >+ <DownloadIcon className="w-3.5 h-3.5" />+ </button>+ )}</div>)}diff --git a/src/renderer/src/lib/engine.ts b/src/renderer/src/lib/engine.tsindex a39d58c..4d6907e 100644--- a/src/renderer/src/lib/engine.ts+++ b/src/renderer/src/lib/engine.ts@@ -1,7 +1,5 @@import type { StemId } from '../../../shared/types'-const DRIFT_LIMIT = 0.06-export type BufferMap = Partial<Record<StemId, AudioBuffer>>export async function decodePayload(@@ -93,16 +91,17 @@ export class StemEngine {this.anchorCtx = startAt}- tick(actualTime: number): number {- if (!this.ctx || !this.playing || !this.hasBuffers()) return actualTime- let expected =- this.anchorYt + (this.ctx.currentTime - this.anchorCtx) * this.rate- if (Math.abs(actualTime - expected) > DRIFT_LIMIT) {- this.align(actualTime)- expected =- this.anchorYt + (this.ctx.currentTime - this.anchorCtx) * this.rate+ expected(): number {+ if (!this.ctx || !this.playing) return this.anchorYt+ return this.anchorYt + (this.ctx.currentTime - this.anchorCtx) * this.rate+ }++ trackDuration(): number {+ let d = 0+ for (const buf of Object.values(this.buffers)) {+ if (buf && buf.duration > d) d = buf.duration}- return expected+ return d}applyMix(diff --git a/src/shared/types.ts b/src/shared/types.tsindex 34b0443..675e50a 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -53,6 +53,13 @@ export type JobEvent =| { kind: 'done'; data: JobDone }| { kind: 'failed'; data: JobFailed }+export interface SearchResult {+ videoId: string+ title: string+ channel?: string+ duration?: number+}+export interface StemKitApi {envStatus(): Promise<EnvStatus>envBootstrap(): Promise<boolean>@@ -62,8 +69,9 @@ export interface StemKitApi {getBuffers(videoId: string): Promise<Record<string, Uint8Array>>exportStem(videoId: string, stem: string): Promise<{ saved: boolean; path?: string }>exportAllStems(videoId: string): Promise<{ saved: boolean; path?: string; count?: number }>- startJob(url: string, model?: string): Promise<{ started: boolean }>- cancelJob(): Promise<void>+ searchYouTube(query: string): Promise<SearchResult[]>+ startJob(url: string, model?: string, stems?: string[]): Promise<{ started: boolean }>+ cancelJob(videoId?: string): Promise<void>openExternal(url: string): Promise<void>onJobEvent(cb: (ev: JobEvent) => void): () => voidonEnvEvent(cb: (ev: EnvEvent) => void): () => void