diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 70fda09..646251c 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -55,10 +55,11 @@ jobs: with: python-version: "3.12" - # --- Step 1: freeze the FastAPI backend into a single-file sidecar --- + # --- Step 1: freeze the FastAPI backend into a onedir sidecar folder --- # build_sidecar.* stages it as - # frontend/src-tauri/binaries/konduktor-sidecar-[.exe] - # which tauri.conf.json's externalBin bundles into the app. + # frontend/src-tauri/binaries/konduktor-sidecar/ + # which tauri.macos.conf.json (bundle.macOS.files, keeps its symlinks) / + # tauri.windows.conf.json (bundle.resources) put in the app as `sidecar/`. - name: Install backend deps working-directory: backend run: | diff --git a/BUILDING-WINDOWS.md b/BUILDING-WINDOWS.md index d3dfe8a..0224ce6 100644 --- a/BUILDING-WINDOWS.md +++ b/BUILDING-WINDOWS.md @@ -39,7 +39,7 @@ cd .. # 1) Freeze + stage the backend sidecar (from the activated backend venv) cd backend .\.venv\Scripts\Activate.ps1 # if not already active -.\build_sidecar.ps1 # → frontend\src-tauri\binaries\konduktor-sidecar-.exe +.\build_sidecar.ps1 # → frontend\src-tauri\binaries\konduktor-sidecar\ (a folder) cd .. # 2) Build the app @@ -56,7 +56,8 @@ frontend\src-tauri\target\release\bundle\msi\Konduktor_0.1.0_x64_en-US.msi frontend\src-tauri\target\release\bundle\nsis\Konduktor_0.1.0_x64-setup.exe ``` -Either one installs the app (bundling the sidecar `.exe` alongside it). +Either one installs the app, with the sidecar folder in its `sidecar\` resource +folder (`tauri.windows.conf.json`). ## Rebuilding after changes diff --git a/CLAUDE.md b/CLAUDE.md index 19e4224..05af4e2 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -875,7 +875,17 @@ Two independent apps that talk over HTTP: shell quits anyway after ~2 s without one, so a hung page cannot trap the user), quits (`quit_now`) when nothing is unsaved, else asks Save · Discard · Cancel; the sidecar is killed only at `RunEvent::Exit`, after the answer; - browser dev gets `beforeunload`), `SaveBar` (+ "Discard changes…" when + browser dev gets `beforeunload`), `StartupGate` (mounted in `main.tsx` + around everything but `AmbientBackdrop`: the shell opens the window AT ONCE + and starts the sidecar beside it, so nothing that calls the API mounts + until `backend_status` / `konduktor://backend` says ready, which is when + `setApiBase` gets the sidecar's address. Meanwhile `StartupScreen` shows + the icon with a generated waveform scrolling under a fixed playhead, a + "first launch takes longer" note after 6 s, Quit / Keep waiting after 90 s, + and if the sidecar exits its last 30 output lines with Copy details / Quit + / Try again (`backend_restart`). The shell has no timeout of its own. Before + ready it answers quit requests itself — nothing can be unsaved — and stops + at ready so it never races `QuitGuard`), `SaveBar` (+ "Discard changes…" when dirty, and the settings gear beside it, whose menu opens `ShortcutsDialog` — the shortcut list is written out BY HAND, so a new or changed shortcut in `PrepStrip` / `TrackTable` must be added there too — and `AppSettings` ("Konduktor Settings…": app-level prefs, each with its default in `APP_SETTING_DEFAULTS` and read through `useAppSetting`; today `expandPlaylistFolders` and `exportRootFolder`, both default off — the latter read by the backend at `run_export` and passed down as `ExportPayload.root_folder`. The Sidebar holds folder open state as per-id overrides of that setting, reset on a new library or a change of the setting, and carried to the new ids when a rename/move changes a folder's path id)), `Toolbar` (search/filters; columns are chosen by right-clicking the table header), `TrackTable` (**the one track list** — All Tracks, playlists, exports and devices. TanStack Table + **virtualized** grid; per-row play button, @@ -1489,6 +1499,21 @@ frontend at `http://localhost:5173`. render is the library's own pipeline (see "Write path"), which reproduces Traktor's byte-exact layout so a no-op save is byte-identical and only edited objects diff. `test_save_fidelity.py` enforces this. +4. **The desktop sidecar is a PyInstaller ONEDIR folder — never go back to + onefile.** A onefile binary unpacked ~390 native libraries into a NEW temp + folder on every launch, and macOS (XProtect / syspolicyd) checks each library + it has not seen before as it is dlopen()ed, keyed per FILE: the window + appeared only after ~10 s on every launch (measured 2026-10-12: 95 s to load + them all fresh, 1 s once seen). As a folder in the app they are checked + once; a launch is ~0.5 s. `build_sidecar.*` stages + `src-tauri/binaries/konduktor-sidecar/`; `lib.rs` spawns + `/sidecar/konduktor-sidecar[.exe]`. On macOS it is bundled by + `tauri.macos.conf.json`'s `bundle.macOS.files`, NOT `bundle.resources`: + the resource copier follows symlinks, turning PyInstaller's 37 library + aliases (`_internal/libavcodec… -> av/.dylibs/…`, `Python.framework`'s + `Versions/Current`) into second copies a library could be loaded twice + from. Windows has no such links and uses `resources` + (`tauri.windows.conf.json`). ## Data model notes diff --git a/README.md b/README.md index a15304b..5915420 100644 --- a/README.md +++ b/README.md @@ -126,14 +126,14 @@ On top of the Python 3.11+ and Node 18+ from above: [BUILDING-WINDOWS.md](BUILDING-WINDOWS.md) for the one-time toolchain setup. The build is a two-step recipe on both platforms: **freeze the backend into a -sidecar binary**, then **build the app**. The only difference is which sidecar +sidecar folder**, then **build the app**. The only difference is which sidecar script you run — `.sh` on macOS/Linux, `.ps1` on Windows. Each build runs on its own OS (the app can't be cross-compiled). ### macOS / Linux ```bash -# 1) Freeze the backend into a sidecar binary (from the activated backend venv) +# 1) Freeze the backend into a sidecar folder (from the activated backend venv) cd backend && source .venv/bin/activate && ./build_sidecar.sh && cd .. # 2) Build the app @@ -147,7 +147,7 @@ The installer lands at ### Windows ```powershell -# 1) Freeze the backend into a sidecar binary (from the activated backend venv) +# 1) Freeze the backend into a sidecar folder (from the activated backend venv) cd backend; .\.venv\Scripts\Activate.ps1; .\build_sidecar.ps1; cd .. # 2) Build the app diff --git a/backend/build_sidecar.ps1 b/backend/build_sidecar.ps1 index 4288a66..c5196ec 100644 --- a/backend/build_sidecar.ps1 +++ b/backend/build_sidecar.ps1 @@ -1,6 +1,7 @@ -# Build the frozen backend sidecar on Windows (PyInstaller) and stage it for -# Tauri as binaries\konduktor-sidecar-.exe. -# Output: backend\dist\konduktor-sidecar.exe + frontend\src-tauri\binaries\... +# Build the frozen backend sidecar on Windows (a PyInstaller onedir folder) and +# stage it for Tauri as frontend\src-tauri\binaries\konduktor-sidecar\, which +# tauri.conf.json bundles as a resource folder (`sidecar\` in the app). +# Output: backend\dist\konduktor-sidecar\ + frontend\src-tauri\binaries\konduktor-sidecar\ # # Run from a PowerShell prompt with the backend venv's Python on PATH, e.g.: # cd backend @@ -16,12 +17,13 @@ $Py = Join-Path $Root ".venv\Scripts\python.exe" if (-not (Test-Path $Py)) { $Py = "python" } & $Py -m PyInstaller --noconfirm --clean konduktor-sidecar.spec -Write-Host "Built: $Root\dist\konduktor-sidecar.exe" +if ($LASTEXITCODE -ne 0) { throw "PyInstaller failed ($LASTEXITCODE)" } +Write-Host "Built: $Root\dist\konduktor-sidecar\" -# Stage for Tauri: name with the host target triple + .exe so the shell plugin -# resolves it. (rustc must be on PATH.) -$Triple = (& rustc -vV | Select-String '^host: ').ToString().Replace('host: ', '').Trim() +# Stage for Tauri, replacing the whole folder so no file from an older build survives. $Dest = Join-Path $Root "..\frontend\src-tauri\binaries" New-Item -ItemType Directory -Force -Path $Dest | Out-Null -Copy-Item "$Root\dist\konduktor-sidecar.exe" (Join-Path $Dest "konduktor-sidecar-$Triple.exe") -Force -Write-Host "Staged: $Dest\konduktor-sidecar-$Triple.exe" +$Staged = Join-Path $Dest "konduktor-sidecar" +if (Test-Path $Staged) { Remove-Item -Recurse -Force $Staged } +Copy-Item -Recurse "$Root\dist\konduktor-sidecar" $Staged +Write-Host "Staged: $Staged\" diff --git a/backend/build_sidecar.sh b/backend/build_sidecar.sh index ac8c7b8..4ad1d7c 100755 --- a/backend/build_sidecar.sh +++ b/backend/build_sidecar.sh @@ -1,7 +1,8 @@ #!/usr/bin/env bash -# Build the frozen backend sidecar (single-file binary) with PyInstaller and -# stage it for Tauri as binaries/konduktor-sidecar-. -# Output: backend/dist/konduktor-sidecar + frontend/src-tauri/binaries/… +# Build the frozen backend sidecar (a onedir folder) with PyInstaller and stage +# it for Tauri as frontend/src-tauri/binaries/konduktor-sidecar/, which +# tauri.conf.json bundles as a resource folder (`sidecar/` in the app). +# Output: backend/dist/konduktor-sidecar/ + frontend/src-tauri/binaries/konduktor-sidecar/ # # One-time: pip install -r requirements-build.txt (into the backend venv). set -euo pipefail @@ -9,25 +10,20 @@ ROOT="$(cd "$(dirname "$0")" && pwd)" cd "$ROOT" PY="${PY:-.venv/bin/python}" "$PY" -m PyInstaller --noconfirm --clean konduktor-sidecar.spec -echo "Built: $ROOT/dist/konduktor-sidecar" +echo "Built: $ROOT/dist/konduktor-sidecar/" -# NOTE: do NOT re-codesign this binary. PyInstaller already ad-hoc signs the -# one-file bootloader AND its packed libraries (Python.framework, etc.) with a -# matching identity. Re-signing only the outer bootloader (e.g. `codesign -s -`) -# desyncs the Team IDs, so at runtime dlopen of the extracted Python framework -# fails with "different Team IDs" and the sidecar dies on launch (which makes -# the Tauri app panic: "backend sidecar did not report a port"). The app bundle -# is ad-hoc signed separately via tauri.conf.json `bundle.macOS.signingIdentity`, -# which seals this binary without re-signing it. +# NOTE: do NOT re-codesign anything in this folder. PyInstaller already ad-hoc +# signs the executable AND its collected libraries (Python, the .so/.dylib +# files) with a matching identity. Re-signing only some of them desyncs the +# Team IDs, so dlopen fails with "different Team IDs" and the sidecar dies on +# launch (the app then shows "Konduktor couldn't start"). The app bundle is +# ad-hoc signed separately via tauri.conf.json `bundle.macOS.signingIdentity`, +# which seals this folder as a resource without re-signing it. -# Stage for Tauri: the sidecar must be named with the host target triple so the -# shell plugin can resolve it in both dev and bundle. (rustc must be on PATH.) -if command -v rustc >/dev/null 2>&1; then - TRIPLE="$(rustc -vV | sed -n 's/host: //p')" - DEST="$ROOT/../frontend/src-tauri/binaries" - mkdir -p "$DEST" - cp "$ROOT/dist/konduktor-sidecar" "$DEST/konduktor-sidecar-$TRIPLE" - echo "Staged: $DEST/konduktor-sidecar-$TRIPLE" -else - echo "warning: rustc not found — skipped staging the Tauri sidecar binary" >&2 -fi +# Stage for Tauri. Replace the whole folder so no file from an older build +# survives; `cp -R` keeps PyInstaller's symlinks as symlinks. +DEST="$ROOT/../frontend/src-tauri/binaries" +mkdir -p "$DEST" +rm -rf "$DEST/konduktor-sidecar" +cp -R "$ROOT/dist/konduktor-sidecar" "$DEST/konduktor-sidecar" +echo "Staged: $DEST/konduktor-sidecar/" diff --git a/backend/konduktor-sidecar.spec b/backend/konduktor-sidecar.spec index fb2f436..3ab53f6 100644 --- a/backend/konduktor-sidecar.spec +++ b/backend/konduktor-sidecar.spec @@ -1,6 +1,14 @@ # PyInstaller spec for the Konduktor backend sidecar (Step 1 of the standalone -# build). Produces a single-file binary that serves the FastAPI API on a free -# loopback port. Build with: pyinstaller konduktor-sidecar.spec (or build_sidecar.sh) +# build). Produces a ONEDIR build — dist/konduktor-sidecar/ holding the +# executable plus `_internal/` — that serves the FastAPI API on a free loopback +# port. Build with: pyinstaller konduktor-sidecar.spec (or build_sidecar.sh) +# +# Onedir, NOT onefile: a onefile binary unpacks ~300 MB (1,000+ files, ~390 +# native libraries) into a NEW temp folder on every launch, and macOS checks +# every library it has not seen before (XProtect / syspolicyd) as it is +# dlopen()ed, keyed per file — so every launch paid ~10 s before the window +# appeared (measured 2026-10-12: the same libraries took 95 s fresh, 1 s once +# seen). Installed as a folder inside the app, they are checked once. # # The tricky bits this handles: # - uvicorn imports its loop/protocol backends dynamically → collect_submodules @@ -82,9 +90,8 @@ pyz = PYZ(a.pure) exe = EXE( pyz, a.scripts, - a.binaries, - a.datas, [], + exclude_binaries=True, name="konduktor-sidecar", debug=False, bootloader_ignore_signals=False, @@ -97,3 +104,12 @@ exe = EXE( codesign_identity=None, entitlements_file=None, ) + +coll = COLLECT( + exe, + a.binaries, + a.datas, + strip=False, + upx=False, + name="konduktor-sidecar", +) diff --git a/backend/requirements-build.txt b/backend/requirements-build.txt index fcfdead..52ca39f 100644 --- a/backend/requirements-build.txt +++ b/backend/requirements-build.txt @@ -1,4 +1,4 @@ # Build-only dependencies (not needed to run the backend in dev). -# Freezes the backend into a standalone sidecar binary for the desktop build. +# Freezes the backend into a standalone sidecar folder (onedir) for the desktop build. # See konduktor-sidecar.spec and build_sidecar.sh. pyinstaller>=6.16 # 6.16+ supports Python 3.14 diff --git a/frontend/index.html b/frontend/index.html index 528a475..21fe310 100644 --- a/frontend/index.html +++ b/frontend/index.html @@ -5,6 +5,11 @@ Konduktor + +
diff --git a/frontend/src-tauri/.gitignore b/frontend/src-tauri/.gitignore index 62374f3..45dbf4e 100644 --- a/frontend/src-tauri/.gitignore +++ b/frontend/src-tauri/.gitignore @@ -3,6 +3,6 @@ /target/ /gen/schemas -# Frozen backend sidecar — a build artifact (23MB); rebuild with +# Frozen backend sidecar (a onedir folder) — a build artifact; rebuild with # backend/build_sidecar.sh. The Rust/config that reference it ARE tracked. /binaries/ diff --git a/frontend/src-tauri/entitlements.plist b/frontend/src-tauri/entitlements.plist index 7cfb3e4..cc61cdd 100644 --- a/frontend/src-tauri/entitlements.plist +++ b/frontend/src-tauri/entitlements.plist @@ -3,12 +3,13 @@ com.apple.security.cs.disable-library-validation diff --git a/frontend/src-tauri/src/lib.rs b/frontend/src-tauri/src/lib.rs index 81d29a6..08ae495 100644 --- a/frontend/src-tauri/src/lib.rs +++ b/frontend/src-tauri/src/lib.rs @@ -1,22 +1,38 @@ // Konduktor desktop shell (Tauri v2). // -// The backend is the frozen Python sidecar (see backend/sidecar.py): on launch -// we spawn it, read the `KONDUKTOR_PORT=` line it prints on stdout, wait for -// it to actually accept connections, then create the app window with an -// initialization script that hands the frontend its API base -// (`window.__KONDUKTOR_API__`). The sidecar is killed when the app exits. +// The backend is the frozen Python sidecar (see backend/sidecar.py), a +// PyInstaller ONEDIR folder bundled as the `sidecar/` resource — not an +// `externalBin`, which must be one file. A one-file build unpacked ~390 native +// libraries into a new temp folder on every launch, and macOS scans each +// library it has not seen before as it loads, so the window took ~10 s to +// appear; installed as a folder they are scanned once. +// +// The window opens AT ONCE and shows the startup screen (StartupScreen.tsx) +// while the backend starts: a first launch after an install or update still +// waits for that one-time scan, and a window that appears seconds late looks +// like an app that failed to open. Meanwhile we spawn the sidecar, read the +// `KONDUKTOR_PORT=` line it prints on stdout and wait for the socket to +// accept connections. The page asks `backend_status` and listens for +// `konduktor://backend` (starting / ready + url / stopped + the output's last +// lines); `backend_restart` is its Try again. There is no timeout here — a +// fresh install can take a minute — so the page decides when to ask the user. +// The sidecar is killed when the app exits. // // Quitting ASKS FIRST. Closing the window or Cmd/Ctrl+Q is prevented and -// becomes a `konduktor://quit-requested` event; the frontend (QuitGuard.tsx) -// acknowledges it, checks for unsaved changes and either quits (`quit_now`) or -// asks Save / Discard / Cancel. The sidecar must outlive that question — a -// Save or Discard runs in it — so it is killed only once the app really exits. -// If the webview does not acknowledge within ~2 s (hung, or not loaded yet), -// the app quits anyway: a broken page must never make the app unquittable. -use std::sync::atomic::{AtomicBool, Ordering}; +// becomes a `konduktor://quit-requested` event; the frontend (QuitGuard.tsx, +// or the startup screen before the app has loaded) acknowledges it, checks for +// unsaved changes and either quits (`quit_now`) or asks Save / Discard / +// Cancel. The sidecar must outlive that question — a Save or Discard runs in +// it — so it is killed only once the app really exits. If the webview does not +// acknowledge within ~2 s (hung, or not loaded yet), the app quits anyway: a +// broken page must never make the app unquittable. +use std::collections::VecDeque; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::Mutex; use std::time::Duration; +use serde::Serialize; +use tauri::window::Color; use tauri::{AppHandle, Emitter, Manager, RunEvent, WebviewUrl, WebviewWindowBuilder, WindowEvent}; use tauri_plugin_shell::process::{CommandChild, CommandEvent}; use tauri_plugin_shell::ShellExt; @@ -24,6 +40,26 @@ use tauri_plugin_shell::ShellExt; /// Holds the running sidecar child so we can terminate it on exit. struct Sidecar(Mutex>); +/// How many of the sidecar's last output lines a "couldn't start" report keeps. +const LOG_LINES: usize = 30; + +/// What the startup screen shows. Serialised as `{"state": "starting"}`, +/// `{"state": "ready", "url": …}` or `{"state": "stopped", "code", "signal", "log"}`. +#[derive(Clone, Serialize)] +#[serde(tag = "state", rename_all = "snake_case")] +enum BackendStatus { + Starting, + Ready { url: String }, + Stopped { code: Option, signal: Option, log: Vec }, +} + +/// The backend's current status, plus a generation counter: each spawn bumps +/// it, so events from a sidecar that was replaced (Try again) are ignored. +struct Backend { + status: Mutex, + generation: AtomicU64, +} + /// Quit handshake state: `allowed` once the frontend (or the timeout) has said /// quit; `acked` once the frontend has seen the current request. struct Quit { @@ -59,6 +95,125 @@ fn request_quit(app: &AppHandle) { }); } +/// Record a new status for generation `gen` (ignored if a newer sidecar has +/// been spawned since) and tell the page. +fn set_status(app: &AppHandle, gen: u64, status: BackendStatus) { + let backend = app.state::(); + if backend.generation.load(Ordering::SeqCst) != gen { + return; + } + *backend.status.lock().unwrap() = status.clone(); + let _ = app.emit("konduktor://backend", status); +} + +fn push_lines(log: &mut VecDeque, bytes: &[u8]) { + for line in String::from_utf8_lossy(bytes).lines() { + if log.len() == LOG_LINES { + log.pop_front(); + } + log.push_back(line.to_string()); + } +} + +/// Spawn the sidecar and follow it until it is serving (ready) or exits (stopped). +fn start_backend(app: &AppHandle) { + kill_sidecar(app); + let gen = app.state::().generation.fetch_add(1, Ordering::SeqCst) + 1; + set_status(app, gen, BackendStatus::Starting); + + // The frozen backend lives in the bundled `sidecar/` folder (staged into + // src-tauri/binaries/ by backend/build_sidecar.*). + let exe = if cfg!(windows) { "konduktor-sidecar.exe" } else { "konduktor-sidecar" }; + let spawned = app + .path() + .resource_dir() + .map_err(|e| e.to_string()) + .and_then(|dir| { + let program = dir.join("sidecar").join(exe); + app.shell() + .command(&program) + .spawn() + .map_err(|e| format!("{}: {e}", program.display())) + }); + let (mut rx, child) = match spawned { + Ok(pair) => pair, + Err(e) => { + let log = vec![format!("Could not start the library service: {e}")]; + set_status(app, gen, BackendStatus::Stopped { code: None, signal: None, log }); + return; + } + }; + app.state::().0.lock().unwrap().replace(child); + + let handle = app.clone(); + tauri::async_runtime::spawn(async move { + let mut log = VecDeque::with_capacity(LOG_LINES); + let mut announced = false; + // Keep draining to the end, so the sidecar's pipes never fill and block it. + while let Some(event) = rx.recv().await { + match event { + CommandEvent::Stdout(bytes) => { + if !announced { + let text = String::from_utf8_lossy(&bytes); + let port = text.lines().find_map(|line| { + line.trim().strip_prefix("KONDUKTOR_PORT=")?.trim().parse::().ok() + }); + if let Some(port) = port { + announced = true; + wait_until_serving(handle.clone(), gen, port); + } + } + push_lines(&mut log, &bytes); + } + CommandEvent::Stderr(bytes) => push_lines(&mut log, &bytes), + CommandEvent::Error(e) => push_lines(&mut log, e.as_bytes()), + CommandEvent::Terminated(payload) => { + let status = BackendStatus::Stopped { + code: payload.code, + signal: payload.signal, + log: log.iter().cloned().collect(), + }; + set_status(&handle, gen, status); + } + _ => {} + } + } + }); +} + +/// The port line is printed before uvicorn binds: report ready once the socket +/// actually accepts connections (or give up quietly if this sidecar is gone). +fn wait_until_serving(app: AppHandle, gen: u64, port: u16) { + tauri::async_runtime::spawn(async move { + loop { + let backend = app.state::(); + let current = backend.generation.load(Ordering::SeqCst) == gen + && matches!(*backend.status.lock().unwrap(), BackendStatus::Starting); + if !current { + return; + } + if std::net::TcpStream::connect(("127.0.0.1", port)).is_ok() { + let url = format!("http://127.0.0.1:{port}"); + set_status(&app, gen, BackendStatus::Ready { url }); + return; + } + tokio::time::sleep(Duration::from_millis(50)).await; + } + }); +} + +/// Where the backend is: the startup screen asks once on load, then listens. +#[tauri::command] +fn backend_status(app: AppHandle) -> BackendStatus { + app.state::().status.lock().unwrap().clone() +} + +/// The startup screen's Try again. +#[tauri::command] +fn backend_restart(app: AppHandle) { + start_backend(&app); +} + /// The frontend has seen the quit request (it may now take as long as it likes). #[tauri::command] fn quit_ack(app: AppHandle) { @@ -82,8 +237,15 @@ pub fn run() { tauri::Builder::default() .plugin(tauri_plugin_shell::init()) .manage(Sidecar(Mutex::new(None))) + .manage(Backend { status: Mutex::new(BackendStatus::Starting), generation: AtomicU64::new(0) }) .manage(Quit { allowed: AtomicBool::new(false), acked: AtomicBool::new(false) }) - .invoke_handler(tauri::generate_handler![quit_ack, quit_cancel, quit_now]) + .invoke_handler(tauri::generate_handler![ + backend_status, + backend_restart, + quit_ack, + quit_cancel, + quit_now + ]) .on_window_event(|window, event| { if let WindowEvent::CloseRequested { api, .. } = event { let app = window.app_handle(); @@ -102,71 +264,22 @@ pub fn run() { )?; } - let handle = app.handle().clone(); + start_backend(app.handle()); - // Spawn the frozen backend. In dev/bundle the shell plugin resolves - // the sidecar from `binaries/konduktor-sidecar-`. - let (mut rx, child) = app - .shell() - .sidecar("konduktor-sidecar") - .expect("sidecar binary not found (build it into src-tauri/binaries/)") - .spawn() - .expect("failed to spawn backend sidecar"); - app.state::().0.lock().unwrap().replace(child); - - tauri::async_runtime::block_on(async move { - // Read stdout until the backend announces its port (bounded so a - // misbehaving sidecar can't hang the launch forever). - let find_port = async { - while let Some(event) = rx.recv().await { - if let CommandEvent::Stdout(bytes) = event { - let text = String::from_utf8_lossy(&bytes); - for line in text.lines() { - if let Some(p) = line.trim().strip_prefix("KONDUKTOR_PORT=") { - if let Ok(n) = p.trim().parse::() { - return Some(n); - } - } - } - } - } - None - }; - let port = tokio::time::timeout(Duration::from_secs(20), find_port) - .await - .ok() - .flatten() - .expect("backend sidecar did not report a port"); - - // Keep draining events so the sidecar's stdout/stderr pipes never - // fill and block it; the task ends when the child exits. - tauri::async_runtime::spawn(async move { while rx.recv().await.is_some() {} }); - - // Wait for the socket to actually accept connections (the port - // line is printed before uvicorn binds). - for _ in 0..200 { - if std::net::TcpStream::connect(("127.0.0.1", port)).is_ok() { - break; - } - std::thread::sleep(Duration::from_millis(50)); - } - - let inject = - format!("window.__KONDUKTOR_API__ = 'http://127.0.0.1:{port}';"); - WebviewWindowBuilder::new(&handle, "main", WebviewUrl::App("index.html".into())) - .title("Konduktor") - .inner_size(1400.0, 900.0) - .min_inner_size(900.0, 600.0) - // On Windows the webview would otherwise be served from - // https://tauri.localhost, and fetching the sidecar over - // http://127.0.0.1 would be blocked as mixed content. Force - // the http custom-protocol scheme so both are http. (No-op on - // macOS, which uses the tauri:// scheme.) - .use_https_scheme(false) - .initialization_script(&inject) - .build() - .expect("failed to create the main window"); - }); + WebviewWindowBuilder::new(app, "main", WebviewUrl::App("index.html".into())) + .title("Konduktor") + .inner_size(1400.0, 900.0) + .min_inner_size(900.0, 600.0) + // The page's own base colour (ink-950), so the first frame — + // before any CSS has loaded — is dark rather than white. + .background_color(Color(5, 6, 10, 255)) + // On Windows the webview would otherwise be served from + // https://tauri.localhost, and fetching the sidecar over + // http://127.0.0.1 would be blocked as mixed content. Force + // the http custom-protocol scheme so both are http. (No-op on + // macOS, which uses the tauri:// scheme.) + .use_https_scheme(false) + .build()?; Ok(()) }) diff --git a/frontend/src-tauri/tauri.conf.json b/frontend/src-tauri/tauri.conf.json index cb8b1e0..ed34927 100644 --- a/frontend/src-tauri/tauri.conf.json +++ b/frontend/src-tauri/tauri.conf.json @@ -19,7 +19,6 @@ "bundle": { "active": true, "targets": "all", - "externalBin": ["binaries/konduktor-sidecar"], "icon": [ "icons/32x32.png", "icons/128x128.png", diff --git a/frontend/src-tauri/tauri.macos.conf.json b/frontend/src-tauri/tauri.macos.conf.json new file mode 100644 index 0000000..33d942e --- /dev/null +++ b/frontend/src-tauri/tauri.macos.conf.json @@ -0,0 +1,8 @@ +{ + "$schema": "../node_modules/@tauri-apps/cli/config.schema.json", + "bundle": { + "macOS": { + "files": { "Resources/sidecar": "binaries/konduktor-sidecar" } + } + } +} diff --git a/frontend/src-tauri/tauri.windows.conf.json b/frontend/src-tauri/tauri.windows.conf.json new file mode 100644 index 0000000..d79ff33 --- /dev/null +++ b/frontend/src-tauri/tauri.windows.conf.json @@ -0,0 +1,6 @@ +{ + "$schema": "../node_modules/@tauri-apps/cli/config.schema.json", + "bundle": { + "resources": { "binaries/konduktor-sidecar/": "sidecar/" } + } +} diff --git a/frontend/src/api.ts b/frontend/src/api.ts index 0b0f0b8..e58ce42 100644 --- a/frontend/src/api.ts +++ b/frontend/src/api.ts @@ -837,14 +837,15 @@ export interface PrefixSuggestions { } // API origin. In the packaged desktop app the frontend is served from -// tauri://localhost, so it can't use relative /api paths — the Tauri shell -// injects window.__KONDUKTOR_API__ (the sidecar's http://127.0.0.1:) -// before any app script runs. In the browser dev server it's undefined, so we -// fall back to relative URLs and let Vite proxy /api to the backend. -export const API_BASE: string = - (typeof window !== 'undefined' && - (window as unknown as { __KONDUKTOR_API__?: string }).__KONDUKTOR_API__) || - '' +// tauri://localhost, so it can't use relative /api paths: the sidecar's +// http://127.0.0.1: is only known once it has started, and the startup +// screen (StartupScreen.tsx) sets it here before anything else renders. In the +// browser dev server it stays '', so URLs are relative and Vite proxies /api. +export let API_BASE = '' + +export function setApiBase(url: string): void { + API_BASE = url +} async function getJSON(url: string): Promise { const res = await fetch(API_BASE + url) diff --git a/frontend/src/components/StartupScreen.tsx b/frontend/src/components/StartupScreen.tsx new file mode 100644 index 0000000..336c005 --- /dev/null +++ b/frontend/src/components/StartupScreen.tsx @@ -0,0 +1,464 @@ +import { useEffect, useRef, useState, type ReactNode } from 'react' +import { createPortal } from 'react-dom' +import { setApiBase } from '../api' +import { Icon } from '../lib/icons' + +/** + * What the desktop window shows while the backend starts, and the gate that + * keeps the app from rendering before it can reach the backend. + * + * The shell (src-tauri/src/lib.rs) opens the window at once and starts the + * sidecar beside it; this asks `backend_status` and listens for + * `konduktor://backend`. A normal launch is about half a second. The first + * launch after an install or update can take much longer — macOS checks every + * native library in the sidecar once — so after `SLOW_MS` a note says why, + * and after `STUCK_MS` the user may quit or keep waiting. If the sidecar + * exits, its last output is shown with Try again (`backend_restart`). + * + * Until the backend is ready, nothing else is mounted: App, QuitGuard and + * UpdateCheck would all query an API with no address yet. So this answers + * the shell's quit request itself (there is nothing unsaved to ask about), + * and stops answering once ready, when QuitGuard takes over. + * + * In a plain browser (dev) there is no shell and Vite proxies /api, so the + * children render at once. + */ + +type BackendStatus = + | { state: 'starting' } + | { state: 'ready'; url: string } + | { state: 'stopped'; code: number | null; signal: number | null; log: string[] } + +/** When the "takes longer" note appears. */ +const SLOW_MS = 6_000 +/** When the user is offered Quit / Keep waiting (and again after each wait). */ +const STUCK_MS = 90_000 +/** The cross-fade into the app. */ +const FADE_MS = 450 + +const IN_SHELL = typeof window !== 'undefined' && '__TAURI_INTERNALS__' in window + +export function StartupGate({ children }: { children: ReactNode }) { + const [status, setStatus] = useState(null) + const [ready, setReady] = useState(!IN_SHELL) + const [leaving, setLeaving] = useState(false) + const [gone, setGone] = useState(!IN_SHELL) + + // The backend's status: asked once, then followed. An event that arrives + // before the answer is newer than it, so the answer is then dropped. + useEffect(() => { + if (!IN_SHELL) return + let unlisten: (() => void) | undefined + let cancelled = false + void (async () => { + const [{ listen }, { invoke }] = await Promise.all([ + import('@tauri-apps/api/event'), + import('@tauri-apps/api/core'), + ]) + let heard = false + const off = await listen('konduktor://backend', (e) => { + heard = true + setStatus(e.payload) + }) + if (cancelled) return off() + unlisten = off + const now = await invoke('backend_status') + if (!heard && !cancelled) setStatus(now) + })() + return () => { + cancelled = true + unlisten?.() + } + }, []) + + // Ready: point the API at the sidecar, mount the app, fade this out over it. + // Once ready it stays ready — a later crash is not a startup problem. + useEffect(() => { + if (status?.state !== 'ready' || ready) return + setApiBase(status.url) + setReady(true) + setLeaving(true) + const t = window.setTimeout(() => setGone(true), FADE_MS) + return () => window.clearTimeout(t) + }, [status, ready]) + + // Before the app is mounted, a quit request is answered here: nothing can + // be unsaved yet. Stops at ready, so it never races QuitGuard. + useEffect(() => { + if (!IN_SHELL || ready) return + let unlisten: (() => void) | undefined + let cancelled = false + void (async () => { + const [{ listen }, { invoke }] = await Promise.all([ + import('@tauri-apps/api/event'), + import('@tauri-apps/api/core'), + ]) + const off = await listen('konduktor://quit-requested', async () => { + await invoke('quit_ack') + await invoke('quit_now') + }) + if (cancelled) off() + else unlisten = off + })() + return () => { + cancelled = true + unlisten?.() + } + }, [ready]) + + return ( + <> + {ready && children} + {!gone && } + + ) +} + +async function shell(command: 'backend_restart' | 'quit_now') { + const { invoke } = await import('@tauri-apps/api/core') + await invoke(command) +} + +function StartupScreen({ status, leaving }: { status: BackendStatus | null; leaving: boolean }) { + const stopped = status?.state === 'stopped' ? status : null + return createPortal( +
+ {stopped ? : } +
+ v{__APP_VERSION__} +
+
, + document.body, + ) +} + +/** The OS doing the checking, for the slow-launch note. */ +function osName(): string { + const ua = navigator.userAgent + if (ua.includes('Windows')) return 'Windows' + if (ua.includes('Mac')) return 'macOS' + return 'your system' +} + +function Starting() { + // Timed from mount: Try again replaces the failure card with a fresh one, + // so each attempt gets its own clock. + const [startedAt] = useState(() => Date.now()) + const [stuckAt, setStuckAt] = useState(STUCK_MS) + const [elapsed, setElapsed] = useState(0) + useEffect(() => { + const t = window.setInterval(() => setElapsed(Date.now() - startedAt), 250) + return () => window.clearInterval(t) + }, [startedAt]) + + const slow = elapsed >= SLOW_MS + const stuck = elapsed >= stuckAt + return ( +
+ +
Konduktor
+
+ {stuck ? 'Still starting…' : 'Starting…'} +
+

+ The first launch after installing or updating takes longer while {osName()} checks the app. Later + launches start in a second or two. +

+
+ + +
+
+ ) +} + +function StoppedCard({ status }: { status: Extract }) { + const [busy, setBusy] = useState(false) + const [copied, setCopied] = useState(false) + const logRef = useRef(null) + const summary = + status.code !== null + ? `The library service exited with code ${status.code}.` + : status.signal !== null + ? `The library service was stopped by signal ${status.signal}.` + : null + const lines = status.log.length ? status.log : ['It wrote nothing before stopping.'] + const details = [`Konduktor v${__APP_VERSION__}`, ...(summary ? [summary] : []), ...lines].join('\n') + + // Show the end of the output: that is where the error is. + useEffect(() => { + const el = logRef.current + if (el) el.scrollTop = el.scrollHeight + }, [status]) + + const copy = async () => { + try { + await navigator.clipboard.writeText(details) + setCopied(true) + window.setTimeout(() => setCopied(false), 2000) + } catch { + // No clipboard access: select the text so Cmd/Ctrl+C works. + const el = logRef.current + if (!el) return + const range = document.createRange() + range.selectNodeContents(el) + window.getSelection()?.removeAllRanges() + window.getSelection()?.addRange(range) + } + } + + const retry = async () => { + setBusy(true) + try { + await shell('backend_restart') + } finally { + setBusy(false) + } + } + + return ( +
+
+ + + +
+

+ Konduktor couldn't start +

+

+ Its library service stopped before it was ready. Nothing in your libraries was changed. Try again, and + if it keeps happening, send the details below with your report. +

+
+
+
+        {summary && 
{summary}
} + {lines.map((line, i) => ( +
+ {line || ' '} +
+ ))} +
+
+ +
+ + +
+
+ ) +} + +// ---- The mark: the app icon, with a track scrolling under a fixed playhead ---- + +const BEAT = 60 / 128 +/** CSS px per second of audio, at the mark's 104 px. */ +const SPEED = 46 +/** 2 px bars with a 1 px gap: the main waveform's rhythm. */ +const BAR = 2 +const SLOT = 3 +/** The icon's own four bands, back to front. */ +const BANDS = ['#ff6a3d', '#8f6bff', '#3f9dff', '#7fe6ff'] + +const jitter = (i: number) => { + const x = Math.sin(i * 12.9898) * 43758.5453 + return x - Math.floor(x) +} + +/** Band levels (0..1) of a generated house track at time t: a kick on every + * beat, offbeat bass and hats, a clap on 2 and 4, a fill every 16 beats. */ +function levels(t: number) { + const n = Math.floor(t / BEAT) + const pos = t - n * BEAT + const in16 = n % 16 + const fill = in16 >= 14 + const sixteenth = BEAT / 4 + const p16 = t % sixteenth + const kick = fill ? 0 : Math.exp(-pos / 0.11) + const bass = pos > BEAT / 2 ? 0.5 * Math.exp(-(pos - BEAT / 2) / 0.16) : 0 + const roll = fill ? 0.35 + (0.5 * ((in16 - 14) * 4 + Math.floor(pos / sixteenth))) / 8 : 0 + const clap = (n % 2 === 1 ? 0.8 : 0) * Math.exp(-pos / 0.07) + roll * Math.exp(-p16 / 0.05) + const pad = 0.22 + 0.08 * Math.sin(t * 0.9) + const hat = 0.85 * Math.exp(-Math.abs(pos - BEAT / 2) / 0.025) + 0.3 * Math.exp(-p16 / 0.02) + return { low: Math.max(kick, bass), mid: Math.max(clap, pad, kick * 0.5), high: Math.max(hat, clap * 0.6) } +} + +function drawWave(ctx: CanvasRenderingContext2D, w: number, h: number, scroll: number) { + ctx.clearRect(0, 0, w, h) + const mid = h / 2 + const half = h * 0.34 + const centre = w / 2 + const first = Math.floor(scroll / SLOT) - 1 + const last = first + Math.ceil(w / SLOT) + 2 + for (let i = first; i <= last; i++) { + const x = i * SLOT - scroll + const t = (i * SLOT) / SPEED + // The peak over the slot, so a kick never falls between two samples. + const a = levels(t) + const b = levels(t + SLOT / SPEED / 2) + const low = Math.max(a.low, b.low) + const md = Math.max(a.mid, b.mid) + const hi = Math.max(a.high, b.high) + const j = 0.9 + 0.2 * jitter(i) + const h0 = half * Math.min(1, (0.16 + 0.84 * Math.max(low, md * 0.8, hi * 0.55)) * j) + const h1 = Math.min(h0 * 0.86, half * (0.1 + 0.6 * md) * j) + const h2 = Math.min(h1 * 0.84, half * (0.07 + 0.5 * hi) * j) + const h3 = Math.min(h2 * 0.78, half * (0.04 + 0.32 * hi) * j) + // Played audio, left of the playhead, sits dimmer, as on a deck. + ctx.globalAlpha = x + BAR / 2 < centre ? 0.6 : 1 + ;[h0, h1, h2, h3].forEach((bh, k) => { + ctx.fillStyle = BANDS[k] + ctx.fillRect(x, mid - bh, BAR, bh * 2) + }) + } + ctx.globalAlpha = 1 + // Bars enter and leave softly at the icon's edges. + ctx.globalCompositeOperation = 'destination-in' + const g = ctx.createLinearGradient(0, 0, w, 0) + g.addColorStop(0, 'rgba(0,0,0,0)') + g.addColorStop(0.14, '#000') + g.addColorStop(0.86, '#000') + g.addColorStop(1, 'rgba(0,0,0,0)') + ctx.fillStyle = g + ctx.fillRect(0, 0, w, h) + ctx.globalCompositeOperation = 'source-over' +} + +function StartupMark() { + const canvas = useRef(null) + useEffect(() => { + const el = canvas.current + const ctx = el?.getContext('2d') + if (!el || !ctx) return + const w = el.offsetWidth + const h = el.offsetHeight + const dpr = window.devicePixelRatio || 1 + el.width = Math.round(w * dpr) + el.height = Math.round(h * dpr) + ctx.setTransform(dpr, 0, 0, dpr, 0, 0) + // Reduced motion: one still frame. + if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) { + drawWave(ctx, w, h, 0) + return + } + let raf = 0 + let start: number | null = null + const frame = (now: number) => { + start ??= now + drawWave(ctx, w, h, ((now - start) / 1000) * SPEED) + raf = requestAnimationFrame(frame) + } + raf = requestAnimationFrame(frame) + return () => cancelAnimationFrame(raf) + }, []) + + return ( +
+ + + + + + + + + + + + + + + + + + + + + {/* Clipped to the icon's rounded square: rx 22 inside a 2-unit inset. */} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ ) +} diff --git a/frontend/src/main.tsx b/frontend/src/main.tsx index 0e961fe..c3f8a45 100644 --- a/frontend/src/main.tsx +++ b/frontend/src/main.tsx @@ -11,6 +11,7 @@ import { ConfirmHost } from './lib/confirm.tsx' import { DragLayer } from './lib/drag.tsx' import { QuitGuard } from './components/QuitGuard.tsx' import { preventHistoryNavigation } from './lib/noNavigation.ts' +import { StartupGate } from './components/StartupScreen.tsx' preventHistoryNavigation() @@ -28,15 +29,18 @@ createRoot(document.getElementById('root')!).render( {/* Behind everything, the picker screen included: every surface is glass over it. */} - - {/* Mounted beside App so the update dialog shows even on the picker screen. */} - - {/* askConfirm()'s dialogs — the app's replacement for window.confirm. */} - - {/* Save · Discard · Cancel when quitting with unsaved changes. */} - - {/* The ghost under the cursor while dragging tracks or playlists. */} - + {/* The desktop app's startup screen: nothing below mounts until the backend answers. */} + + + {/* Mounted beside App so the update dialog shows even on the picker screen. */} + + {/* askConfirm()'s dialogs — the app's replacement for window.confirm. */} + + {/* Save · Discard · Cancel when quitting with unsaved changes. */} + + {/* The ghost under the cursor while dragging tracks or playlists. */} + + , )