Fixed slow build startup time and implemented loading screen

This commit is contained in:
patben8 committed 2026-10-12 13:20:00 +02:00
1 parent a0df683fee
commit d474c662db
18 files changed
+790 -148

No files matched your search

+4 -3
View File
@@ -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-<triple>[.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: |
+3 -2
View File
@@ -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-<triple>.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
+26 -1
View File
@@ -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
`<resources>/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
+3 -3
View File
@@ -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
+11 -9
View File
@@ -1,6 +1,7 @@
# Build the frozen backend sidecar on Windows (PyInstaller) and stage it for
# Tauri as binaries\konduktor-sidecar-<target-triple>.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\"
+19 -23
View File
@@ -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-<target-triple>.
# 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/"
+20 -4
View File
@@ -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",
)
+1 -1
View File
@@ -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
+5
View File
@@ -5,6 +5,11 @@
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Konduktor</title>
<!-- The app's base colour before any stylesheet loads, so the window's
first frame is dark (the shell sets the same colour on the window).
On body ONLY: a background on html stops body's from spreading to the
page, and body's own box then paints over AmbientBackdrop (-z-10). -->
<style>:root { color-scheme: dark; } body { background: #05060a; }</style>
</head>
<body>
<div id="root"></div>
+1 -1
View File
@@ -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/
+7 -6
View File
@@ -3,12 +3,13 @@
<plist version="1.0">
<dict>
<!--
The backend is a PyInstaller one-file binary: at launch it extracts its
bundled Python.framework to a temp dir and dlopen()s it. Tauri signs every
nested binary with the hardened runtime (adhoc,runtime), which enforces
library validation — and the extracted framework has a different Team ID
than the ad-hoc-signed bootloader, so it's rejected ("different Team IDs")
and the sidecar dies on launch. Disabling library validation lets it load.
The backend is a PyInstaller onedir folder (Contents/Resources/sidecar)
whose executable dlopen()s its own ad-hoc-signed Python.framework and
native libraries. Under the hardened runtime (adhoc,runtime) library
validation rejects code with a different Team ID ("different Team IDs"),
which killed the sidecar on launch when it was a one-file binary Tauri
signed itself. Kept disabled so any process the app's signature covers
can still load those libraries.
-->
<key>com.apple.security.cs.disable-library-validation</key>
<true/>
+190 -77
View File
@@ -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=<n>` 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=<n>` 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<Option<CommandChild>>);
/// 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<i32>, signal: Option<i32>, log: Vec<String> },
}
/// 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<BackendStatus>,
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::<Backend>();
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<String>, 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::<Backend>().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::<Sidecar>().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::<u16>().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::<Backend>();
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::<Backend>().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-<target-triple>`.
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::<Sidecar>().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::<u16>() {
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(())
})
-1
View File
@@ -19,7 +19,6 @@
"bundle": {
"active": true,
"targets": "all",
"externalBin": ["binaries/konduktor-sidecar"],
"icon": [
"icons/32x32.png",
"icons/128x128.png",
+8
View File
@@ -0,0 +1,8 @@
{
"$schema": "../node_modules/@tauri-apps/cli/config.schema.json",
"bundle": {
"macOS": {
"files": { "Resources/sidecar": "binaries/konduktor-sidecar" }
}
}
}
@@ -0,0 +1,6 @@
{
"$schema": "../node_modules/@tauri-apps/cli/config.schema.json",
"bundle": {
"resources": { "binaries/konduktor-sidecar/": "sidecar/" }
}
}
+9 -8
View File
@@ -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:<port>)
// 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:<port> 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<T>(url: string): Promise<T> {
const res = await fetch(API_BASE + url)
+464
View File
@@ -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<BackendStatus | null>(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<BackendStatus>('konduktor://backend', (e) => {
heard = true
setStatus(e.payload)
})
if (cancelled) return off()
unlisten = off
const now = await invoke<BackendStatus>('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 && <StartupScreen status={status} leaving={leaving} />}
</>
)
}
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(
<div
className="fixed inset-0 z-[90] flex items-center justify-center p-6 transition-opacity ease-out"
style={{ opacity: leaving ? 0 : 1, transitionDuration: `${FADE_MS}ms`, pointerEvents: leaving ? 'none' : undefined }}
>
{stopped ? <StoppedCard status={stopped} /> : <Starting />}
<div className="absolute inset-x-0 bottom-[22px] text-center font-mono text-[11px] tracking-[0.02em] text-faint">
v{__APP_VERSION__}
</div>
</div>,
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 (
<div className="flex flex-col items-center text-center">
<StartupMark />
<div className="mt-[22px] text-[26px] font-semibold tracking-[-0.02em]">Konduktor</div>
<div className="mt-1.5 min-h-[21px] text-sm text-muted" role="status" aria-live="polite">
{stuck ? 'Still starting…' : 'Starting…'}
</div>
<p
className="mt-[18px] max-w-[46ch] text-[13px] leading-[1.55] text-faint transition-[opacity,transform] duration-[600ms]"
style={{ opacity: slow ? 1 : 0, transform: slow ? 'none' : 'translateY(4px)' }}
aria-hidden={!slow}
>
The first launch after installing or updating takes longer while {osName()} checks the app. Later
launches start in a second or two.
</p>
<div
className="mt-4 flex justify-center gap-2 transition-opacity duration-[400ms]"
style={{ opacity: stuck ? 1 : 0, pointerEvents: stuck ? undefined : 'none' }}
aria-hidden={!stuck}
>
<button
tabIndex={stuck ? 0 : -1}
onClick={() => void shell('quit_now')}
className="btn-glass rounded-full px-4 py-2 text-sm text-muted hover:text-text"
>
Quit
</button>
<button
tabIndex={stuck ? 0 : -1}
onClick={() => setStuckAt(elapsed + STUCK_MS)}
className="btn-glass rounded-full px-4 py-2 text-sm text-muted hover:text-text"
>
Keep waiting
</button>
</div>
</div>
)
}
function StoppedCard({ status }: { status: Extract<BackendStatus, { state: 'stopped' }> }) {
const [busy, setBusy] = useState(false)
const [copied, setCopied] = useState(false)
const logRef = useRef<HTMLPreElement>(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 (
<div
role="alertdialog"
aria-modal="true"
aria-labelledby="startup-failed-title"
className="glass-overlay w-full max-w-[560px] overflow-hidden"
>
<div className="flex items-start gap-3.5 px-6 pb-4 pt-[22px]">
<span className="flex h-9 w-9 shrink-0 items-center justify-center rounded-xl bg-pink/10 text-pink shadow-[inset_0_0_0_1px_rgb(255_122_154/0.35)]">
<Icon name="warning" size={18} />
</span>
<div className="min-w-0">
<h2 id="startup-failed-title" className="text-base font-semibold tracking-[-0.01em]">
Konduktor couldn't start
</h2>
<p className="mt-1 text-[13px] leading-[1.55] text-muted">
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.
</p>
</div>
</div>
<pre
ref={logRef}
className="well mx-6 max-h-[180px] select-text overflow-auto rounded-xl px-3.5 py-3 font-mono text-[11.5px] leading-[1.6] text-muted"
>
{summary && <div>{summary}</div>}
{lines.map((line, i) => (
<div key={i} className={i === lines.length - 1 ? 'text-pink' : undefined}>
{line || ' '}
</div>
))}
</pre>
<div className="flex items-center gap-2 px-6 pb-5 pt-4">
<button onClick={() => void copy()} className="rounded-full px-2.5 py-2 text-sm text-faint hover:text-text">
{copied ? 'Copied' : 'Copy details'}
</button>
<div className="flex-1" />
<button
onClick={() => void shell('quit_now')}
className="btn-glass rounded-full px-4 py-2 text-sm text-muted hover:text-text"
>
Quit
</button>
<button
autoFocus
disabled={busy}
onClick={() => void retry()}
className="btn-primary rounded-full px-4 py-2 text-sm font-semibold disabled:opacity-50"
>
Try again
</button>
</div>
</div>
)
}
// ---- 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<HTMLCanvasElement>(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 (
<div
role="img"
aria-label="Konduktor"
className="relative h-[104px] w-[104px] [filter:drop-shadow(0_22px_40px_rgb(0_0_0/0.55))]"
>
<svg viewBox="0 0 100 100" className="absolute inset-0 h-full w-full" aria-hidden>
<defs>
<clipPath id="startup-clip">
<rect x="2" y="2" width="96" height="96" rx="22" />
</clipPath>
<filter id="startup-blur" filterUnits="userSpaceOnUse" x="-60" y="-60" width="220" height="220">
<feGaussianBlur stdDeviation="13" />
</filter>
</defs>
<g clipPath="url(#startup-clip)">
<rect width="100" height="100" fill="#07070d" />
<g filter="url(#startup-blur)">
<circle cx="22" cy="18" r="32" fill="#6d4aff" />
<circle cx="90" cy="28" r="26" fill="#e0409a" />
<circle cx="76" cy="96" r="32" fill="#12b5c9" />
<circle cx="8" cy="82" r="26" fill="#2f3fe0" />
</g>
<rect width="100" height="100" fill="#05060a" opacity="0.5" />
</g>
</svg>
{/* Clipped to the icon's rounded square: rx 22 inside a 2-unit inset. */}
<canvas
ref={canvas}
aria-hidden
className="absolute"
style={{ inset: '1.92%', width: '96.15%', height: '96.15%', borderRadius: '22.9%' }}
/>
<svg viewBox="0 0 100 100" className="absolute inset-0 h-full w-full" aria-hidden>
<defs>
<clipPath id="startup-clip-top">
<rect x="2" y="2" width="96" height="96" rx="22" />
</clipPath>
<filter id="startup-shadow" filterUnits="userSpaceOnUse" x="-20" y="-20" width="140" height="140">
<feGaussianBlur stdDeviation="2.2" />
</filter>
<linearGradient id="startup-sheen" x1="0" y1="0" x2="0" y2="1">
<stop offset="0" stopColor="#fff" stopOpacity=".16" />
<stop offset=".42" stopColor="#fff" stopOpacity="0" />
</linearGradient>
<linearGradient id="startup-rim" x1="0" y1="0" x2="0.4" y2="1">
<stop offset="0" stopColor="#fff" stopOpacity=".55" />
<stop offset=".5" stopColor="#fff" stopOpacity=".08" />
<stop offset="1" stopColor="#fff" stopOpacity=".22" />
</linearGradient>
</defs>
<g clipPath="url(#startup-clip-top)">
<g filter="url(#startup-shadow)" fill="#000" opacity=".95">
<rect x="45.5" y="11" width="9" height="78" />
</g>
<rect x="47.8" y="12" width="4.4" height="76" fill="#fff" />
<path d="M42 12h16L50 21z M42 88h16L50 79z" fill="#fff" />
<rect width="100" height="100" fill="url(#startup-sheen)" />
</g>
<rect x="2.4" y="2.4" width="95.2" height="95.2" rx="21.6" fill="none" stroke="url(#startup-rim)" strokeWidth=".8" />
</svg>
</div>
)
}
+13 -9
View File
@@ -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(
<QueryClientProvider client={queryClient}>
{/* Behind everything, the picker screen included: every surface is glass over it. */}
<AmbientBackdrop />
<App />
{/* Mounted beside App so the update dialog shows even on the picker screen. */}
<UpdateCheck />
{/* askConfirm()'s dialogs — the app's replacement for window.confirm. */}
<ConfirmHost />
{/* Save · Discard · Cancel when quitting with unsaved changes. */}
<QuitGuard />
{/* The ghost under the cursor while dragging tracks or playlists. */}
<DragLayer />
{/* The desktop app's startup screen: nothing below mounts until the backend answers. */}
<StartupGate>
<App />
{/* Mounted beside App so the update dialog shows even on the picker screen. */}
<UpdateCheck />
{/* askConfirm()'s dialogs — the app's replacement for window.confirm. */}
<ConfirmHost />
{/* Save · Discard · Cancel when quitting with unsaved changes. */}
<QuitGuard />
{/* The ghost under the cursor while dragging tracks or playlists. */}
<DragLayer />
</StartupGate>
</QueryClientProvider>
</StrictMode>,
)