diff --git a/CLAUDE.md b/CLAUDE.md index db5379f..0199eb4 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -170,8 +170,9 @@ Two independent apps that talk over HTTP: (plus its pending tag fields and staged art, so Save still writes them to the new file). Either sets `` (the literal from `core/stem_file`), INFO bitrate/playtime/playtime_float/filesize(KB), VOLUMEID only where it - still names the volume, and clears AUDIO_ID (`_KEEP_AUDIO_ID_ON_STEM`, - pending the Traktor check). **Every START shifts by the time-base + still names the volume, and KEEPS AUDIO_ID (`_KEEP_AUDIO_ID_ON_STEM`: + measured in Traktor 4.5 — cleared, Traktor re-analyses on load and + re-measures a hand-set grid's BPM; kept, it touches nothing). **Every START shifts by the time-base difference**, the old offset read from `StemSwap.original_audio` — the original's bytes where they are NOW (parked, under a non-audio name, so `timebase.offset_ms(..., suffix=)` takes the original's suffix). Read @@ -322,6 +323,16 @@ Two independent apps that talk over HTTP: know the track. `trackAudioUrl`/`trackCuesFor` in `api.ts` are the one place that choice is made. - `app_state.py` — the one loaded library, and the **version-history commit**. + **`discard()`** (`POST /api/discard`, SaveBar's "Discard changes…", the + quit prompt's Discard) drops every unsaved edit through the adapter's own + `reload`, NOT `open` — reopening would re-run the missing-files check and + forget this session's relocation answers. The route stops (and WAITS for) + running batches first, as library open does (`_stop_batches`), or a batch + would keep writing into the reloaded library. Rekordbox's reload is a real + discard (`RekordboxStore.discard`): session rolled back and closed with its + engine, buffered ANLZ grids and journal cleared — before, it opened a second + connection and stayed "dirty". A reentrant `mutation` lock serialises + open / save / discard (and, next, a stem batch's swap step). History is app-level: the adapter returns the bytes it wrote plus a summary, and `AppState.save()` versions them. Every write path must go through it. - `library_id.py` — a **stable identity for a library that survives it being @@ -478,7 +489,13 @@ Two independent apps that talk over HTTP: same menu and the row's hover buttons, which share one set of actions. A Traktor folder's id is its PATH of names, so the `PATCH`/`DELETE` playlist routes take a `:path` param, a folder name may not contain `/`, - and renaming onto a sibling folder's name is refused), `SaveBar` (+ 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), `Toolbar` (search/filters; columns are chosen by right-clicking the table header), + and renaming onto a sibling folder's name is refused), `QuitGuard` (mounted in `main.tsx`: the desktop shell PREVENTS window close / + Cmd+Q and emits `konduktor://quit-requested`; this acks it (`quit_ack` — the + 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 + 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), `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, configurable columns, header sorting, inline double-click editing, and @@ -796,6 +813,12 @@ serialization path.** It enforces: removable library is never written beside, an unwritable location falls back rather than failing, and `paths.write_json` is atomic (curated user work, so `prefs.py`'s best-effort "any I/O error degrades to no prefs" is NOT adequate). +- `test_discard.py` — discarding unsaved edits through the route: the edit is + gone, the file and version history untouched, relocation answers and the + saved path mapping survive, the adapter object is the same (a reload, not a + reopen), and a running batch has stopped by the time discard returns; on + Rekordbox (temp copy, skipped when absent) the library is clean afterwards and + a later save writes nothing that was thrown away; read-only libraries 409. - `test_layering.py` — `core/` imports nothing platform-specific, and no adapter imports another platform's library (checked on real imports via AST, so merely naming a platform in a comment is fine). Rekordbox and OneLibrary deliberately diff --git a/backend/konduktor/adapters/rekordbox/adapter.py b/backend/konduktor/adapters/rekordbox/adapter.py index 1575d26..c484c2f 100644 --- a/backend/konduktor/adapters/rekordbox/adapter.py +++ b/backend/konduktor/adapters/rekordbox/adapter.py @@ -80,7 +80,9 @@ class RekordboxAdapter: self._store.close() def reload(self) -> None: - self._store._load() + """Re-read the library from disk, DISCARDING unsaved edits (see + `RekordboxStore.discard` for why a plain re-open is not enough).""" + self._store.discard() self._cloud_synced = self._store.cloud_synced self._rebuild() diff --git a/backend/konduktor/adapters/rekordbox/store.py b/backend/konduktor/adapters/rekordbox/store.py index 63afaeb..23b5c69 100644 --- a/backend/konduktor/adapters/rekordbox/store.py +++ b/backend/konduktor/adapters/rekordbox/store.py @@ -101,6 +101,24 @@ class RekordboxStore: self._content_cache: list | None = None self._by_id: dict[str, object] | None = None + def discard(self) -> None: + """Drop every unsaved edit and re-open the library as it is on disk. + + Three things hold edits here, and all three must go: the SQLAlchemy + session (rolled back, then closed with its engine — `_load()` alone + would open a SECOND connection and leak the first), the buffered grid + writes (which the next save would otherwise still write to ANLZ files), + and the journal (else the library keeps reporting unsaved changes). + """ + try: + self._db.session.rollback() + except Exception: # noqa: BLE001 — discarding must not fail halfway + pass + self.close() + self._journal = EditJournal() + self._pending_grids.clear() + self._load() + def close(self) -> None: """Release the session AND the pooled connection. diff --git a/backend/konduktor/adapters/traktor/store.py b/backend/konduktor/adapters/traktor/store.py index 4e948d0..e5f7335 100644 --- a/backend/konduktor/adapters/traktor/store.py +++ b/backend/konduktor/adapters/traktor/store.py @@ -1241,11 +1241,14 @@ class TraktorStore: return key_remap # ---- stem conversion --------------------------------------------------- - #: Whether a converted entry keeps Traktor's analysis fingerprint. It is a - #: fingerprint of the OLD file; cleared, Traktor re-analyses the new one on - #: load (the import precedent: prep survives). Settled by the milestone-2 - #: check in Traktor 4.5. - _KEEP_AUDIO_ID_ON_STEM = False + #: Whether a converted entry keeps Traktor's analysis fingerprint (AUDIO_ID). + #: KEPT, as measured in Traktor 4.5 (kit 5, 2026-09-30): with it kept, Traktor + #: loads the stem entry as it is — cues, grid and fingerprint untouched. With + #: it cleared, Traktor re-analyses on load: it keeps grid POSITIONS (even a + #: hand-nudged, unlocked one) but re-measures the grid's BPM (125.000023 -> + #: 125.00042), i.e. it rewrites prep the user set. The stem file's mix is the + #: same audio as the original, so the old fingerprint still describes it. + _KEEP_AUDIO_ID_ON_STEM = True def apply_stem_swaps(self, swaps: list, *, add_to_playlist: str | None = None) -> StemSwapResult: """Point entries at converted stem files ("repoint"), or add entries for diff --git a/backend/konduktor/app_state.py b/backend/konduktor/app_state.py index 257a3ac..b07b152 100644 --- a/backend/konduktor/app_state.py +++ b/backend/konduktor/app_state.py @@ -25,6 +25,7 @@ human summary, and this module versions them. from __future__ import annotations import os +import threading from pathlib import Path from . import __version__, adapters, history, library_id, prefs # noqa: F401 — registers adapters @@ -51,6 +52,11 @@ class AppState: # This open's missing-files check (see `relocation.py`). A new one per # open, which is what makes the dialog ask again on a reopen. self.relocation: RelocationCheck | None = None + # Serialises the operations that REPLACE or COMMIT the whole library — + # open, save, discard (and a stem batch's swap step). A save landing in + # the middle of another would commit a half-applied state; reentrant so + # one of them may call another. + self.mutation = threading.RLock() @property def loaded(self) -> bool: @@ -95,6 +101,10 @@ class AppState: pass def open(self, path: Path) -> None: + with self.mutation: + self._open(path) + + def _open(self, path: Path) -> None: # The registry picks the adapter by probing the file, not by extension — # a Rekordbox library is a .db and a Serato one is a directory. Raises on # an unrecognised or unparseable file; only commit once it has parsed. @@ -146,6 +156,10 @@ class AppState: cannot restore from. """ assert self.adapter is not None and self.path is not None + with self.mutation: + return self._save() + + def _save(self): outcome = self.adapter.save() # Not every platform is versioned. A library that is more than one file # has no single blob that IS the library, and it says so through its @@ -158,6 +172,17 @@ class AppState: ) return outcome, commit + def discard(self) -> None: + """Drop every unsaved edit: the library re-reads itself from disk. + + Through the adapter's own `reload`, NOT `open` — reopening would start a + new missing-files check and forget this session's relocation answers, + which are not edits and survive a reload (the store keeps them). + """ + assert self.adapter is not None + with self.mutation: + self.adapter.reload() + STATE = AppState() diff --git a/backend/konduktor/main.py b/backend/konduktor/main.py index a6aa0be..75c3ff1 100644 --- a/backend/konduktor/main.py +++ b/backend/konduktor/main.py @@ -162,16 +162,7 @@ def open_collection(body: OpenCollection) -> CollectionStatus: # This checks only that the path is there at all; `can_open()` decides. if not path.exists(): raise HTTPException(400, f"Not found: {path}") - # A running analysis writes into the library being replaced; stop it, and - # WAIT for it to stop — a job still finishing its current track would - # otherwise keep writing (or, for file work, keep moving files) after the - # switch. Batches check for a cancel between tracks, so this is short. - stopping = [job for kind in BATCH_JOBS for job in JOBS.active(kind)] - for job in stopping: - JOBS.cancel(job.id) - for job in stopping: - if not JOBS.wait(job.id, timeout=60): - log.warning("batch %s (%s) still running after cancel; opening anyway", job.id, job.kind) + _stop_batches() try: STATE.open(path) except AdapterError as ex: @@ -739,6 +730,22 @@ def state() -> EditState: return EditState(dirty=require_adapter().dirty, library=_library_info()) +@app.post("/api/discard", response_model=EditState) +def discard_changes() -> EditState: + """Drop every unsaved edit — the library re-reads itself from disk. + + A running batch is stopped first (and waited for): it writes into the + library being discarded, so it would otherwise keep adding edits to the + freshly reloaded one. + """ + adapter = require_adapter() + if not adapter.capabilities().writable: + raise HTTPException(409, "This library cannot be edited, so there is nothing to discard") + _stop_batches() + STATE.discard() + return state() + + @app.post("/api/reload") def reload_collection() -> dict: if not STATE.loaded: @@ -1039,6 +1046,22 @@ CUE_JOB = "auto-hotcues" BATCH_JOBS = (GRID_JOB, CUE_JOB) +def _stop_batches() -> None: + """Cancel every running batch analysis and WAIT for it to stop. + + Used wherever the library is about to be replaced or reloaded: a job still + finishing its current track would otherwise keep writing into it (or, for + file work, keep moving files) afterwards. Batches check for a cancel + between tracks, so this is short. + """ + stopping = [job for kind in BATCH_JOBS for job in JOBS.active(kind)] + for job in stopping: + JOBS.cancel(job.id) + for job in stopping: + if not JOBS.wait(job.id, timeout=60): + log.warning("batch %s (%s) still running after cancel; continuing", job.id, job.kind) + + def _require_no_batch() -> None: """An early, friendly refusal. Not race-free on its own — the batch routes START through `_submit_batch`, which re-checks under the registry's lock.""" diff --git a/backend/run_tests.sh b/backend/run_tests.sh index f4550ca..875a6ad 100755 --- a/backend/run_tests.sh +++ b/backend/run_tests.sh @@ -6,7 +6,7 @@ cd "$(dirname "${BASH_SOURCE[0]}")" source .venv/bin/activate fail=0 -for t in test_layering.py test_save_fidelity.py test_timebase.py test_stem_file.py test_stem_swap.py test_traktor_adapter.py test_rekordbox_adapter.py test_rekordbox_fidelity.py test_onelibrary_adapter.py test_import.py test_grid_detect.py test_auto_hotcues.py test_grid_batch.py test_bulk_remove.py test_folders.py test_picker.py test_relocate.py test_library_id.py test_exports.py test_export.py test_export_pioneer.py test_device_export.py test_phase3.py test_history.py; do +for t in test_layering.py test_save_fidelity.py test_timebase.py test_stem_file.py test_stem_swap.py test_traktor_adapter.py test_rekordbox_adapter.py test_rekordbox_fidelity.py test_onelibrary_adapter.py test_import.py test_grid_detect.py test_auto_hotcues.py test_grid_batch.py test_bulk_remove.py test_folders.py test_picker.py test_relocate.py test_library_id.py test_exports.py test_export.py test_export_pioneer.py test_device_export.py test_phase3.py test_history.py test_discard.py; do echo "──────────────────────────────────────────" echo "▶ $t" echo "──────────────────────────────────────────" diff --git a/backend/test_discard.py b/backend/test_discard.py new file mode 100644 index 0000000..0ce31cb --- /dev/null +++ b/backend/test_discard.py @@ -0,0 +1,131 @@ +"""Discarding unsaved edits (`POST /api/discard`, `AppState.discard`). + +Konduktor had no discard path at all: switching library dropped edits, quitting +killed the backend. Discard is also what a stem conversion's parked originals +will hang on, so it has to be exact. Pins: + + * Traktor: an edit is dropped, the library is clean, the file on disk and the + version history are untouched — and this session's relocation answers and + saved path mapping survive (they are not edits; reopening would lose them). + * A running batch is stopped BEFORE the reload, so it cannot keep writing + into the reloaded library. + * Rekordbox: the SQLAlchemy session, the buffered ANLZ grid writes and the + journal all go — a plain re-open left the library still "dirty" and the + next save still writing the discarded grids. + * A read-only library has nothing to discard (409). +""" +from __future__ import annotations + +import os +import shutil +import sys +import tempfile +import time +import warnings +from pathlib import Path +from types import SimpleNamespace + +warnings.filterwarnings("ignore") +os.environ["KONDUKTOR_DATA_DIR"] = tempfile.mkdtemp(prefix="konduktor-discard-appdata-") + +REAL = Path(__file__).resolve().parents[1] / "collection.nml" +FIXTURE = Path(__file__).resolve().parent / "fixtures" / "onelibrary" +failed = False + + +def check(label, cond, detail=""): + global failed + print(f" [{'PASS' if cond else 'FAIL'}] {label}" + (f" — {detail}" if detail and not cond else "")) + if not cond: + failed = True + + +print("== Traktor, through the routes ==") +with tempfile.TemporaryDirectory() as d: + work = Path(d) / "collection.nml" + shutil.copy2(REAL, work) + original = work.read_bytes() + os.environ["KONDUKTOR_NML"] = str(work) + from fastapi.testclient import TestClient + + import konduktor.main as main + from konduktor import history + from konduktor.core.pathmap import PathMapping + + with TestClient(main.app) as c: + a = main.require_adapter() + track = next(t for t in a.tracks if t.genre) + genre = track.genre # a string: the index updates Track objects in place + commits_before = len(history.list_history(work)) + r = c.patch("/api/tracks", json={"track_id": track.id, "fields": {"genre": "Discard me"}}) + check("(setup) an edit makes the library dirty", r.status_code == 200 and c.get("/api/state").json()["dirty"]) + session = [PathMapping.make("/Volumes/Gone", "/Volumes/Here")] + a.set_session_mappings(session) + a.set_path_mapping(PathMapping.make("/Old", "/New")) + + r = c.post("/api/discard") + check("discard answers with a clean state", r.status_code == 200 and r.json()["dirty"] is False, r.text[:200]) + a = main.require_adapter() + check("the edit is gone from the projection", a.track(track.id).genre == genre, a.track(track.id).genre) + check("the file on disk was never touched", work.read_bytes() == original) + check("no version was recorded", len(history.list_history(work)) == commits_before) + check("this session's relocation answers survive", a.store._session_mappings == session) + check("…and so does the saved path mapping", not a.store._path_mapping.empty) + check("the same adapter object: a reload, not a reopen", main.STATE.adapter is a) + + # A running batch is stopped (and waited for) before the reload. + main.grid_detect.detect_grid = lambda p, *x, **k: (time.sleep(0.05), SimpleNamespace(anchor=0.1, bpm=128.0))[1] + ids = [t.id for t in a.tracks[:60]] + jid = c.post("/api/tracks/grid/auto-batch", json={"track_ids": ids, "replace_existing": True}).json()["id"] + time.sleep(0.2) + r = c.post("/api/discard") + job = main.JOBS.get(jid) + check("a running batch has STOPPED by the time discard returns", job.finished, job.state) + time.sleep(0.2) + check("…and nothing it did survives the reload", c.get("/api/state").json()["dirty"] is False) + os.environ.pop("KONDUKTOR_NML", None) + +print("== Rekordbox: session, buffered grids and journal all go ==") +from konduktor.adapters.rekordbox import discovery # noqa: E402 +from konduktor.adapters.rekordbox.adapter import RekordboxAdapter # noqa: E402 + +found = discovery.detect_libraries() +if not found: + print(" (skipped: no Rekordbox library on this machine)") +else: + src = Path(found[0]["path"]) + with tempfile.TemporaryDirectory() as d: + work = Path(d) / "master.db" + shutil.copy2(src, work) + if (src.parent / "share").is_dir(): + shutil.copytree(src.parent / "share", Path(d) / "share") + before = work.read_bytes() + ad = RekordboxAdapter(work) + track = next(t for t in ad.tracks if t.title) + title = track.title + ad.set_track_metadata(track.id, {"title": "Discard me"}) + cues = ad.track_cues(track.id) + if cues is not None and cues.grid_markers: + ad.replace_grid(track.id, [(m.start + 0.01, m.bpm) for m in cues.grid_markers]) + check("(setup) edits make it dirty", ad.dirty) + ad.reload() + check("after discard it is clean", ad.dirty is False) + check("the metadata edit is gone", ad.track(track.id).title == title, ad.track(track.id).title) + check("no buffered grid write survives for the next save", not ad._store._pending_grids) + ad.save() + ad.close() + check("a save after discard writes nothing the user threw away", + RekordboxAdapter(work).track(track.id).title == title) + del before + +print("== read-only ==") +os.environ["KONDUKTOR_NML"] = "" +with TestClient(main.app) as c: + r = c.post("/api/library/open", json={"path": str(FIXTURE)}) + if r.status_code == 200: + check("a read-only library has nothing to discard (409)", c.post("/api/discard").status_code == 409) + else: + print(f" (skipped: fixture did not open: {r.status_code})") + +print("\nRESULT:", "FAILED" if failed else "ALL PASSED") +sys.exit(1 if failed else 0) diff --git a/backend/test_stem_swap.py b/backend/test_stem_swap.py index e2c514f..717f668 100644 --- a/backend/test_stem_swap.py +++ b/backend/test_stem_swap.py @@ -125,6 +125,7 @@ with tempfile.TemporaryDirectory() as d: ad = TraktorAdapter(work) before_cues = ad.track_cues(tid) before = ad.snapshot() + audio_id = ad.store.model_entry(tid).audio_id written = build_stem(mp3) parked = park(mp3) stem = written.path @@ -140,6 +141,8 @@ with tempfile.TemporaryDirectory() as d: == (written.bit_rate, round(written.duration), round(written.size / 1024)), f"{entry.info.bitrate} {entry.info.playtime} {entry.info.filesize}") check("the projection calls it a stem track", ad.track(new).media_kind == "stem") + check("Traktor's fingerprint is KEPT (cleared, Traktor re-measures the grid's BPM on load)", + entry.audio_id == audio_id and bool(audio_id)) after_cues = ad.track_cues(new) check("every cue reads back at the same DECODED second", [(c.slot, round(c.start, 9)) for c in after_cues.cues] == [(c.slot, round(c.start, 9)) for c in before_cues.cues], diff --git a/frontend/src-tauri/src/lib.rs b/frontend/src-tauri/src/lib.rs index 7fecc44..81d29a6 100644 --- a/frontend/src-tauri/src/lib.rs +++ b/frontend/src-tauri/src/lib.rs @@ -5,21 +5,94 @@ // 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. +// +// 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}; use std::sync::Mutex; use std::time::Duration; -use tauri::{Manager, WebviewUrl, WebviewWindowBuilder}; +use tauri::{AppHandle, Emitter, Manager, RunEvent, WebviewUrl, WebviewWindowBuilder, WindowEvent}; use tauri_plugin_shell::process::{CommandChild, CommandEvent}; use tauri_plugin_shell::ShellExt; /// Holds the running sidecar child so we can terminate it on exit. struct Sidecar(Mutex>); +/// Quit handshake state: `allowed` once the frontend (or the timeout) has said +/// quit; `acked` once the frontend has seen the current request. +struct Quit { + allowed: AtomicBool, + acked: AtomicBool, +} + +fn kill_sidecar(app: &AppHandle) { + if let Some(child) = app.state::().0.lock().unwrap().take() { + let _ = child.kill(); + } +} + +fn exit_now(app: &AppHandle) { + app.state::().allowed.store(true, Ordering::SeqCst); + kill_sidecar(app); + app.exit(0); +} + +/// Hand the quit decision to the frontend, with a deadline for it to answer. +fn request_quit(app: &AppHandle) { + app.state::().acked.store(false, Ordering::SeqCst); + if app.emit("konduktor://quit-requested", ()).is_err() { + exit_now(app); + return; + } + let handle = app.clone(); + tauri::async_runtime::spawn(async move { + tokio::time::sleep(Duration::from_secs(2)).await; + if !handle.state::().acked.load(Ordering::SeqCst) { + exit_now(&handle); + } + }); +} + +/// The frontend has seen the quit request (it may now take as long as it likes). +#[tauri::command] +fn quit_ack(app: AppHandle) { + app.state::().acked.store(true, Ordering::SeqCst); +} + +/// The user chose Cancel: forget the request. +#[tauri::command] +fn quit_cancel(app: AppHandle) { + app.state::().acked.store(false, Ordering::SeqCst); +} + +/// Quit for real (nothing unsaved, or Save / Discard has finished). +#[tauri::command] +fn quit_now(app: AppHandle) { + exit_now(&app); +} + #[cfg_attr(mobile, tauri::mobile_entry_point)] pub fn run() { tauri::Builder::default() .plugin(tauri_plugin_shell::init()) .manage(Sidecar(Mutex::new(None))) + .manage(Quit { allowed: AtomicBool::new(false), acked: AtomicBool::new(false) }) + .invoke_handler(tauri::generate_handler![quit_ack, quit_cancel, quit_now]) + .on_window_event(|window, event| { + if let WindowEvent::CloseRequested { api, .. } = event { + let app = window.app_handle(); + if !app.state::().allowed.load(Ordering::SeqCst) { + api.prevent_close(); + request_quit(app); + } + } + }) .setup(|app| { if cfg!(debug_assertions) { app.handle().plugin( @@ -99,12 +172,17 @@ pub fn run() { }) .build(tauri::generate_context!()) .expect("error while building the Tauri application") - .run(|app_handle, event| { - // Terminate the sidecar when the app is quitting. - if let tauri::RunEvent::ExitRequested { .. } = event { - if let Some(child) = app_handle.state::().0.lock().unwrap().take() { - let _ = child.kill(); + .run(|app_handle, event| match event { + // Cmd/Ctrl+Q, the app menu's Quit, the last window closing: ask + // first, unless the answer is already in. + RunEvent::ExitRequested { api, .. } => { + if !app_handle.state::().allowed.load(Ordering::SeqCst) { + api.prevent_exit(); + request_quit(app_handle); } } + // Really exiting: only now may the backend go. + RunEvent::Exit => kill_sidecar(app_handle), + _ => {} }); } diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index d06c35d..224c9c2 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -5,6 +5,7 @@ import { CapabilitiesContext, slotLabeller } from './lib/capabilities' import { writeHint } from './lib/platformCopy' import { invalidateTrackLists } from './lib/trackQueries' import { api, type CueBatchResult, type GridBatchResult, type AutoCueSlot, type PlaylistNode, type Track, type TrackOrigin } from './api' +import { confirmDiscardUnsaved } from './lib/unsaved' import { COLUMN_MENU, DEFAULT_COLUMN_ORDER, @@ -1034,6 +1035,7 @@ export default function App() { onSwitchLibrary={() => setForcePicker(true)} onDone={(msg) => notify('success', msg)} onOpenPathMapping={() => setShowPaths(true)} + onDiscarded={() => afterBulk(prepTrack ? [prepTrack.id] : [], true)} /> @@ -1353,7 +1355,11 @@ export default function App() { } loading={loading} collectionName={capabilities.data ? libraryName : null} - onChangeCollection={() => setForcePicker(true)} + onChangeCollection={() => { + // The same question the sidebar header asks: this button used to + // switch library without it, silently dropping unsaved edits. + void confirmDiscardUnsaved().then((ok) => ok && setForcePicker(true)) + }} /> diff --git a/frontend/src/api.ts b/frontend/src/api.ts index 524a7fe..8805fe3 100644 --- a/frontend/src/api.ts +++ b/frontend/src/api.ts @@ -758,6 +758,8 @@ export const api = { patchPrefs: (patch: Record) => send>('PATCH', '/api/prefs', patch), save: () => send('POST', '/api/save'), + /** Drop every unsaved edit; the library re-reads itself from disk. */ + discard: () => send('POST', '/api/discard'), // ---- version history ---- history: () => getJSON('/api/history'), diff --git a/frontend/src/components/QuitGuard.tsx b/frontend/src/components/QuitGuard.tsx new file mode 100644 index 0000000..6ccd5d9 --- /dev/null +++ b/frontend/src/components/QuitGuard.tsx @@ -0,0 +1,150 @@ +import { createPortal } from 'react-dom' +import { useEffect, useRef, useState } from 'react' +import { useQuery } from '@tanstack/react-query' +import { api } from '../api' + +/** + * Ask before quitting with unsaved changes: Save · Discard · Cancel. + * + * The desktop shell (src-tauri/src/lib.rs) no longer quits on its own. Closing + * the window or Cmd/Ctrl+Q is PREVENTED there and becomes a + * `konduktor://quit-requested` event; this answers it. It acknowledges at once + * (`quit_ack`) — the shell quits anyway after ~2 s without one, so a webview + * that has hung can never trap the user — then either quits (`quit_now`) or + * asks. Discard goes through the backend rather than just letting the process + * die, because unsaved state may include files to put back (a stem + * conversion's parked originals). + * + * In a plain browser (dev) there is no shell to prevent anything, so the most + * that can be done is the browser's own `beforeunload` warning. + * + * Mounted once in main.tsx, beside App, so it works on the picker screen too. + */ +export function QuitGuard() { + const [asking, setAsking] = useState(false) + const [busy, setBusy] = useState(null) + const [error, setError] = useState(null) + const askingRef = useRef(false) + const state = useQuery({ queryKey: ['state'], queryFn: api.state, retry: false }) + const dirty = state.data?.dirty ?? false + + // Tauri: answer the shell's quit request. + useEffect(() => { + if (!('__TAURI_INTERNALS__' in window)) 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') + if (askingRef.current) return // already asking: a second Cmd+Q changes nothing + const unsaved = await api + .state() + .then((s) => s.dirty) + .catch(() => false) // no library loaded: nothing to lose + if (!unsaved) { + await invoke('quit_now') + return + } + askingRef.current = true + setError(null) + setAsking(true) + }) + if (cancelled) off() + else unlisten = off + })() + return () => { + cancelled = true + unlisten?.() + } + }, []) + + // Browser dev: the browser's own warning is all there is. + useEffect(() => { + if ('__TAURI_INTERNALS__' in window || !dirty) return + const warn = (e: BeforeUnloadEvent) => { + e.preventDefault() + } + window.addEventListener('beforeunload', warn) + return () => window.removeEventListener('beforeunload', warn) + }, [dirty]) + + const quit = async () => { + const { invoke } = await import('@tauri-apps/api/core') + await invoke('quit_now') + } + const cancel = async () => { + askingRef.current = false + setAsking(false) + const { invoke } = await import('@tauri-apps/api/core') + await invoke('quit_cancel') + } + const act = async (kind: 'save' | 'discard') => { + setBusy(kind) + setError(null) + try { + if (kind === 'save') await api.save() + else await api.discard() + await quit() + } catch (e) { + // Stay open: a failed save must never turn into a silent loss. + setError(e instanceof Error ? e.message : String(e)) + setBusy(null) + } + } + + useEffect(() => { + if (!asking) return + const onKey = (e: KeyboardEvent) => { + if (e.key === 'Escape' && !busy) void cancel() + } + window.addEventListener('keydown', onKey) + return () => window.removeEventListener('keydown', onKey) + }) + + if (!asking) return null + return createPortal( +
+
+
+ Save changes before quitting? +
+
+

You have unsaved changes. If you quit without saving, they are lost.

+ {error &&

{error}

} +
+
+ + + +
+
+
, + document.body, + ) +} diff --git a/frontend/src/components/SaveBar.tsx b/frontend/src/components/SaveBar.tsx index 50ed99a..cdd79cf 100644 --- a/frontend/src/components/SaveBar.tsx +++ b/frontend/src/components/SaveBar.tsx @@ -4,16 +4,19 @@ import { api } from '../api' import { useCaps } from '../lib/capabilities' import { overwriteWarning, readOnlyNotice, saveLabel } from '../lib/platformCopy' import { Icon } from '../lib/icons' +import { askConfirm } from '../lib/confirm' interface Props { onError: (msg: string) => void /** Rendered to the right of the save button (the settings gear). */ trailing?: ReactNode + /** After a discard, so the owner can refresh what it holds outside queries. */ + onDiscarded?: () => void } // Bottom-of-sidebar save control. Shows unsaved-changes state and writes to the // NML; every save is recorded in the collection's version history. -export function SaveBar({ onError, trailing }: Props) { +export function SaveBar({ onError, trailing, onDiscarded }: Props) { const qc = useQueryClient() const [justSaved, setJustSaved] = useState(null) const { data: state } = useQuery({ queryKey: ['state'], queryFn: api.state }) @@ -31,6 +34,25 @@ export function SaveBar({ onError, trailing }: Props) { onError: (e: Error) => onError(e.message), }) + // The way back that did not exist: every edit since the last save goes, and + // the library re-reads itself from disk. Everything cached is refetched. + const discard = useMutation({ + mutationFn: api.discard, + onSuccess: () => { + qc.invalidateQueries() + onDiscarded?.() + }, + onError: (e: Error) => onError(e.message), + }) + const confirmDiscard = async () => { + const ok = await askConfirm({ + title: 'Discard unsaved changes?', + body: 'Every change since the last save is thrown away and the library is re-read from disk. This cannot be undone.', + confirmLabel: 'Discard changes', + }) + if (ok) discard.mutate() + } + const caps = useCaps() const warning = overwriteWarning(caps.save) const dirty = state?.dirty ?? false @@ -79,6 +101,17 @@ export function SaveBar({ onError, trailing }: Props) { {trailing} + {dirty && !save.isPending && ( +
+ +
+ )} {justSaved && (
{justSaved}
)} diff --git a/frontend/src/components/Sidebar.tsx b/frontend/src/components/Sidebar.tsx index 1272cad..ab1ed3d 100644 --- a/frontend/src/components/Sidebar.tsx +++ b/frontend/src/components/Sidebar.tsx @@ -3,11 +3,11 @@ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' import { api, type PlaylistKind, type PlaylistNode } from '../api' import { useCaps } from '../lib/capabilities' import { SaveBar } from './SaveBar' +import { confirmDiscardUnsaved } from '../lib/unsaved' import { SettingsMenu } from './SettingsMenu' import { DevicesSection } from './DevicesSection' import { ExportsSection } from './ExportsSection' import { ConfirmDialog, type ConfirmRequest } from './ConfirmDialog' -import { askConfirm } from '../lib/confirm' import { ContextMenu, type MenuItem } from './ContextMenu' import { Icon, type IconName } from '../lib/icons' import { PlatformIcon } from '../lib/platformIcons' @@ -49,6 +49,8 @@ interface Props { onSwitchLibrary: () => void onDone: (msg: string) => void onOpenPathMapping: () => void + /** After unsaved edits were discarded (SaveBar). */ + onDiscarded?: () => void } // Kind picks the icon; every behavioural question is answered by the node's own @@ -319,27 +321,18 @@ export function Sidebar({ onSwitchLibrary, onDone, onOpenPathMapping, + onDiscarded, }: Props) { const qc = useQueryClient() - // Both share a cache entry with App and SaveBar, so the header never - // disagrees with what is loaded or with whether it has been saved. + // Shares a cache entry with App, so the header never disagrees with what is + // loaded. const library = useQuery({ queryKey: ['collection'], queryFn: api.collection }).data?.library - const dirty = useQuery({ queryKey: ['state'], queryFn: api.state }).data?.dirty ?? false // Switching library throws away every unsaved edit — the adapter holds them in // its native model, and opening another library replaces it. Worth a confirm: // until now there was no way to switch at all, so this hazard is new. const switchLibrary = async () => { - if ( - dirty && - !(await askConfirm({ - title: 'Discard unsaved changes?', - body: 'You have unsaved changes. Opening a different library will discard them.', - confirmLabel: 'Discard and switch', - })) - ) - return - onSwitchLibrary() + if (await confirmDiscardUnsaved()) onSwitchLibrary() } // There is no per-node flag for "you may create a NEW playlist" — the node // flags describe existing nodes — so this is the library-level gate. @@ -609,7 +602,11 @@ export function Sidebar({ Collection Version History - } /> + } + /> ) } diff --git a/frontend/src/lib/unsaved.ts b/frontend/src/lib/unsaved.ts new file mode 100644 index 0000000..fe581b5 --- /dev/null +++ b/frontend/src/lib/unsaved.ts @@ -0,0 +1,24 @@ +import { api } from '../api' +import { askConfirm } from './confirm' + +/** + * Ask before an action that throws away unsaved edits — opening a different + * library replaces the adapter that holds them. Resolves true when there is + * nothing to lose or the user agreed. + * + * Reads the state fresh rather than from a cached query: the two places that + * switch library (the sidebar header and the status bar) must not disagree, and + * the status bar's button used to skip the question entirely. + */ +export async function confirmDiscardUnsaved(): Promise { + const dirty = await api + .state() + .then((s) => s.dirty) + .catch(() => false) // no library loaded: nothing to lose + if (!dirty) return true + return askConfirm({ + title: 'Discard unsaved changes?', + body: 'You have unsaved changes. Opening a different library will discard them.', + confirmLabel: 'Discard and switch', + }) +} diff --git a/frontend/src/main.tsx b/frontend/src/main.tsx index f712cb4..80074f8 100644 --- a/frontend/src/main.tsx +++ b/frontend/src/main.tsx @@ -8,6 +8,7 @@ import App from './App.tsx' import { UpdateCheck } from './components/UpdateDialog.tsx' import { AmbientBackdrop } from './components/AmbientBackdrop.tsx' import { ConfirmHost } from './lib/confirm.tsx' +import { QuitGuard } from './components/QuitGuard.tsx' import { preventHistoryNavigation } from './lib/noNavigation.ts' preventHistoryNavigation() @@ -31,6 +32,8 @@ createRoot(document.getElementById('root')!).render( {/* askConfirm()'s dialogs — the app's replacement for window.confirm. */} + {/* Save · Discard · Cancel when quitting with unsaved changes. */} + , )