diff --git a/CLAUDE.md b/CLAUDE.md index 99ddecb..f8fddfb 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -358,11 +358,18 @@ Two independent apps that talk over HTTP: `AutoCueDialog` (the Auto Hotcues slot template: event + beat offset per slot, a per-slot Replace tick for occupied slots — never remembered, since overwriting is a decision about THIS track — and the template itself - persisted as `autoCueTemplate` in userprefs), + persisted as `autoCueTemplate` in userprefs. Also has a **batch mode** for + the context menu: same template, but it starts a job via `onRun`, and each + tick reads "Replace" and applies to every track in the batch. A Replace + RENAMES the slot's cue — `set_hotcue` keeps the old name only when called + without one, which is what a hand move does), `ContextMenu` (supports `▸` submenus, section headings, separators and checkbox items that toggle without closing — the header row's right-click column chooser uses those; "Add to" lists - playlists + exports and acts on the whole selection) + `EditTagsDialog` + playlists + exports and acts on the whole selection; "Remove ▸" holds + From this playlist / From this export / Grids / Hotcues / From collection, + each behind a `ConfirmDialog` — as is the playlist Delete key. Enter + confirms unless a button has focus, so Tab-to-Cancel + Enter cancels) + `EditTagsDialog` (right-click → multi-field metadata + album-art edit), `StatusBar`, `RatingStars` (read-only, or click-to-set when given `onChange`), `Toast`, `UpdateDialog` (`UpdateCheck`, mounted in `main.tsx` beside `App` so it shows @@ -447,7 +454,10 @@ serialization path.** It enforces: **flexible (multi-marker) grids** add/move/delete reversibly, `delete_grid` leaves no companion debris (I); **companion cues are ordinary editable hotcues** — move/retype/delete work and never touch the grid marker (J); and - real flexible grids in the collection project correctly (K). + real flexible grids in the collection project correctly (K); and + **removing a track from the collection** drops its `` and its + PRIMARYKEYs from exactly the playlists that held it — the only ADDED lines are + the `ENTRIES=` recounts, every other playlist byte-identical (L). The guard that catches serialization regressions like the lxml reformatting bug. - `test_phase3.py` — full create/add/reorder/rename/delete/save cycle stays Traktor-valid, backup-first, COLLECTION byte-identical, original untouched. @@ -492,13 +502,30 @@ serialization path.** It enforces: (across a tempo change), and the ROUTE end to end on a temp copy of the real collection — the previous implementation's route returned 500 on every call for a week while its helper's tests passed. -- `test_grid_batch.py` — **batch grid analysis** (context menu → Analyze Grid & - BPM → `POST /api/tracks/grid/auto-batch`, a `jobs.py` job shown in the status - bar). Pins the batch-only decisions: locked grids are skipped always, existing - grids unless `replace_existing`, a failing track is reported not fatal, one - run at a time, a cancel KEEPS finished tracks (unsaved edits like any other) - and still returns its result, and opening another library cancels the run. - Shares `_analyse_grid` with the deck's single-track Analyze. +- `test_grid_batch.py` — **batch analysis** from the context menu, both + `jobs.py` jobs shown in the status bar: Analyze Grid & BPM + (`POST /api/tracks/grid/auto-batch`) and Auto Hotcues… + (`POST /api/tracks/cue/auto-batch`, one template for every track). Pins the + batch-only decisions: locked grids are skipped always, existing grids unless + `replace_existing`; a hotcue batch analyses a grid FIRST where there is none + and never touches an existing one, and a ticked Replace applies to every + track; a failing track is reported not fatal; **one batch at a time ACROSS + both kinds** (a grid run would move the beats a hotcue run is placing cues + on); a cancel KEEPS finished tracks (unsaved edits like any other) and still + returns its result; opening another library cancels the run. Each shares its + helper (`_analyse_grid`, `_place_auto_cues`) with the deck's single-track + button. +- `test_bulk_remove.py` — the context menu's **Remove ▸** routes + (`/api/tracks/grid/clear`, `/api/tracks/cue/clear`, `/api/tracks/remove`): + locked grids are kept, clearing hotcues empties the whole bank (loops and the + grid's beat-1 cue too) but never the grid, a removed track leaves the + projection AND its playlists while its audio file is untouched, removal is + gated on `tracks.removable`, and all three are refused while a batch + analysis runs. `remove_tracks` is the protocol's only DESTROYING verb for + tracks; Traktor implements it, Rekordbox and OneLibrary refuse (a Rekordbox + track spans rows in several tables plus ANLZ files, and which Rekordbox + expects deleted together is unmeasured). The journal records it as + `track/remove`, NOT an edit — otherwise history would read "edited 40 tracks". - `test_picker.py` — the picker's routes. Pins the scoping, because the bug it replaced was invisible: `/api/library/options` flattened every driver's detections and returned `[0]`, so a plugged-in USB stick could be offered as diff --git a/backend/konduktor/adapters/onelibrary/adapter.py b/backend/konduktor/adapters/onelibrary/adapter.py index 3b14149..511c3e8 100644 --- a/backend/konduktor/adapters/onelibrary/adapter.py +++ b/backend/konduktor/adapters/onelibrary/adapter.py @@ -239,6 +239,9 @@ class OneLibraryAdapter: def add_tracks(self, items: list) -> list[str]: self._refuse("Adding tracks") + def remove_tracks(self, track_ids: list[str]) -> int: + self._refuse("Removing tracks") + def set_track_metadata(self, track_id: str, fields: dict) -> Track | None: self._refuse("Editing track metadata") diff --git a/backend/konduktor/adapters/rekordbox/adapter.py b/backend/konduktor/adapters/rekordbox/adapter.py index 5d5c85b..c02e220 100644 --- a/backend/konduktor/adapters/rekordbox/adapter.py +++ b/backend/konduktor/adapters/rekordbox/adapter.py @@ -400,6 +400,12 @@ class RekordboxAdapter: # import target for now. self._refuse("Adding tracks") + def remove_tracks(self, track_ids: list[str]) -> int: + # Same shape as adding: a track is a djmdContent row plus its cues, + # playlist rows, contentCue/contentFile mirrors and ANLZ files, and + # which of those Rekordbox expects to be deleted together is unmeasured. + self._refuse("Removing tracks") + def set_cover_art(self, track_id: str, data: bytes, mime: str) -> None: self._refuse("Editing cover art") diff --git a/backend/konduktor/adapters/traktor/adapter.py b/backend/konduktor/adapters/traktor/adapter.py index 578c213..8d3b5f6 100644 --- a/backend/konduktor/adapters/traktor/adapter.py +++ b/backend/konduktor/adapters/traktor/adapter.py @@ -150,6 +150,16 @@ class TraktorAdapter: def cover_art(self, track_id: str) -> tuple[bytes, str] | None: return self._store.cover_art(track_id) + # ---- removing tracks --------------------------------------------------- + def remove_tracks(self, track_ids: list[str]) -> int: + with _translate(): + n = self._store.remove_entries(track_ids) + if n: + # Rebuilt rather than patched: an entry sharing a removed key went + # too, and the index would otherwise still hold its projection. + self._rebuild() + return n + # ---- adding tracks ---------------------------------------------------- def add_tracks(self, items: list) -> list[str]: """Add tracks that came from somewhere else, with their prep. diff --git a/backend/konduktor/adapters/traktor/capabilities.py b/backend/konduktor/adapters/traktor/capabilities.py index 080b190..3b540ae 100644 --- a/backend/konduktor/adapters/traktor/capabilities.py +++ b/backend/konduktor/adapters/traktor/capabilities.py @@ -59,6 +59,7 @@ def capabilities_for(path: Path, editable_fields: list[str]) -> Capabilities: rating_max=5, editable_fields=sorted(editable_fields), media_kinds=["audio", "stem"], + removable=True, artwork=True, artwork_note=( "Traktor caches its own cover thumbnail, so a replaced image may " diff --git a/backend/konduktor/adapters/traktor/store.py b/backend/konduktor/adapters/traktor/store.py index ffb1fd4..2e4c765 100644 --- a/backend/konduktor/adapters/traktor/store.py +++ b/backend/konduktor/adapters/traktor/store.py @@ -418,6 +418,56 @@ class TraktorStore: self.dirty = True return key + def remove_entries(self, track_ids: list[str]) -> int: + """Remove tracks from the collection AND from every playlist; return + how many ENTRYs went. + + The mirror of `add_entry`, with the same care about bytes: only the + removed ENTRYs, the `` count and the playlists that + actually referenced a removed track change — any other playlist is left + alone rather than rebuilt, so it still renders what it was parsed from. + + Playlists must be purged too: a PRIMARYKEY naming a track that is no + longer in COLLECTION is a dangling reference, not an empty slot. The + audio file is never touched — this is the library's record of the track, + like Traktor's own "Delete from Collection". + + Matches by primary key in DOCUMENT order, so two ENTRYs sharing a key + (which `iter_entries` warns can happen) both go, where the key→entry + dict would have found only one. + """ + gone = set(track_ids) + with self._lock: + before = self._nml.collection.entry + kept = [e for e in before if self._key_of(e) not in gone] + removed = len(before) - len(kept) + if removed == 0: + return 0 + self._nml.collection.entry = kept + self._nml.collection.entries = len(kept) + for key in gone: + if self._entry_by_key.pop(key, None) is not None: + self._track_art.pop(key, None) + self._note("track", "remove", key) + for n in self._iter_nodes(self._root()): + pl = n.playlist + if pl is None or not pl.entry: + continue + entries = [ + e for e in pl.entry + if not (e.primarykey is not None and e.primarykey.key in gone) + ] + if len(entries) != len(pl.entry): + pl.entry = entries + pl.entries = len(entries) + self.dirty = True + return removed + + @staticmethod + def _key_of(entry) -> str | None: + loc = entry.location + return f"{loc.volume or ''}{loc.dir or ''}{loc.file or ''}" if loc else None + def iter_entries(self): """Every collection ENTRY in document order. @@ -480,7 +530,10 @@ class TraktorStore: """Create (or reposition + retype) the hotcue in `slot` at `start_sec`. `length_sec` > 0 makes it a loop (used with cue_type 5). `name` sets the - cue label on create; when unset it falls back to Traktor's "n.n.".""" + label: on create it falls back to Traktor's "n.n."; on a replace, None + keeps the old label (a hand move is still the same cue) while a name + renames it (Auto Hotcues' Replace puts a DIFFERENT cue in the slot, and + keeping "Drop 1" on a cue now at "Drop 1 -16" would mislabel it).""" if not 0 <= slot <= 7: raise PlaylistError(f"Invalid hotcue slot: {slot}") if cue_type not in self.CREATABLE_TYPES: @@ -496,6 +549,8 @@ class TraktorStore: existing.start = start_ms existing.type = cue_type existing.len = len_ms + if name is not None: + existing.name = name else: if entry.cue_v2 is None: entry.cue_v2 = [] diff --git a/backend/konduktor/core/adapter.py b/backend/konduktor/core/adapter.py index 4bdfe55..999924e 100644 --- a/backend/konduktor/core/adapter.py +++ b/backend/konduktor/core/adapter.py @@ -135,6 +135,12 @@ class LibraryAdapter(Protocol): # what `test_save_fidelity.py` checks rather than taking on trust. def add_tracks(self, items: list["NewTrack"]) -> list[str]: ... + # Remove tracks from the library — and so from every playlist, since an + # entry naming a track the library no longer has is a dangling reference. + # Never touches audio files. Returns how many were removed; gated on + # `capabilities().tracks.removable`. + def remove_tracks(self, track_ids: list[str]) -> int: ... + # ---- commands: track metadata / art --------------------------------- def set_track_metadata(self, track_id: str, fields: dict) -> Track | None: ... def set_cover_art(self, track_id: str, data: bytes, mime: str) -> None: ... diff --git a/backend/konduktor/core/capabilities.py b/backend/konduktor/core/capabilities.py index c6858ca..7a58c98 100644 --- a/backend/konduktor/core/capabilities.py +++ b/backend/konduktor/core/capabilities.py @@ -58,6 +58,9 @@ class TrackCapabilities(BaseModel): rating_max: int = 5 editable_fields: list[str] = [] media_kinds: list[MediaKind] = ["audio"] + # Tracks can be removed from the library (and so from its playlists). The + # audio file is never touched either way. + removable: bool = False artwork: bool = False artwork_note: str | None = None diff --git a/backend/konduktor/core/edit_journal.py b/backend/konduktor/core/edit_journal.py index b5f98e8..eedc00a 100644 --- a/backend/konduktor/core/edit_journal.py +++ b/backend/konduktor/core/edit_journal.py @@ -68,12 +68,21 @@ class EditJournal: changed, they simply did not exist before. Counting them here would both mislabel the version-history message and drag them through the file-tag sync, which has nothing to write for a track whose fields were never - touched. + touched. Excludes tracks REMOVED from the library for the same reason: + "edited 40 tracks" would describe a deletion as an edit. """ + removed = self.removed_tracks() return { c.target for c in self.changes - if c.scope == "track" and c.target and c.op != "add" + if c.scope == "track" and c.target and c.op not in ("add", "remove") + and c.target not in removed + } + + def removed_tracks(self) -> set[str]: + """Tracks taken out of the library this session.""" + return { + c.target for c in self.changes if c.scope == "track" and c.op == "remove" and c.target } def added_tracks(self) -> set[str]: @@ -115,6 +124,9 @@ class EditJournal: n_added = len(self.added_tracks()) if n_added: parts.append(f"added {tracks(n_added)}") + n_removed = len(self.removed_tracks()) + if n_removed: + parts.append(f"removed {tracks(n_removed)} from the collection") # --- track metadata + cover art (already counted per-track) --- n_meta = len(self.edited_tracks() | (extra_tracks or set())) diff --git a/backend/konduktor/main.py b/backend/konduktor/main.py index dc4386b..3276043 100644 --- a/backend/konduktor/main.py +++ b/backend/konduktor/main.py @@ -36,6 +36,8 @@ from .schemas import ( AutoGridRequest, AutoCueOutcome, AutoHotcue, + AutoHotcuesBatchRequest, + TrackIds, AutoHotcuesRequest, AutoHotcuesResult, CollectionCandidate, @@ -149,8 +151,9 @@ def open_collection(body: OpenCollection) -> CollectionStatus: if not path.exists(): raise HTTPException(400, f"Not found: {path}") # A running analysis writes into the library being replaced; stop it. - for job in JOBS.active(GRID_JOB): - JOBS.cancel(job.id) + for kind in BATCH_JOBS: + for job in JOBS.active(kind): + JOBS.cancel(job.id) try: STATE.open(path) except AdapterError as ex: @@ -838,22 +841,35 @@ def auto_hotcues(body: AutoHotcuesRequest) -> AutoHotcuesResult: raise HTTPException(404, "Track not found") if not cues.grid_markers: raise HTTPException(400, "Set a beatgrid before using Auto Hotcues") - slots = a.capabilities().cues.hotcue_slots + _check_cue_slots(a, body.slots) + try: + return _place_auto_cues(a, body.track_id, cues, body.slots) + except _AnalysisError as ex: + raise HTTPException(400, str(ex)) + + +def _check_cue_slots(a, slots: list) -> None: + """Refuse a template the bank cannot hold — once, before any track is touched.""" + n = a.capabilities().cues.hotcue_slots seen: set[int] = set() - for r in body.slots: - if not 0 <= r.slot < slots: - raise HTTPException(400, f"Slot {r.slot} is outside this library's {slots} hotcues") + for r in slots: + if not 0 <= r.slot < n: + raise HTTPException(400, f"Slot {r.slot} is outside this library's {n} hotcues") if r.slot in seen: raise HTTPException(400, f"Slot {r.slot} is requested twice") seen.add(r.slot) - path = a.audio_path(body.track_id) - if path is None or not path.exists(): - raise HTTPException(400, "Audio file not found (is the drive mounted?)") + +def _place_auto_cues(a, track_id: str, cues: TrackCues, slots: list) -> AutoHotcuesResult: + """Analyse one gridded track's structure and place the template — shared by + the deck's Auto button and the batch job, so the two cannot drift.""" + path = a.audio_path(track_id) + if path is None or not path.exists(): + raise _AnalysisError("Audio file not found (is the drive mounted?)") try: found = structure.analyse(str(path), [(m.start, m.bpm) for m in cues.grid_markers]) except Exception as ex: # analysis is best-effort; never 500 the UI - raise HTTPException(400, f"Analysis failed: {ex}") + raise _AnalysisError(f"Analysis failed: {ex}") from ex existing = { c.slot: ah.ExistingCue(c.editable, c.start) @@ -862,7 +878,7 @@ def auto_hotcues(body: AutoHotcuesRequest) -> AutoHotcuesResult: } outcomes = ah.plan( found, - [ah.SlotRequest(r.slot, r.event, r.offset_beats, r.overwrite) for r in body.slots], + [ah.SlotRequest(r.slot, r.event, r.offset_beats, r.overwrite) for r in slots], existing, ) placed = [o for o in outcomes if o.status == ah.PLACED] @@ -870,7 +886,7 @@ def auto_hotcues(body: AutoHotcuesRequest) -> AutoHotcuesResult: # overwrite=True is safe: `plan` only passes an occupied slot when the # user ticked it, and the adapter still refuses a protected one. cues = a.place_cues( - body.track_id, + track_id, [AutoHotcue(slot=o.slot, start=o.start, name=o.name) for o in placed], overwrite=True, ) @@ -892,31 +908,42 @@ def auto_grid(body: AutoGridRequest) -> TrackCues: raise HTTPException(404, "Track not found") try: return _analyse_grid(a, body.track_id) - except _GridAnalysisError as ex: + except _AnalysisError as ex: raise HTTPException(400, str(ex)) -class _GridAnalysisError(Exception): +class _AnalysisError(Exception): """A track that could not be analysed; the message is user-facing.""" +# Batch analysis jobs. ONE at a time across both kinds: a grid run replacing a +# track's grid while a hotcue run places cues on the old one would put cues on +# beats that no longer exist. +GRID_JOB = "grid-analysis" +CUE_JOB = "auto-hotcues" +BATCH_JOBS = (GRID_JOB, CUE_JOB) + + +def _require_no_batch() -> None: + if any(JOBS.active(k) for k in BATCH_JOBS): + raise HTTPException(409, "A batch analysis is already running") + + def _analyse_grid(a, track_id: str) -> TrackCues: """Detect and write one track's grid — shared by the deck's Analyze and the batch job, so the two cannot come to mean different things.""" path = a.audio_path(track_id) if path is None or not path.exists(): - raise _GridAnalysisError("Audio file not found (is the drive mounted?)") + raise _AnalysisError("Audio file not found (is the drive mounted?)") try: found = grid_detect.detect_grid(str(path)) except Exception as ex: # analysis is best-effort; never 500 the UI - raise _GridAnalysisError(f"Analysis failed: {ex}") from ex + raise _AnalysisError(f"Analysis failed: {ex}") from ex # "Analysed", not "replace": each platform writes an analysis result in its # own shape (Traktor pairs the first marker with a beat-1 cue). return a.set_analysed_grid(track_id, [(found.anchor, found.bpm)]) -GRID_JOB = "grid-analysis" - @app.post("/api/tracks/grid/auto-batch", response_model=JobStatus) def auto_grid_batch(body: AutoGridBatchRequest) -> JobStatus: @@ -930,10 +957,7 @@ def auto_grid_batch(body: AutoGridBatchRequest) -> JobStatus: a = require_adapter() if not a.capabilities().grid.editable: raise HTTPException(422, "This library's beatgrids cannot be edited") - # One at a time: two runs over overlapping selections would analyse the - # same track twice and race on its grid. - if JOBS.active(GRID_JOB): - raise HTTPException(409, "Grid analysis is already running") + _require_no_batch() ids = list(dict.fromkeys(body.track_ids)) def run(handle) -> dict: @@ -955,7 +979,7 @@ def auto_grid_batch(body: AutoGridBatchRequest) -> JobStatus: try: _analyse_grid(a, track_id) result["analysed"].append(track_id) - except (_GridAnalysisError, AdapterError) as ex: + except (_AnalysisError, AdapterError) as ex: result["failed"].append({"title": title, "reason": str(ex)}) handle.progress(done=i + 1) return result @@ -964,6 +988,57 @@ def auto_grid_batch(body: AutoGridBatchRequest) -> JobStatus: return JobStatus(**job.as_dict()) +@app.post("/api/tracks/cue/auto-batch", response_model=JobStatus) +def auto_hotcues_batch(body: AutoHotcuesBatchRequest) -> JobStatus: + """Place one Auto Hotcues template on many tracks, as a JOB. + + A track with no beatgrid gets one analysed first (as "Analyze Grid & BPM" + would), since the events are found on the grid; a track that has one keeps + it untouched. Same contract as the grid batch: written as each track + finishes, a cancel keeps what is done, a failing track is reported and + skipped.""" + a = require_adapter() + caps = a.capabilities() + if not caps.writable or caps.cues.hotcue_slots == 0: + raise HTTPException(422, "This library's hotcues cannot be edited") + _check_cue_slots(a, body.slots) + if not body.slots: + raise HTTPException(400, "The template places no cues") + _require_no_batch() + ids = list(dict.fromkeys(body.track_ids)) + + def run(handle) -> dict: + result = {"tracks": [], "cues_placed": 0, "grids_created": 0, "failed": []} + handle.progress(done=0, total=len(ids)) + for i, track_id in enumerate(ids): + if handle.cancelled: + break # keep what is done; return it rather than raise + track = a.track(track_id) + title = (track.title or track_id) if track else track_id + handle.progress(message=title) + try: + cues = a.track_cues(track_id) if track else None + if cues is None: + raise _AnalysisError("Track not found") + if not cues.grid_markers: + if track.grid_locked: + raise _AnalysisError("No beatgrid, and the grid is locked") + if not caps.grid.editable: + raise _AnalysisError("No beatgrid") + cues = _analyse_grid(a, track_id) + result["grids_created"] += 1 + placed = _place_auto_cues(a, track_id, cues, body.slots) + result["tracks"].append(track_id) + result["cues_placed"] += sum(o.status == ah.PLACED for o in placed.outcomes) + except (_AnalysisError, AdapterError) as ex: + result["failed"].append({"title": title, "reason": str(ex)}) + handle.progress(done=i + 1) + return result + + job = JOBS.submit(CUE_JOB, run) + return JobStatus(**job.as_dict()) + + @app.patch("/api/tracks/cue", response_model=TrackCues) def edit_cue_type(body: SetCueType) -> TrackCues: """Change the type of an existing cue (keeps its position).""" @@ -1020,6 +1095,72 @@ def remove_grid(track_id: str) -> TrackCues: return require_adapter().delete_grid(track_id) +# ---- bulk Remove (the context menu's Remove ▸ submenu) -------------------- +# +# Quick in-memory edits, so requests rather than jobs — but refused while a +# batch analysis runs: it would write cues/grids onto a track removed under it. + + +@app.post("/api/tracks/grid/clear") +def clear_grids(body: TrackIds) -> dict: + """Delete the beatgrid of every given track. Locked grids are skipped — + a lock is the user saying "leave this grid alone" — and reported.""" + a = require_adapter() + if not a.capabilities().grid.editable: + raise HTTPException(422, "This library's beatgrids cannot be edited") + _require_no_batch() + out = {"cleared": 0, "locked": 0, "empty": 0} + for tid in dict.fromkeys(body.track_ids): + track = a.track(tid) + if track is None: + continue + if track.grid_locked: + out["locked"] += 1 + elif not (a.track_cues(tid) or TrackCues()).grid_markers: + out["empty"] += 1 # counted from the cues: the projection's count can be approximate + else: + a.delete_grid(tid) + out["cleared"] += 1 + return out + + +@app.post("/api/tracks/cue/clear") +def clear_hotcues(body: TrackIds) -> dict: + """Empty the whole hotcue bank of every given track — point cues, loops + and the grid's paired beat-1 cue alike (the grid itself is untouched). + Cues the adapter will not edit — Rekordbox memory cues — are kept.""" + a = require_adapter() + caps = a.capabilities() + if not caps.writable or caps.cues.hotcue_slots == 0: + raise HTTPException(422, "This library's hotcues cannot be edited") + _require_no_batch() + out = {"tracks": 0, "cues": 0} + for tid in dict.fromkeys(body.track_ids): + cues = a.track_cues(tid) + slots = sorted({ + c.slot for c in (cues.cues if cues else []) + if c.role == "hotcue" and c.slot is not None and c.editable + }) + for slot in slots: + a.delete_cue(tid, slot) + if slots: + out["tracks"] += 1 + out["cues"] += len(slots) + return out + + +@app.post("/api/tracks/remove") +def remove_tracks(body: TrackIds) -> dict: + """Remove tracks from the library and every playlist. Audio files are + never touched. An export set referencing one will report it as missing, + which is what export sets do with any track that has gone.""" + a = require_adapter() + if not a.capabilities().tracks.removable: + raise HTTPException(422, "Tracks cannot be removed from this library") + _require_no_batch() + return {"removed": a.remove_tracks(list(dict.fromkeys(body.track_ids)))} + + @app.patch("/api/tracks/grid/lock", response_model=TrackCues) def edit_grid_lock(body: SetGridLock) -> TrackCues: """Toggle Traktor's LOCK flag on a track.""" diff --git a/backend/konduktor/schemas.py b/backend/konduktor/schemas.py index 089b572..4a419db 100644 --- a/backend/konduktor/schemas.py +++ b/backend/konduktor/schemas.py @@ -105,6 +105,20 @@ class AutoHotcuesRequest(BaseModel): slots: list[AutoCueSlot] +class TrackIds(BaseModel): + """A body naming a set of tracks — the bulk Remove commands.""" + + track_ids: list[str] + + +class AutoHotcuesBatchRequest(BaseModel): + """The same template applied to every track. `overwrite` on a slot means + "replace this slot's cue on every track that has one".""" + + track_ids: list[str] + slots: list[AutoCueSlot] + + class AutoCueOutcome(BaseModel): slot: int event: AutoCueEvent diff --git a/backend/run_tests.sh b/backend/run_tests.sh index f475c55..38a7b89 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_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_picker.py test_library_id.py test_exports.py test_export.py test_export_pioneer.py test_phase3.py test_history.py; do +for t in test_layering.py test_save_fidelity.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_picker.py test_library_id.py test_exports.py test_export.py test_export_pioneer.py test_phase3.py test_history.py; do echo "──────────────────────────────────────────" echo "▶ $t" echo "──────────────────────────────────────────" diff --git a/backend/test_bulk_remove.py b/backend/test_bulk_remove.py new file mode 100644 index 0000000..2358c7d --- /dev/null +++ b/backend/test_bulk_remove.py @@ -0,0 +1,126 @@ +"""The context menu's Remove ▸ commands, through their routes, on a temp copy. + +Removing from the COLLECTION is new — the protocol's only destroying verb for +tracks — and its bytes are pinned by invariant L in `test_save_fidelity.py`. +This pins what the routes decide: which tracks each command skips (locked +grids, memory cues), that "clear hotcues" empties the whole bank but leaves the +grid, that a removed track leaves the projection AND every playlist while its +audio file is untouched, that the capability gates the route, and that a +running batch analysis blocks all three. +""" +from __future__ import annotations + +import os +import shutil +import tempfile +import time +from pathlib import Path +from types import SimpleNamespace + +REAL = Path(__file__).resolve().parents[1] / "collection.nml" + +failed = False + + +def check(label, cond, detail=""): + global failed + print(f" {'✓' if cond else '✗'} {label}" + ("" if cond else f" [{detail}]")) + if not cond: + failed = True + + +print("== bulk remove ==") +with tempfile.TemporaryDirectory() as d: + work = Path(d) / "collection.nml" + shutil.copy2(REAL, work) + os.environ["KONDUKTOR_NML"] = str(work) + from fastapi.testclient import TestClient + + import konduktor.main as main + + with TestClient(main.app, raise_server_exceptions=False) as c: + a = main.require_adapter() + gridded = [t.id for t in a.tracks if t.grid_marker_count > 0 and not t.grid_locked][:3] + locked = gridded[2] + a.set_grid_lock(locked, True) + bare = next(t.id for t in a.tracks if t.grid_marker_count == 0) + + # ---- grids ---------------------------------------------------------- + r = c.post("/api/tracks/grid/clear", json={"track_ids": [*gridded, bare]}) + check("grid clear answers 200", r.status_code == 200, r.text[:200]) + check("…counts cleared / locked / empty", + r.json() == {"cleared": 2, "locked": 1, "empty": 1}, r.text) + check("the grids are gone", all(not a.track_cues(t).grid_markers for t in gridded[:2])) + check("a locked grid is kept", bool(a.track_cues(locked).grid_markers)) + + # ---- hotcues -------------------------------------------------------- + with_cues = [t.id for t in a.tracks + if (cu := a.track_cues(t.id)) and len(cu.grid_markers) > 0 + and any(q.slot is not None and q.grid_marker is not None for q in cu.cues) + and sum(q.slot is not None for q in cu.cues) >= 2][:2] + before = {t: a.track_cues(t) for t in with_cues} + n_cues = sum(sum(q.slot is not None for q in cu.cues) for cu in before.values()) + r = c.post("/api/tracks/cue/clear", json={"track_ids": with_cues}) + check("hotcue clear answers 200", r.status_code == 200, r.text[:200]) + check("…counts tracks and cues", r.json() == {"tracks": 2, "cues": n_cues}, f"{r.text} vs {n_cues}") + check("the whole bank is empty, incl. the grid's beat-1 cue", + all(not any(q.slot is not None for q in a.track_cues(t).cues) for t in with_cues)) + # Positions and tempos, not the whole marker: its `companion` slot is + # SUPPOSED to become None, since the paired cue was just deleted. + def grid(cu): + return [(m.start, m.bpm) for m in cu.grid_markers] + check("…and the grid itself is untouched (only its pairing ends)", + all(grid(a.track_cues(t)) == grid(before[t]) for t in with_cues) + and all(m.companion is None for t in with_cues for m in a.track_cues(t).grid_markers)) + + # ---- from collection ------------------------------------------------ + caps = c.get("/api/capabilities").json() + check("Traktor advertises removable tracks", caps["tracks"]["removable"] is True) + tree = c.get("/api/playlists").json() + + def lists(nodes): + for n in nodes: + yield n + yield from lists(n["children"]) + + pl = next(n for n in lists(tree) if n.get("count") and n.get("can_add_tracks")) + in_pl = c.get(f"/api/playlists/{pl['id']}/tracks").json() + in_pl = in_pl["tracks"] if isinstance(in_pl, dict) else in_pl + victim = in_pl[0]["id"] + audio = a.audio_path(victim) + existed = audio is not None and audio.exists() + n_before = len(a.tracks) + + r = c.post("/api/tracks/remove", json={"track_ids": [victim, victim, "nope"]}) + check("remove answers 200", r.status_code == 200, r.text[:200]) + check("…and removes exactly one (duplicates / unknowns ignored)", r.json() == {"removed": 1}, r.text) + check("the track leaves the projection", a.track(victim) is None and len(a.tracks) == n_before - 1) + after = c.get(f"/api/playlists/{pl['id']}/tracks").json() + after = after["tracks"] if isinstance(after, dict) else after + check("…and the playlist", all(t["id"] != victim for t in after) and len(after) == len(in_pl) - 1) + check("the audio file is untouched", not existed or audio.exists()) + check("the edit is unsaved (Save lights up)", c.get("/api/state").json().get("dirty") is True) + + # ---- gating ---------------------------------------------------------- + orig_caps = a.capabilities + a.capabilities = lambda: orig_caps().model_copy(update={ + "tracks": orig_caps().tracks.model_copy(update={"removable": False})}) + r = c.post("/api/tracks/remove", json={"track_ids": [gridded[0]]}) + check("remove is refused without the capability", r.status_code == 422, r.text[:200]) + a.capabilities = orig_caps + + main.grid_detect.detect_grid = lambda p, *a_, **k: (time.sleep(0.05), SimpleNamespace(anchor=0.1, bpm=128.0))[1] + a.audio_path = lambda tid: Path(__file__) + jid = c.post("/api/tracks/grid/auto-batch", + json={"track_ids": [t.id for t in a.tracks][:40], "replace_existing": True}).json()["id"] + for route in ("/api/tracks/grid/clear", "/api/tracks/cue/clear", "/api/tracks/remove"): + r = c.post(route, json={"track_ids": [gridded[0]]}) + check(f"{route} is refused while a batch runs", r.status_code == 409, r.text[:200]) + c.post(f"/api/jobs/{jid}/cancel") + + check("nothing was written to disk (edits stay in memory until Save)", + work.read_bytes() == REAL.read_bytes()) + +print() +print("FAILED" if failed else "RESULT: ALL PASSED") +raise SystemExit(1 if failed else 0) diff --git a/backend/test_grid_batch.py b/backend/test_grid_batch.py index c142c9a..fb3e0b8 100644 --- a/backend/test_grid_batch.py +++ b/backend/test_grid_batch.py @@ -1,9 +1,12 @@ -"""Batch grid analysis — the route and its job, on a temp copy of the collection. +"""Batch analysis — grid and Auto Hotcues jobs, on a temp copy of the collection. Detection itself is `test_grid_detect.py`'s job; this pins the WIRING, and the decisions only the batch makes: locked grids are skipped always, existing grids only when asked, a failing track is reported and skipped rather than fatal, a -cancel keeps what is done, and nothing reaches disk before Save. +cancel keeps what is done, and nothing reaches disk before Save. Batch Auto +Hotcues adds: one template on every track, a grid analysed first where there is +none (and an existing one left alone), Replace applying to every track, and one +batch job at a time ACROSS both kinds. """ from __future__ import annotations @@ -14,6 +17,8 @@ import time from pathlib import Path from types import SimpleNamespace +import numpy as np + REAL = Path(__file__).resolve().parents[1] / "collection.nml" failed = False @@ -106,6 +111,90 @@ with tempfile.TemporaryDirectory() as d: n = len(j["result"]["analysed"]) if j["result"] else -1 check("…and still returns what it finished", 0 < n < len(many), str(n)) + # ---- batch Auto Hotcues -------------------------------------------- + print("== batch auto hotcues ==") + main.grid_detect.detect_grid = fake_detect + from konduktor.core import structure + + def fake_analyse(path, markers): + bpm = markers[0][1] + st = structure.Structure(beats=np.arange(400) * 60.0 / bpm, bar0=0, + n_bars=100, duration=400 * 60.0 / bpm) + st.events = {"drop_1": 129, "outro": 353} # clear of any beat-0 grid cue + return st + + main.structure.analyse = fake_analyse + + def free(tid, n): + cu = a.track_cues(tid) + used = {q.slot for q in cu.cues if q.slot is not None} + return [k for k in range(8) if k not in used][:n] + + gridded = next(t.id for t in a.tracks if t.grid_marker_count > 0 and not t.grid_locked + and len(free(t.id, 2)) == 2 and t.id not in many) + nogrid = next(t.id for t in a.tracks if t.grid_marker_count == 0 + and t.id not in (missing, *bare, *many)) + before_grid = a.track_cues(gridded).grid_markers + s0, s1 = free(gridded, 2) + tmpl = [{"slot": s0, "event": "drop_1"}, {"slot": s1, "event": "outro"}] + + r = c.post("/api/tracks/cue/auto-batch", + json={"track_ids": [gridded, nogrid, missing], "slots": tmpl}) + check("the batch route starts a job", r.status_code == 200, r.text[:200]) + j = wait(c, r.json()["id"]) + res = j["result"] + check("the job finishes", j["state"] == "done", str(j)) + check("both tracks got cues", res["tracks"] == [gridded, nogrid], str(res)) + check("a grid is created only where there was none", res["grids_created"] == 1, str(res)) + check("an existing grid is left untouched", + a.track_cues(gridded).grid_markers == before_grid) + check("the track without a grid now has one", len(a.track_cues(nogrid).grid_markers) == 1) + names = {q.slot: q.name for q in a.track_cues(gridded).cues if q.slot is not None} + check("the template's cues are placed", names.get(s0) == "Drop 1" and names.get(s1) == "Outro", str(names)) + check("placed cues are counted", res["cues_placed"] == 4, str(res)) + check("a missing file is reported, not fatal", + len(res["failed"]) == 1 and "not found" in res["failed"][0]["reason"], str(res)) + + # Occupied slots: kept, unless ticked — and then replaced on every track. + # A fresh beat (16 before the drop), so the one-cue-per-beat rule cannot + # be what decides it. + tmpl2 = [{"slot": s0, "event": "drop_1", "offset_beats": -16}] + res = wait(c, c.post("/api/tracks/cue/auto-batch", + json={"track_ids": [gridded], "slots": tmpl2}).json()["id"])["result"] + check("an occupied slot is kept without Replace", res["cues_placed"] == 0, str(res)) + tmpl2[0]["overwrite"] = True + res = wait(c, c.post("/api/tracks/cue/auto-batch", + json={"track_ids": [gridded], "slots": tmpl2}).json()["id"])["result"] + names = {q.slot: q.name for q in a.track_cues(gridded).cues if q.slot is not None} + check("…and replaced with it", names.get(s0) == "Drop 1 -16" and res["cues_placed"] == 1, + f"{names} {res}") + + r = c.post("/api/tracks/cue/auto-batch", + json={"track_ids": [gridded], "slots": [{"slot": 99, "event": "outro"}]}) + check("a template the bank cannot hold is refused up front", r.status_code == 400, r.text[:200]) + r = c.post("/api/tracks/cue/auto-batch", json={"track_ids": [gridded], "slots": []}) + check("an empty template is refused", r.status_code == 400, r.text[:200]) + + # One batch at a time ACROSS kinds. + main.grid_detect.detect_grid = lambda p, *a, **k: (time.sleep(0.05), fake_detect(p))[1] + jid = c.post("/api/tracks/grid/auto-batch", + json={"track_ids": many, "replace_existing": True}).json()["id"] + r = c.post("/api/tracks/cue/auto-batch", json={"track_ids": [gridded], "slots": tmpl}) + check("hotcues are refused while a grid run is going", r.status_code == 409, r.text[:200]) + c.post(f"/api/jobs/{jid}/cancel") + wait(c, jid) + + # Opening another library cancels a running batch. + main.structure.analyse = lambda p, m: (time.sleep(0.05), fake_analyse(p, m))[1] + gridded_many = [t.id for t in a.tracks if t.grid_marker_count > 0][:40] + jid = c.post("/api/tracks/cue/auto-batch", + json={"track_ids": gridded_many, "slots": tmpl}).json()["id"] + time.sleep(0.1) + other = Path(d) / "other.nml" + shutil.copy2(REAL, other) + c.post("/api/library/open", json={"path": str(other)}) + check("opening another library cancels the run", wait(c, jid)["state"] == "cancelled") + check("nothing was written to disk (edits stay in memory until Save)", work.read_bytes() == REAL.read_bytes()) diff --git a/backend/test_onelibrary_adapter.py b/backend/test_onelibrary_adapter.py index e314fce..a507e2e 100644 --- a/backend/test_onelibrary_adapter.py +++ b/backend/test_onelibrary_adapter.py @@ -307,6 +307,7 @@ print("== every command is refused ==") COMMANDS = [ ("set_track_metadata", lambda: adapter.set_track_metadata(one.id, {"title": "x"})), ("set_cover_art", lambda: adapter.set_cover_art(one.id, b"", "image/png")), + ("remove_tracks", lambda: adapter.remove_tracks([one.id])), ("create_playlist", lambda: adapter.create_playlist("x")), ("rename_playlist", lambda: adapter.rename_playlist(node.id, "x")), ("delete_playlist", lambda: adapter.delete_playlist(node.id)), diff --git a/backend/test_rekordbox_adapter.py b/backend/test_rekordbox_adapter.py index ac22482..a0f4556 100644 --- a/backend/test_rekordbox_adapter.py +++ b/backend/test_rekordbox_adapter.py @@ -296,6 +296,9 @@ with tempfile.TemporaryDirectory() as d: print("== what Rekordbox genuinely cannot do still refuses, with a reason ==") commands = { "set_cover_art": lambda: adapter.set_cover_art(sample.id, b"", "image/jpeg"), + # A track spans rows in several tables plus ANLZ files; which of them + # Rekordbox expects deleted together is unmeasured. + "remove_tracks": lambda: adapter.remove_tracks([sample.id]), # Rekordbox genuinely has no per-track grid lock, unlike Traktor's LOCK. "set_grid_lock": lambda: adapter.set_grid_lock(sample.id, True), "remap_locations": lambda: adapter.remap_locations(None), diff --git a/backend/test_save_fidelity.py b/backend/test_save_fidelity.py index 47071fe..1c8ecab 100644 --- a/backend/test_save_fidelity.py +++ b/backend/test_save_fidelity.py @@ -687,5 +687,54 @@ else: check("K: a marker without a companion projects None", ok_comp) +# ---- Invariant L: removing a track from the collection is localized --------- +print("== L. remove_entries drops the ENTRY and its playlist references, nothing else ==") +with tempfile.TemporaryDirectory() as d: + work = Path(d) / "collection.nml" + shutil.copy2(REAL, work) + store = TraktorStore(work) + original = store._render() + + def pl_nodes(st): + return [n for n in st._iter_nodes(st._root()) if n.playlist is not None] + + in_pl = {k for n in pl_nodes(store) for k in store._entry_keys_of(n.playlist)} + target = next(e for e in store._nml.collection.entry + if e.location and store._key_of(e) in in_pl) + key = store._key_of(target) + touched = {n.playlist.uuid for n in pl_nodes(store) if key in store._entry_keys_of(n.playlist)} + untouched = [n.playlist.uuid for n in pl_nodes(store) if n.playlist.uuid not in touched] + n_before = len(store._nml.collection.entry) + + removed = store.remove_entries([key, "no/such/track.mp3"]) + after = store._render() + check("L: exactly one ENTRY removed (an unknown id is ignored)", removed == 1, str(removed)) + + import difflib + plus = [d for d in difflib.unified_diff(tag_lines(original), tag_lines(after), n=0) + if d.startswith("+") and not d.startswith("+++")] + # Every ADDED line is a recount — the collection's or a touched playlist's. + # Nothing is rewritten, only removed. + check("L: the only added lines are ENTRIES recounts", + all("ENTRIES=" in d for d in plus) and len(plus) == 1 + len(touched), "\n".join(plus[:6])) + check("L: every other playlist is byte-identical", + all(original[slice(*playlist_block_span(original, u))] == after[slice(*playlist_block_span(after, u))] + for u in untouched)) + + check("L: the edit journal records a removal, not an edit", + store._journal.removed_tracks() == {key} and not store._journal.edited_tracks()) + summary = store._journal.summary() + check("L: …and the history message says so", "removed 1 track from the collection" in summary.lower(), summary) + + store.save() + re = TraktorStore(work) + keys = [re._key_of(e) for e in re._nml.collection.entry] + check("L: the track is gone from the collection", key not in keys) + check("L: matches the entries", re._nml.collection.entries == len(keys) == n_before - 1) + check("L: …and from every playlist", all(key not in re._entry_keys_of(n.playlist) for n in pl_nodes(re))) + check("L: every playlist's ENTRIES count matches", + all((n.playlist.entries or 0) == len(n.playlist.entry or []) for n in pl_nodes(re))) + + print("\nRESULT:", "FAILED" if failed else "ALL PASSED") sys.exit(1 if failed else 0) diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index b3c2ff8..fc923df 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -1,9 +1,9 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react' import { useQuery, useQueryClient } from '@tanstack/react-query' import type { ColumnSizingState, SortingState, VisibilityState } from '@tanstack/react-table' -import { CapabilitiesContext } from './lib/capabilities' +import { CapabilitiesContext, slotLabeller } from './lib/capabilities' import { writeHint } from './lib/platformCopy' -import { api, type GridBatchResult, type PlaylistNode, type Track } from './api' +import { api, type CueBatchResult, type GridBatchResult, type AutoCueSlot, type PlaylistNode, type Track } from './api' import { COLUMN_MENU, DEFAULT_COLUMN_ORDER, @@ -18,6 +18,8 @@ import { CollectionPicker } from './components/CollectionPicker' import { ContextMenu, type MenuItem } from './components/ContextMenu' import { EditTagsDialog } from './components/EditTagsDialog' import { AnalyzeGridDialog } from './components/AnalyzeGridDialog' +import { AutoCueDialog } from './components/AutoCueDialog' +import { ConfirmDialog, type ConfirmRequest } from './components/ConfirmDialog' import { PathMappingDialog } from './components/PathMappingDialog' import { HistoryPanel } from './components/HistoryPanel' import { PrepStrip } from './components/PrepStrip' @@ -62,14 +64,19 @@ export default function App() { const [prepTrack, setPrepTrack] = useState(null) const [playRequest, setPlayRequest] = useState(0) // bump → deck loads & auto-plays const [importing, setImporting] = useState(false) - // Batch grid analysis: the confirm step (only when some tracks already have - // a grid), then the running job, polled into the status bar. + // Batch analysis (grid, or Auto Hotcues): a confirm step, then the running + // job, polled into the status bar. ONE at a time across both kinds — the + // backend refuses a second, since a grid run would move the beats a hotcue + // run is placing cues on. const [gridConfirm, setGridConfirm] = useState< { ids: string[]; existing: number; locked: number } | null >(null) - const [gridJobId, setGridJobId] = useState(null) - const [gridCancelling, setGridCancelling] = useState(false) + const [cueBatch, setCueBatch] = useState<{ ids: string[]; withoutGrid: number } | null>(null) + const [batchJob, setBatchJob] = useState<{ id: string; kind: 'grid' | 'cues' } | null>(null) + const [batchCancelling, setBatchCancelling] = useState(false) const [cuesRefresh, setCuesRefresh] = useState(0) // bump → deck re-reads its cues + // Every Remove ▸ action (and the playlist Delete key) confirms first. + const [confirmReq, setConfirmReq] = useState(null) const playTrack = useCallback((t: Track) => { setPrepTrack(t) @@ -424,28 +431,29 @@ export default function App() { return m }, [source.kind, tracks]) - const gridJob = useQuery({ - queryKey: ['job', gridJobId], - queryFn: () => api.job(gridJobId!), - enabled: !!gridJobId, + const batchJobStatus = useQuery({ + queryKey: ['job', batchJob?.id ?? null], + queryFn: () => api.job(batchJob!.id), + enabled: !!batchJob, refetchInterval: (q) => (q.state.data && q.state.data.state !== 'running' ? false : 400), }) - const gridDone = gridJob.data?.done ?? 0 + const batchDone = batchJobStatus.data?.done ?? 0 useEffect(() => { // Each finished track is an unsaved edit; let the Save button know as they land. - if (gridDone > 0) qc.invalidateQueries({ queryKey: ['state'] }) - }, [gridDone, qc]) + if (batchDone > 0) qc.invalidateQueries({ queryKey: ['state'] }) + }, [batchDone, qc]) useEffect(() => { - const job = gridJob.data - if (!job || job.state === 'running') return - setGridJobId(null) - setGridCancelling(false) + const job = batchJobStatus.data + if (!job || job.state === 'running' || !batchJob || job.id !== batchJob.id) return + const kind = batchJob.kind + setBatchJob(null) + setBatchCancelling(false) if (job.state === 'failed') { - onError(`Grid analysis failed: ${job.error ?? 'unknown error'}`) + const what = kind === 'grid' ? 'Grid analysis' : 'Auto Hotcues' + onError(`${what} failed: ${job.error ?? 'unknown error'}`) return } - const r = job.result as unknown as GridBatchResult | null - if (!r) return + if (!job.result) return qc.invalidateQueries({ queryKey: ['state'] }) qc.invalidateQueries({ queryKey: ['tracks'] }) qc.invalidateQueries({ queryKey: ['playlist'] }) @@ -453,26 +461,44 @@ export default function App() { qc.invalidateQueries({ queryKey: ['export-playlist-tracks'] }) qc.invalidateQueries({ queryKey: ['export-loose'] }) qc.invalidateQueries({ queryKey: ['facets'] }) - if (prepTrack && r.analysed.includes(prepTrack.id)) setCuesRefresh((n) => n + 1) - const n = r.analysed.length - const parts = [ - `${job.state === 'cancelled' ? 'Cancelled — analyzed' : 'Analyzed'} ${n} track${n === 1 ? '' : 's'}`, - r.existing ? `skipped ${r.existing} with a grid` : '', - r.locked ? `${r.locked} locked` : '', - r.failed.length - ? `${r.failed.length} failed (${r.failed[0].title}: ${r.failed[0].reason}${r.failed.length > 1 ? ', …' : ''})` - : '', - ].filter(Boolean) - notify(r.failed.length && n === 0 ? 'error' : 'success', parts.join(' · ')) + const cancelled = job.state === 'cancelled' + const plural = (n: number, w: string) => `${n} ${w}${n === 1 ? '' : 's'}` + let touched: string[] + let parts: string[] + let failures: CueBatchResult['failed'] + if (kind === 'grid') { + const r = job.result as unknown as GridBatchResult + touched = r.analysed + failures = r.failed + parts = [ + `${cancelled ? 'Cancelled — analyzed' : 'Analyzed'} ${plural(r.analysed.length, 'track')}`, + r.existing ? `skipped ${r.existing} with a grid` : '', + r.locked ? `${r.locked} locked` : '', + ] + } else { + const r = job.result as unknown as CueBatchResult + touched = r.tracks + failures = r.failed + parts = [ + `${cancelled ? 'Cancelled — placed' : 'Placed'} ${plural(r.cues_placed, 'cue')} on ${plural(r.tracks.length, 'track')}`, + r.grids_created ? `analyzed ${plural(r.grids_created, 'new grid')}` : '', + ] + } + if (failures.length) { + const f = failures[0] + parts.push(`${failures.length} failed (${f.title}: ${f.reason}${failures.length > 1 ? ', …' : ''})`) + } + if (prepTrack && touched.includes(prepTrack.id)) setCuesRefresh((n) => n + 1) + notify(failures.length && touched.length === 0 ? 'error' : 'success', parts.filter(Boolean).join(' · ')) // Only the job's finish matters here; prepTrack is read, not tracked. // eslint-disable-next-line react-hooks/exhaustive-deps - }, [gridJob.data]) + }, [batchJobStatus.data]) const handleOpened = () => { setForcePicker(false) setSource({ kind: 'all' }) setSelected(new Set()) - setGridJobId(null) // the backend cancels it; its result is for the old library + setBatchJob(null) // the backend cancels it; its result is for the old library setFilters(emptyFilters) setSorting([]) qc.invalidateQueries() // refetch everything for the newly-opened collection @@ -516,8 +542,8 @@ export default function App() { setGridConfirm(null) try { const job = await api.autoGridBatch(ids, replaceExisting) - setGridCancelling(false) - setGridJobId(job.id) + setBatchCancelling(false) + setBatchJob({ id: job.id, kind: 'grid' }) } catch (e) { onError((e as Error).message) } @@ -539,6 +565,184 @@ export default function App() { } const canAnalyzeGrid = canEdit && !viewingDevice && !!capabilities.data?.grid.editable + const startCueBatch = (ids: string[]) => { + const byId = new Map(tracks.map((t) => [t.id, t])) + const withoutGrid = ids.filter((id) => (byId.get(id)?.grid_marker_count ?? 0) === 0).length + setCueBatch({ ids, withoutGrid }) + } + // Rejects on failure, so the dialog stays open and shows it can be retried. + const runCueBatch = async (ids: string[], slots: AutoCueSlot[]) => { + const job = await api.autoCuesBatch(ids, slots) + setBatchCancelling(false) + setBatchJob({ id: job.id, kind: 'cues' }) + } + const canAutoCue = canEdit && !viewingDevice && (capabilities.data?.cues.hotcue_slots ?? 0) > 0 + + // ---- Remove ▸ ----------------------------------------------------------- + const nTracks = (n: number) => `${n} track${n === 1 ? '' : 's'}` + const trackNoun = (ids: string[]) => { + if (ids.length > 1) return nTracks(ids.length) + const t = tracks.find((x) => x.id === ids[0]) + return t?.title ? `“${t.title}”` : 'this track' + } + // Refetch whatever a track list or the deck could be showing. Throws on + // failure (after reporting), so the confirm dialog stays open for a retry. + const afterBulk = (ids: string[], cuesChanged: boolean) => { + qc.invalidateQueries({ queryKey: ['state'] }) + qc.invalidateQueries({ queryKey: ['tracks'] }) + qc.invalidateQueries({ queryKey: ['playlist'] }) + qc.invalidateQueries({ queryKey: ['playlists'] }) + qc.invalidateQueries({ queryKey: ['export-tracks'] }) + qc.invalidateQueries({ queryKey: ['export-playlist-tracks'] }) + qc.invalidateQueries({ queryKey: ['export-loose'] }) + qc.invalidateQueries({ queryKey: ['export-contents'] }) + qc.invalidateQueries({ queryKey: ['facets'] }) + if (cuesChanged && prepTrack && ids.includes(prepTrack.id)) setCuesRefresh((n) => n + 1) + } + const guard = async (fn: () => Promise) => { + try { + await fn() + } catch (e) { + onError((e as Error).message) + throw e + } + } + + const confirmRemoveFromPlaylist = (ids: string[]) => + setConfirmReq({ + title: 'Remove from playlist', + body: ( +

+ Remove {trackNoun(ids)} from {playlistNode?.name ?? 'this playlist'}? + The {ids.length === 1 ? 'track stays' : 'tracks stay'} in the collection. +

+ ), + confirmLabel: `Remove ${nTracks(ids.length)}`, + onConfirm: () => { + removeFromPlaylist(ids) + setSelected(new Set()) + }, + }) + + const confirmRemoveFromExport = (exportId: string, ids: string[]) => { + const name = exportSets.data?.find((x) => x.id === exportId)?.name ?? 'this export' + setConfirmReq({ + title: 'Remove from export', + body: ( +

+ Remove {trackNoun(ids)} from {name}? Your library is not + changed. +

+ ), + confirmLabel: `Remove ${nTracks(ids.length)}`, + onConfirm: () => + guard(async () => { + await removeFromExport(exportId, ids) + setSelected(new Set()) + }), + }) + } + + const confirmClearGrids = (ids: string[]) => { + const locked = tracks.filter((t) => ids.includes(t.id) && t.grid_locked).length + setConfirmReq({ + title: 'Remove beatgrids', + body: ( + <> +

+ Delete the beatgrid of {trackNoun(ids)}? Tempo and markers go; the paired beat-1 cue goes + with them. Hotcues are kept. +

+ {locked > 0 && ( +

{locked} locked {locked === 1 ? 'grid is' : 'grids are'} kept.

+ )} + + ), + confirmLabel: 'Remove grids', + onConfirm: () => + guard(async () => { + const r = await api.clearGrids(ids) + afterBulk(ids, true) + notify( + 'success', + [`Removed ${r.cleared} grid${r.cleared === 1 ? '' : 's'}`, r.locked ? `${r.locked} locked, kept` : ''] + .filter(Boolean) + .join(' · '), + ) + }), + }) + } + + const confirmClearHotcues = (ids: string[]) => + setConfirmReq({ + title: 'Remove hotcues', + body: ( +

+ Clear every hotcue on {trackNoun(ids)} — cues, loops and the grid’s beat-1 cue? The beatgrid + itself is kept. +

+ ), + confirmLabel: 'Remove hotcues', + onConfirm: () => + guard(async () => { + const r = await api.clearHotcues(ids) + afterBulk(ids, true) + notify('success', `Removed ${r.cues} hotcue${r.cues === 1 ? '' : 's'} from ${nTracks(r.tracks)}`) + }), + }) + + const confirmRemoveTracks = (ids: string[]) => + setConfirmReq({ + title: 'Remove from collection', + body: ( + <> +

+ Remove {trackNoun(ids)} from the collection and from every playlist? +

+

+ The audio {ids.length === 1 ? 'file stays' : 'files stay'} on disk. Nothing is written until you + save, and a save can be rolled back from version history. +

+ + ), + confirmLabel: `Remove ${nTracks(ids.length)}`, + onConfirm: () => + guard(async () => { + const r = await api.removeTracks(ids) + setSelected(new Set()) + if (prepTrack && ids.includes(prepTrack.id)) setPrepTrack(null) + afterBulk(ids, false) + notify('success', `Removed ${nTracks(r.removed)} from the collection`) + }), + }) + + const canClearGrids = canEdit && !viewingDevice && !!capabilities.data?.grid.editable + const canClearCues = canAutoCue + const canRemoveTracks = canEdit && !viewingDevice && !!capabilities.data?.tracks.removable + const exportRootId = + source.kind === 'export' ? source.id : source.kind === 'export-other' ? source.exportId : null + const removeItems = (ids: string[]): MenuItem[] => [ + ...(playlistEditable + ? [{ label: 'From this playlist…', onClick: () => confirmRemoveFromPlaylist(ids) }] + : []), + // Only on the export's ROOT view. Inside a referenced playlist there is + // nothing to remove: the reference is live, and per-track removal would + // need an exclusion list — hidden state deciding what a future export + // contains. Remove the whole playlist, or add tracks instead. + ...(exportRootId ? [{ label: 'From this export…', onClick: () => confirmRemoveFromExport(exportRootId, ids) }] : []), + // Removing touches cues and grids a running batch is writing; the backend + // refuses, so the items say why instead of failing on click. + ...(canClearGrids + ? [{ label: 'Grids…', hint: batchJob ? 'busy' : undefined, disabled: !!batchJob, onClick: () => confirmClearGrids(ids) }] + : []), + ...(canClearCues + ? [{ label: 'Hotcues…', hint: batchJob ? 'busy' : undefined, disabled: !!batchJob, onClick: () => confirmClearHotcues(ids) }] + : []), + ...(canRemoveTracks + ? [{ label: 'From collection…', danger: true, hint: batchJob ? 'busy' : undefined, disabled: !!batchJob, onClick: () => confirmRemoveTracks(ids) }] + : []), + ] + // The "Add to" submenu. Exports are listed even on a read-only library: // adding to one touches no library data — an export is Konduktor's own // curation. The playlist being viewed is left out; adding a track to the @@ -586,43 +790,31 @@ export default function App() { ? [ { label: 'Analyze Grid & BPM', - hint: gridJobId ? 'running' : menu.ids.length > 1 ? String(menu.ids.length) : undefined, - disabled: !!gridJobId, + hint: batchJob ? 'busy' : menu.ids.length > 1 ? String(menu.ids.length) : undefined, + disabled: !!batchJob, onClick: () => startGridAnalysis(menu.ids), }, ] : []), + // The deck's ✨ Auto covers a single loaded track, with its + // existing cues shown; this is the same template over the selection. + ...(canAutoCue + ? [ + { + label: 'Auto Hotcues…', + hint: batchJob ? 'busy' : menu.ids.length > 1 ? String(menu.ids.length) : undefined, + disabled: !!batchJob, + onClick: () => startCueBatch(menu.ids), + }, + ] + : []), // A device's track ids belong to the stick, not the collection, so // there is nothing they could be added to. ...(viewingDevice ? [] : [{ label: 'Add to', submenu: addToItems(menu.ids) }]), - ...(playlistEditable - ? [ - { - label: menu.ids.length > 1 ? `Remove ${menu.ids.length} from playlist` : 'Remove from playlist', - danger: true, - onClick: () => { - removeFromPlaylist(menu.ids) - setSelected(new Set()) - }, - }, - ] - : []), - // Only on the export's ROOT view. Inside a referenced playlist there - // is nothing to remove: the reference is live, and per-track removal - // would need an exclusion list — hidden state deciding what a future - // export contains. Remove the whole playlist, or add tracks instead. - ...(source.kind === 'export' || source.kind === 'export-other' - ? [ - { - label: 'Remove from this export', - onClick: () => - removeFromExport( - source.kind === 'export' ? source.id : source.exportId, - menu.ids, - ), - }, - ] - : []), + ...(() => { + const items = removeItems(menu.ids) + return items.length ? [{ label: 'Remove', submenu: items }] : [] + })(), ]} onClose={() => setMenu(null)} /> @@ -655,6 +847,17 @@ export default function App() { onError={onError} /> )} + {confirmReq && setConfirmReq(null)} />} + {cueBatch && ( + runCueBatch(cueBatch.ids, slots)} + onClose={() => setCueBatch(null)} + onError={onError} + /> + )} {gridConfirm && ( openMenu(track, x, y, true)} onHeaderContextMenu={(x, y) => setHeaderMenu({ x, y })} onPlay={playTrack} @@ -925,16 +1128,16 @@ export default function App() { sourceName={viewName} selected={viewingDevice ? 0 : selected.size} job={ - gridJobId + batchJob ? { - label: 'Analyzing', - done: gridJob.data?.done ?? 0, - total: gridJob.data?.total ?? 0, - detail: gridJob.data?.message, - cancelling: gridCancelling, + label: batchJob.kind === 'grid' ? 'Analyzing grids' : 'Placing hotcues', + done: batchJobStatus.data?.done ?? 0, + total: batchJobStatus.data?.total ?? 0, + detail: batchJobStatus.data?.message, + cancelling: batchCancelling, onCancel: () => { - setGridCancelling(true) - api.cancelJob(gridJobId).catch((e) => onError((e as Error).message)) + setBatchCancelling(true) + api.cancelJob(batchJob.id).catch((e) => onError((e as Error).message)) }, } : null diff --git a/frontend/src/api.ts b/frontend/src/api.ts index 1bcde25..5518d03 100644 --- a/frontend/src/api.ts +++ b/frontend/src/api.ts @@ -232,6 +232,8 @@ export interface Capabilities { rating_max: number editable_fields: TrackField[] media_kinds: MediaKind[] + /** Tracks can be removed from the library (audio files are never touched). */ + removable: boolean artwork: boolean artwork_note: string | null } @@ -353,6 +355,15 @@ export interface GridBatchResult { failed: { title: string; reason: string }[] } +/** What a batch Auto Hotcues run did. `tracks` got the template (whatever it + * placed on each); `failed` could not be analysed. */ +export interface CueBatchResult { + tracks: string[] + cues_placed: number + grids_created: number + failed: { title: string; reason: string }[] +} + export interface SourceCandidate { path: string /** What a person recognises, e.g. "OneLibrary — Hardy". */ @@ -676,6 +687,22 @@ export const api = { /** Many tracks at once, as a job — poll `job()`. Locked grids are always * skipped; existing ones unless `replaceExisting`. The finished job's * `result` is a `GridBatchResult`. */ + /** Auto Hotcues over many tracks, one template for all, as a job. A track + * without a grid gets one analysed first. The finished job's `result` is a + * `CueBatchResult`. */ + autoCuesBatch: (trackIds: string[], slots: AutoCueSlot[]) => + send('POST', '/api/tracks/cue/auto-batch', { track_ids: trackIds, slots }), + /** Delete these tracks' beatgrids; locked grids are skipped and counted. */ + clearGrids: (trackIds: string[]) => + send<{ cleared: number; locked: number; empty: number }>('POST', '/api/tracks/grid/clear', { + track_ids: trackIds, + }), + /** Empty these tracks' whole hotcue bank (the grid is untouched). */ + clearHotcues: (trackIds: string[]) => + send<{ tracks: number; cues: number }>('POST', '/api/tracks/cue/clear', { track_ids: trackIds }), + /** Remove tracks from the library and every playlist. Audio files stay. */ + removeTracks: (trackIds: string[]) => + send<{ removed: number }>('POST', '/api/tracks/remove', { track_ids: trackIds }), autoGridBatch: (trackIds: string[], replaceExisting: boolean) => send('POST', '/api/tracks/grid/auto-batch', { track_ids: trackIds, diff --git a/frontend/src/components/AutoCueDialog.tsx b/frontend/src/components/AutoCueDialog.tsx index 81c7da3..a83dd51 100644 --- a/frontend/src/components/AutoCueDialog.tsx +++ b/frontend/src/components/AutoCueDialog.tsx @@ -3,6 +3,7 @@ import { useQuery, useQueryClient } from '@tanstack/react-query' import { api, type AutoCueEvent, + type AutoCueSlot, type AutoHotcuesResult, type CuePoint, type Track, @@ -17,6 +18,11 @@ import { formatDuration } from '../lib/format' * every track the same way — but the per-slot "replace" ticks are NOT: whether * to overwrite a hand-placed cue is a decision about THIS track, and a * remembered tick would silently clobber the next track's cues. + * + * Batch mode (`batch` instead of `track`) edits the same remembered template but + * does not run it: it hands the slots to `onRun`, which starts a job. There is + * no single track to show existing cues for, so each slot's tick reads "Replace + * existing" and applies to every track in the batch — still never remembered. */ export const AUTO_CUE_EVENTS: { id: AutoCueEvent; label: string }[] = [ @@ -64,18 +70,33 @@ function loadTemplate(prefs: Record | undefined, slots: number) }) } -interface Props { - track: Track +type Props = { slotCount: number slotLabel: (slot: number) => string - /** The track's current hotcues by slot, to mark occupied rows. */ - existing: Map onClose: () => void - onDone: (result: AutoHotcuesResult) => void onError: (msg: string) => void -} +} & ( + | { + track: Track + /** The track's current hotcues by slot, to mark occupied rows. */ + existing: Map + onDone: (result: AutoHotcuesResult) => void + batch?: undefined + onRun?: undefined + } + | { + track?: undefined + existing?: undefined + onDone?: undefined + /** How many tracks the template will be applied to. */ + batch: { count: number; withoutGrid: number } + /** Start the batch; resolve once it has started. */ + onRun: (slots: AutoCueSlot[]) => Promise + } +) -export function AutoCueDialog({ track, slotCount, slotLabel, existing, onClose, onDone, onError }: Props) { +export function AutoCueDialog(props: Props) { + const { slotCount, slotLabel, onClose, onError } = props const qc = useQueryClient() const prefs = useQuery({ queryKey: ['prefs'], queryFn: api.getPrefs }) const [rows, setRows] = useState(null) @@ -114,14 +135,15 @@ export function AutoCueDialog({ track, slotCount, slotLabel, existing, onClose, .patchPrefs({ [PREF_KEY]: template }) .then((p) => qc.setQueryData(['prefs'], p)) .catch(() => {}) + const slots: AutoCueSlot[] = rows.flatMap((r, slot) => + r.event ? [{ slot, event: r.event, offset_beats: r.offset, overwrite: replace.has(slot) }] : [], + ) try { - const result = await api.autoCues( - track.id, - rows.flatMap((r, slot) => - r.event ? [{ slot, event: r.event, offset_beats: r.offset, overwrite: replace.has(slot) }] : [], - ), - ) - onDone(result) + if (props.batch) { + await props.onRun(slots) + } else { + props.onDone(await api.autoCues(props.track.id, slots)) + } onClose() } catch (e) { onError((e as Error).message) @@ -138,7 +160,9 @@ export function AutoCueDialog({ track, slotCount, slotLabel, existing, onClose,
Auto Hotcues
- {track.artist} — {track.title} + {props.batch + ? `${props.batch.count} tracks — the same slots on every one` + : `${props.track.artist} — ${props.track.title}`}
@@ -147,13 +171,31 @@ export function AutoCueDialog({ track, slotCount, slotLabel, existing, onClose, Slot Event Offset (beats) - Existing cue + {props.batch ? 'Occupied slot' : 'Existing cue'} {rows === null ? (
Loading…
) : ( rows.map((r, slot) => { - const cue = existing.get(slot) + const cue = props.existing?.get(slot) + const tick = (label: string, title?: string) => ( + + ) return (
@@ -197,26 +239,11 @@ export function AutoCueDialog({ track, slotCount, slotLabel, existing, onClose, +
- {cue ? ( + {props.batch ? ( + tick('Replace', 'Replace the cue in this slot on every track that has one') + ) : cue ? ( cue.editable ? ( - + tick(`Replace ${cue.name || formatDuration(cue.start)}`, cue.name ?? '') ) : ( Grid cue (kept) @@ -229,6 +256,12 @@ export function AutoCueDialog({ track, slotCount, slotLabel, existing, onClose, ) }) )} + {props.batch && props.batch.withoutGrid > 0 && ( +

+ {props.batch.withoutGrid} of these {props.batch.withoutGrid === 1 ? 'has' : 'have'} no + beatgrid — {props.batch.withoutGrid === 1 ? 'it' : 'they'}’ll get one analyzed first. +

+ )}

Events are found on the beatgrid, counting bar 1 from its first marker — if drops land a bar or two off, move the grid marker onto the first downbeat. Occupied slots are kept @@ -250,7 +283,13 @@ export function AutoCueDialog({ track, slotCount, slotLabel, existing, onClose, disabled={busy || rows === null || active === 0} className="rounded-md bg-accent px-4 py-1.5 text-sm font-semibold text-ink-950 hover:brightness-110 disabled:opacity-40" > - {busy ? 'Analyzing…' : `Analyze & place ${active} cue${active === 1 ? '' : 's'}`} + {busy + ? props.batch + ? 'Starting…' + : 'Analyzing…' + : props.batch + ? `Place ${active} cue${active === 1 ? '' : 's'} on ${props.batch.count} tracks` + : `Analyze & place ${active} cue${active === 1 ? '' : 's'}`} diff --git a/frontend/src/components/ConfirmDialog.tsx b/frontend/src/components/ConfirmDialog.tsx new file mode 100644 index 0000000..c664b7e --- /dev/null +++ b/frontend/src/components/ConfirmDialog.tsx @@ -0,0 +1,79 @@ +import { useEffect, useState, type ReactNode } from 'react' + +export interface ConfirmRequest { + title: string + /** What will happen, in a sentence or two. */ + body: ReactNode + /** The confirm button's label, e.g. "Remove 3 tracks". */ + confirmLabel: string + onConfirm: () => Promise | void +} + +interface Props extends ConfirmRequest { + onClose: () => void +} + +/** A yes/no confirmation for destructive actions. Enter confirms and Esc + * cancels, so a confirmed Delete key stays a two-keystroke action. */ +export function ConfirmDialog({ title, body, confirmLabel, onConfirm, onClose }: Props) { + const [busy, setBusy] = useState(false) + + const confirm = async () => { + if (busy) return + setBusy(true) + try { + await onConfirm() + onClose() + } catch { + setBusy(false) // the caller has already reported it; allow a retry + } + } + + useEffect(() => { + const onKey = (e: KeyboardEvent) => { + if (e.key === 'Escape' && !busy) onClose() + // A focused button handles its own Enter — otherwise tabbing to Cancel + // and pressing Enter would run the destructive action. + if (e.key === 'Enter' && !(e.target instanceof HTMLButtonElement)) { + e.preventDefault() + void confirm() + } + } + window.addEventListener('keydown', onKey) + return () => window.removeEventListener('keydown', onKey) + }) + + return ( +

!busy && onClose()} + > +
e.stopPropagation()} + > +
+ {title} +
+
{body}
+
+ + +
+
+
+ ) +}