Extended Rekordbox support

This commit is contained in:
patben8 committed 2026-09-18 12:59:44 +02:00
1 parent 010f67cd2d
commit 43e712afbd
17 files changed
+837 -100

No files matched your search

+68
View File
@@ -758,3 +758,71 @@ they will need components to actually read them: **this change did not retrofit
per-feature gating**, it added the library-level gate that was missing. A
platform that is writable but cannot, say, edit a beatgrid would still offer the
control today.
---
## 11. Milestone 2: metadata + playlist writes
**Scope decision (Ben, 2026-09-18): shipping Rekordbox writes with NO undo is
accepted.** `capabilities.save.history` stays `False` — a Rekordbox library is
`master.db` + ~200 ANLZ files + `masterPlaylists6.xml`, and restoring the
database alone would roll back Rekordbox's auth token and sampler state (§8.9).
Rekordbox's own `master.backup.db` is the only safety net. Revisit only if Ben
asks; do not silently add a half-backup.
What turns on here: **track metadata and playlists**. Cues and the beatgrid stay
read-only until milestone 3 (§8.2, §8.4 — both are hand-written write paths).
### Milestone 2 landed
`./run_tests.sh` green at **258 assertions**; `npm run build` + 25 vitest pass.
Rekordbox now accepts **track metadata and playlist** edits. Cues and the
beatgrid still refuse, and now say so through `cues.editable` / `grid.editable`
rather than through the library-level flag.
**Per-feature gating came first, deliberately.** §10 warned that flipping
`writable` would re-expose every prep control, because `caps.writable` was the
only gate in the app. So `cues.editable` was added to `CueCapabilities`
(symmetric with `grid.editable`), the 12 PrepStrip handlers were split onto
`refuseCueEdit` / `refuseGridEdit`, and the tables now gate **per field** via a
`editableFields` set in the table meta — `InlineEdit` takes a `readOnly` prop and
`RatingStars` simply loses its `onChange`. Without that, milestone 2 would have
shipped a regression.
**Three real bugs found by building it:**
1. **Foreign-key edits projected as no-ops.** `artist`/`album`/`genre`/`label`/
`remixer` are FKs into lookup tables. Setting the id does not move
SQLAlchemy's cached relationship, so re-projecting immediately read the OLD
name back — the API returned `genre: null` for an edit that had in fact
worked. Fixed with a flush + expire; pinned by a test that sets both a brand
new lookup value and an existing one.
2. **`close()` did not release the file.** `pyrekordbox`'s `close()` only closes
the session; the pooled connection keeps the OS handle, so `master.db` could
not be replaced. Now disposes the engine. This surfaced as a `disk I/O error`
in the fidelity test and would have surfaced in production as a failed
restore or a locked library.
3. **Nothing ever closed the previous library.** `AppState.open()` replaced the
adapter without closing it, leaking a handle per library switch. It now closes
the old one *after* the new one parses, so a failed open leaves the current
library intact.
**`SaveOutcome` was promoted to `core/adapter.py`** under the two-platform rule,
with `snapshot` now optional — Rekordbox has no single blob that IS the library.
`AppState.save()` gates version history on `capabilities.save.history` instead of
assuming every platform is versioned.
Also corrected in CLAUDE.md: the cue routes are `/api/tracks/cue`, not
`/api/tracks/hotcue`.
### What milestone 3 inherits
- `cues.editable` / `grid.editable` are the flags to flip, and the UI already
gates on them — no frontend work should be needed beyond flipping them.
- `beatgrid.beats_from_markers()` is written and unit-tested as the inverse of
the read projection.
- The cue write must maintain **both** `djmdCue` rows and the `contentCue` JSON
mirror + `rb_cue_count` (§8.2), and should decide deliberately whether to stamp
`rb_local_usn` on `djmdCue` rows — Rekordbox itself leaves them NULL.
- `test_rekordbox_fidelity.py` is the harness to extend: add a cue edit and a
grid edit as phases F and G, asserting the same "exactly these rows" property.
+35 -9
View File
@@ -59,7 +59,8 @@ Two independent apps that talk over HTTP:
- `driver.py`/`discovery.py` — `can_open`, default-location detection, restore.
- `beatgrid.py`, `locations.py`, `capabilities.py` — Traktor's grid/companion
rules, LOCATION ↔ OS path conversion, and its capability set.
- `adapters/rekordbox/` — **READ-ONLY** (milestone 1 of the Rekordbox work).
- `adapters/rekordbox/` — **track metadata + playlists writable; cues and the
beatgrid still read-only** (milestone 2).
`master.db` is SQLCipher-encrypted SQLite, read via `pyrekordbox`. Every
mutating command raises `Unsupported` and `capabilities()` advertises nothing
as editable, so the UI never offers an edit. Three things differ from Traktor
@@ -79,7 +80,23 @@ Two independent apps that talk over HTTP:
mapping is NOT a plain index and is deliberately left to the UI.
Writes are refused outright on a **cloud-synced** library (detected by a
server-issued `usn` on any row): a bad sync state would propagate to the
user's other machines, which version history cannot undo.
user's other machines, and there is no version history here to undo it.
Every command passes through `_require_writable()` so a command added later
cannot forget that check.
Edits accumulate in the SQLAlchemy session and `save()` commits — which maps
onto Konduktor's "edit in memory, Save writes to disk" model exactly, since
`pyrekordbox`'s `commit()` is what assigns Rekordbox's USNs. A real Rekordbox
7 was verified to accept a library written this way, display the edit, leave
the row alone, and continue from the counter it was left at.
`artist`/`album`/`genre`/`label`/`remixer` are **foreign keys into lookup
tables**, so a write is find-or-create (pyrekordbox's `add_*` RAISES on an
existing name) followed by a **flush + expire** — without which the ORM
re-reads the stale relationship and a successful edit projects as a no-op.
`producer`/`mix` are absent from `editable_fields`: Rekordbox has no column
for them and its Composer is a different field.
`close()` disposes the SQLAlchemy engine, not just the session — otherwise
the OS file handle stays open and `master.db` cannot be replaced. `AppState`
closes the previous adapter when opening a new library.
- `app_state.py` — the one loaded library, and the **version-history commit**.
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.
@@ -219,6 +236,12 @@ serialization path.** It enforces:
projection, playlist tree, capabilities and the refusal of all 21 commands
against a **temp copy** of the local Rekordbox library. Skips cleanly when no
Rekordbox is installed, so it is safe on any machine.
- `test_rekordbox_fidelity.py` — the **row-level analogue of the byte diff**: a
full table dump before/after, compared row by row (a byte diff is meaningless
against SQLite). Asserts a no-op save changes zero rows; a one-field edit
changes exactly two — the track and `agentRegistry.localUpdateCount` — with the
counter up by one and the edited row stamped with it; edits are invisible on
disk until save; and playlist create/fill/rename/delete round-trip.
- `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).
@@ -327,12 +350,15 @@ that number and nothing else — everything derives from it:
- ✅ Generic model + adapter interface (Traktor as the only adapter) — step 2 of
the multi-platform plan. Backend, wire format and UI are all generic; nothing
above `adapters/traktor/` knows what Traktor is.
- 🟡 Rekordbox adapter — **read-only milestone done**: a Rekordbox library opens,
projects and browses through the generic layer (tracks, playlists, cues,
beatgrid), with every command refused. Research for the write path is captured
in `.claude/handoffs/rekordbox-adapter.md` §8, incl. the verified result that
Rekordbox accepts Konduktor-written rows when USNs are maintained. Remaining:
metadata/playlist writes, then the hand-written cue store and ANLZ grid store.
- 🟡 Rekordbox adapter — **read + metadata/playlist writes done** (milestones 1
and 2). A Rekordbox library opens, projects, browses and now accepts track
metadata and playlist edits, verified row-by-row by `test_rekordbox_fidelity.py`
and end to end through the API. Research is captured in
`.claude/handoffs/rekordbox-adapter.md` §8, incl. the verified result that
Rekordbox accepts Konduktor-written rows when USNs are maintained. Remaining
(milestone 3): the hand-written cue store (`djmdCue` + the `contentCue` JSON
mirror) and the ANLZ beatgrid store. **No version history on Rekordbox** —
accepted scope decision, see handoff §11.
- ⬜ Serato adapter; ⬜ export/conversion
- ⬜ Bulk metadata editing; ⬜ Phase 4 — polish + optional Tauri desktop packaging
@@ -389,7 +415,7 @@ diff — no COLLECTION splicing needed.
`POST/PATCH/DELETE /api/playlists[...]`, `PUT .../entries` (replace),
`POST .../add` (append); `PATCH /api/tracks` (metadata); `GET/PUT /api/tracks/art`
(cover art); `GET /api/tracks/audio` (Range-aware stream for playback/analysis);
`GET /api/tracks/cues`, `POST/PATCH/DELETE /api/tracks/hotcue`,
`GET /api/tracks/cues`, `POST/PATCH/DELETE /api/tracks/cue`,
`POST/PATCH/DELETE /api/tracks/grid/marker`,
`PUT /api/tracks/grid` (replace), `DELETE /api/tracks/grid`,
`PATCH /api/tracks/lock` (prep); `POST /api/save`.
+73 -27
View File
@@ -5,14 +5,17 @@ Mirrors `adapters.traktor.adapter`. It holds:
* a ``RekordboxStore`` — the retained NATIVE model (the open ``master.db``),
* a ``TrackIndex`` — the generic READ projection built from it.
**Read-only milestone.** Every mutating command raises `Unsupported`, and
`capabilities()` reports nothing as editable, so a correct UI never offers one
in the first place; the raise is the backstop, not the mechanism.
**Track metadata and playlists are writable; cues and the beatgrid are not
yet.** Those two are separate native stores (two DB tables kept consistent, and
the per-track ANLZ analysis files), so they keep refusing until milestone 3 —
and `capabilities.cues.editable` / `grid.editable` say so, which is what the UI
actually gates on. The raise is the backstop, not the mechanism.
Writes are refused for a second, permanent reason on a cloud-synced library:
Writes are refused entirely, and permanently, on a **cloud-synced** library:
propagating a bad sync state to the user's other machines is not something
version history can undo. That check lives here so it cannot be bypassed by a
future command path forgetting it.
version history can undo — especially here, where there is no version history at
all. That check lives at the top of every command path so no future command can
forget it.
"""
from __future__ import annotations
@@ -48,6 +51,25 @@ class RekordboxAdapter:
]
)
def _refresh(self, track_id: str) -> None:
"""Re-project one track after a command, so the UI cannot go stale.
Every mutating command must end in this — a forgotten refresh is a
silently stale projection that no byte- or row-level test would catch.
"""
counts = self._store.cue_counts()
row = self._store.content(track_id)
self._index.replace(projection.to_track(row, counts.get(str(row.ID), (0, 0))))
def close(self) -> None:
"""Release the database connection.
Rekordbox's library is a live SQLite file, not a document parsed into
memory: leaving the connection open keeps a file handle (and possibly a
`-wal`) around, so an adapter that is being replaced must be closed.
"""
self._store.close()
def reload(self) -> None:
self._store._load()
self._cloud_synced = self._store.cloud_synced
@@ -55,7 +77,11 @@ class RekordboxAdapter:
# ---- identity --------------------------------------------------------
def capabilities(self) -> Capabilities:
return caps.capabilities_for(self.path, cloud_synced=self._cloud_synced)
return caps.capabilities_for(
self.path,
cloud_synced=self._cloud_synced,
editable_fields=sorted(RekordboxStore.EDITABLE_FIELDS),
)
@property
def cloud_synced(self) -> bool:
@@ -107,6 +133,7 @@ class RekordboxAdapter:
rows = self._store.playlists()
folder = int(tables.PlaylistType.FOLDER)
smart = int(tables.PlaylistType.SMART_PLAYLIST)
writable = not self._cloud_synced
nodes: dict[str, PlaylistNode] = {}
parents: dict[str, str] = {}
@@ -122,10 +149,13 @@ class RekordboxAdapter:
children=[],
# A smart playlist has no static entry list; a folder has no tracks.
selectable=kind == "playlist",
can_add_tracks=False,
can_reorder=False,
can_rename=False,
can_delete=False,
# Rekordbox's own working lists are filtered out by the store, so
# everything reaching here is the user's and may be edited — as
# long as the library itself is writable at all.
can_add_tracks=writable and kind == "playlist",
can_reorder=writable and kind == "playlist",
can_rename=writable,
can_delete=writable,
can_contain_children=kind == "folder",
)
parent = str(r.ParentID or "root")
@@ -184,13 +214,38 @@ class RekordboxAdapter:
def remap_locations(self, mapping: PathMapping) -> int:
raise Unsupported(self._readonly_reason("Rewriting stored paths"))
# ---- commands: track metadata ----------------------------------------
def set_track_metadata(self, track_id: str, fields: dict) -> Track | None:
self._require_writable("Editing track metadata")
self._store.set_track_metadata(track_id, fields)
self._refresh(track_id)
return self._index.get(track_id)
# ---- commands: playlists ----------------------------------------------
def create_playlist(self, name: str, parent_id: str | None = None) -> str:
self._require_writable("Creating playlists")
return self._store.create_playlist(name, parent_id)
def rename_playlist(self, node_id: str, name: str) -> None:
self._require_writable("Renaming playlists")
self._store.rename_playlist(node_id, name)
def delete_playlist(self, node_id: str) -> None:
self._require_writable("Deleting playlists")
self._store.delete_playlist(node_id)
def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int:
self._require_writable("Editing playlists")
return self._store.set_playlist_entries(node_id, track_ids)
# ---- save -------------------------------------------------------------
@property
def dirty(self) -> bool:
return False
return self._store.dirty
def save(self):
raise Unsupported(self._readonly_reason("Saving"))
self._require_writable("Saving")
return self._store.save()
def snapshot(self) -> bytes:
"""The library's bytes, for version history.
@@ -216,20 +271,11 @@ class RekordboxAdapter:
def _refuse(self, what: str):
raise Unsupported(self._readonly_reason(what))
def create_playlist(self, name: str, parent_id: str | None = None) -> str:
self._refuse("Creating playlists")
def rename_playlist(self, node_id: str, name: str) -> None:
self._refuse("Renaming playlists")
def delete_playlist(self, node_id: str) -> None:
self._refuse("Deleting playlists")
def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int:
self._refuse("Editing playlists")
def set_track_metadata(self, track_id: str, fields: dict) -> Track | None:
self._refuse("Editing track metadata")
def _require_writable(self, what: str) -> None:
"""Every write passes through here, so the cloud-sync refusal cannot be
forgotten by a command added later."""
if self._cloud_synced:
raise Unsupported(self._readonly_reason(what))
def set_cover_art(self, track_id: str, data: bytes, mime: str) -> None:
self._refuse("Editing cover art")
@@ -1,10 +1,14 @@
"""What a Rekordbox library can persist.
**Milestone 1 reports everything as read-only.** The spike verified that
Rekordbox accepts writes that maintain its USN columns (see the handoff's
Findings), but the write path is not built yet, and the capability system exists
precisely so the UI never offers an edit that will not persist. Every flag here
is therefore false/empty until milestone 2 turns them on one at a time.
**Track metadata and playlists are writable; cues and the beatgrid are not.**
The spike verified that Rekordbox accepts writes which maintain its USN columns
(see the handoff's Findings), and those two write paths use `pyrekordbox`, which
maintains them. Cues and the grid are separate hand-written stores and stay
false until milestone 3 — the capability system exists precisely so the UI never
offers an edit that will not persist.
A **cloud-synced** library reports `writable=False` regardless: Konduktor will
not write one at all.
Two facts are already known and encoded, because getting them wrong later would
be a silent data bug rather than a missing feature:
@@ -35,7 +39,11 @@ HOTCUE_SLOTS = 8
def capabilities_for(
path, version: str | None = None, *, cloud_synced: bool = False
path,
version: str | None = None,
*,
cloud_synced: bool = False,
editable_fields: list[str] | None = None,
) -> Capabilities:
# A cloud-synced library is refused PERMANENTLY, not pending a milestone:
# a local edit the server did not issue could propagate a broken sync state
@@ -43,9 +51,12 @@ def capabilities_for(
return Capabilities(
platform="rekordbox",
version=version,
writable=False,
readonly_cause="cloud_synced" if cloud_synced else "platform_incomplete",
writable=not cloud_synced,
readonly_cause="cloud_synced" if cloud_synced else None,
cues=CueCapabilities(
# Milestone 3: the cue store is hand-written (djmdCue rows plus the
# contentCue JSON mirror, kept consistent) and does not exist yet.
editable=False,
hotcue_slots=HOTCUE_SLOTS,
slot_labels="letter",
# Rekordbox is the only platform with memory cues, so they are
@@ -61,12 +72,15 @@ def capabilities_for(
grid=GridCapabilities(editable=False, flexible=True, lockable=False),
tracks=TrackCapabilities(
rating_max=5, # Rekordbox stores 0-5 directly, unlike Traktor's /51
editable_fields=[], # read-only in this milestone
# Narrower than Traktor's: `producer` and `mix` have no Rekordbox
# column (its Composer is a different field), so they are absent
# rather than mapped onto something approximate.
editable_fields=sorted(editable_fields or []),
media_kinds=["audio"],
artwork=False,
artwork_note=None,
),
playlists=PlaylistCapabilities(folders=True, smart="read_only", reorder=False),
playlists=PlaylistCapabilities(folders=True, smart="read_only", reorder=True),
save=SaveCapabilities(
app_name="Rekordbox",
library_label="master.db",
+187 -3
View File
@@ -3,8 +3,16 @@
This is the only module that knows ``pyrekordbox`` exists. It owns the decrypted
SQLCipher session, the ANLZ analysis files, and the caches the projection reads.
**Read-only in this milestone.** The write path is deliberately absent rather
than stubbed: a store that cannot write cannot half-write.
**Writes cover track metadata and playlists.** Cues and the beatgrid are
deliberately absent rather than stubbed — they are separate stores (two DB tables
kept consistent, and the ANLZ analysis files) and a store that cannot write them
cannot half-write them.
Edits accumulate in the SQLAlchemy session and are only made permanent by
`save()`, which maps exactly onto Konduktor's "edit in memory, Save writes to
disk" model. `pyrekordbox`'s `commit()` is what assigns Rekordbox's update
sequence numbers, and a real Rekordbox was verified to accept and continue from
the result — see the handoff's Findings.
Two things here are not obvious and are load-bearing:
@@ -24,7 +32,8 @@ from pathlib import Path
from sqlalchemy import func, select, text
from sqlalchemy.orm import joinedload
from ...core.adapter import LibraryNotSupported, NotFound
from ...core.adapter import InvalidCommand, LibraryNotSupported, NotFound, SaveOutcome
from ...core.edit_journal import EditJournal
from ...core.pathmap import PathMapping
log = logging.getLogger(__name__)
@@ -37,6 +46,7 @@ class RekordboxStore:
self.path = Path(path)
self._mapping = PathMapping()
self._grid_cache: dict[str, tuple[list[float], list[float]] | None] = {}
self._journal = EditJournal()
self._load()
# ---- open ------------------------------------------------------------
@@ -54,10 +64,22 @@ class RekordboxStore:
self._by_id: dict[str, object] | None = None
def close(self) -> None:
"""Release the session AND the pooled connection.
`pyrekordbox`'s own `close()` only closes the SQLAlchemy session, which
returns the connection to the engine's pool — the OS file handle stays
open. Disposing the engine is what actually releases `master.db`, and
without it the file cannot be replaced (a restore, or a test copying a
fresh library over it) on any platform that locks open files.
"""
try:
self._db.close()
except Exception: # noqa: BLE001 — closing must never raise
pass
try:
self._db.engine.dispose()
except Exception: # noqa: BLE001
pass
# ---- identity --------------------------------------------------------
@property
@@ -253,3 +275,165 @@ class RekordboxStore:
return [
str(c.FolderPath) for c in self.iter_content() if getattr(c, "FolderPath", None)
]
# ---- writes: track metadata -----------------------------------------
#
# Deliberately NOT editable: the file path (it is the track's identity),
# BPM and key (audio/grid territory), and Rekordbox's own read-only
# bookkeeping. `producer` and `mix` are Traktor concepts with no Rekordbox
# column — Rekordbox has a Composer, which is not the same field — so they
# are simply absent from the set rather than mapped to something close.
_DIRECT_FIELDS = {
"title": "Title",
"comment": "Commnt",
"release_date": "ReleaseDate",
}
# Fields stored as a foreign key into a lookup table, which must be
# found-or-created: `add_*` in pyrekordbox RAISES on an existing name.
_LOOKUP_FIELDS = {
"artist": ("DjmdArtist", "ArtistID", "add_artist"),
"album": ("DjmdAlbum", "AlbumID", "add_album"),
"genre": ("DjmdGenre", "GenreID", "add_genre"),
"label": ("DjmdLabel", "LabelID", "add_label"),
# A remixer IS an artist in Rekordbox — same table, different column.
"remixer": ("DjmdArtist", "RemixerID", "add_artist"),
}
EDITABLE_FIELDS = set(_DIRECT_FIELDS) | set(_LOOKUP_FIELDS) | {"rating"}
def _lookup_id(self, table_name: str, adder: str, name: str) -> str | None:
"""The id of the lookup row called `name`, creating it if needed."""
if not name:
return None
table = getattr(self._tables, table_name)
existing = self._db.session.query(table).filter_by(Name=name).first()
if existing is not None:
return str(existing.ID)
row = getattr(self._db, adder)(name)
return str(row.ID)
def set_track_metadata(self, track_id: str, fields: dict) -> None:
row = self.content(track_id)
for key, value in fields.items():
if key not in self.EDITABLE_FIELDS:
continue # unknown/!safe fields are ignored, never guessed at
if key == "rating":
try:
stars = int(value or 0)
except (TypeError, ValueError):
raise InvalidCommand(f"Rating must be a number, got {value!r}") from None
if not 0 <= stars <= 5:
raise InvalidCommand(f"Rating must be 0-5, got {stars}")
before, new = row.Rating, stars
row.Rating = stars
elif key in self._DIRECT_FIELDS:
column = self._DIRECT_FIELDS[key]
before = getattr(row, column)
new = (value or None) if isinstance(value, str) else value
setattr(row, column, new)
else:
table_name, column, adder = self._LOOKUP_FIELDS[key]
before = getattr(row, column)
new = self._lookup_id(table_name, adder, (value or "").strip())
setattr(row, column, new)
self._journal.record("track", "set", track_id, key, before, new)
# Artist/album/genre/label are FOREIGN KEYS. Setting the id does not move
# the ORM's cached relationship, so re-projecting the row immediately
# would read the OLD name back and report a successful edit as a no-op.
# Flush pushes the ids into the transaction; expiring the row makes the
# next attribute access reload the joined rows with them.
self._db.flush()
self._db.session.expire(row)
# ---- writes: playlists ------------------------------------------------
def _playlist(self, node_id: str):
t = self._tables
row = (
self._db.session.query(t.DjmdPlaylist)
.filter(t.DjmdPlaylist.ID == str(node_id))
.first()
)
if row is None:
raise NotFound(f"No playlist {node_id!r}")
return row
def create_playlist(self, name: str, parent_id: str | None = None) -> str:
name = (name or "").strip()
if not name:
raise InvalidCommand("A playlist needs a name")
parent = self._playlist(parent_id) if parent_id else None
if parent is not None and int(parent.Attribute or 0) != int(
self._tables.PlaylistType.FOLDER
):
raise InvalidCommand("A playlist can only be created inside a folder")
row = self._db.create_playlist(name, parent=parent)
self._journal.record("playlist", "create", name)
return str(row.ID)
def rename_playlist(self, node_id: str, name: str) -> None:
name = (name or "").strip()
if not name:
raise InvalidCommand("A playlist needs a name")
row = self._playlist(node_id)
self._db.rename_playlist(row, name)
self._journal.record("playlist", "rename", name)
def delete_playlist(self, node_id: str) -> None:
row = self._playlist(node_id)
name = row.Name
self._db.delete_playlist(row)
self._journal.record("playlist", "delete", name)
def set_playlist_entries(self, node_id: str, track_ids: list[str]) -> int:
"""Replace a playlist's contents, in the given order.
Rekordbox keys order by `DjmdSongPlaylist.TrackNo`, and there is no
bulk reorder — so this clears the list and re-adds it. `add_to_playlist`
is used one row at a time because it is what maintains Rekordbox's own
USN ordering for these rows.
"""
t = self._tables
playlist = self._playlist(node_id)
if int(playlist.Attribute or 0) != int(t.PlaylistType.PLAYLIST):
raise InvalidCommand("Only a plain playlist has an editable track list")
known = {tid for tid in track_ids if self._by_id and str(tid) in self._by_id}
unknown = [tid for tid in track_ids if tid not in known]
if unknown:
raise NotFound(f"Unknown track(s): {', '.join(map(str, unknown[:3]))}")
existing = (
self._db.session.query(t.DjmdSongPlaylist)
.filter(t.DjmdSongPlaylist.PlaylistID == str(node_id))
.all()
)
for song in existing:
self._db.remove_from_playlist(playlist, song)
for n, track_id in enumerate(track_ids, start=1):
self._db.add_to_playlist(playlist, str(track_id), track_no=n)
self._journal.record("playlist", "entries", playlist.Name, after=len(track_ids))
return len(track_ids)
# ---- save --------------------------------------------------------------
@property
def dirty(self) -> bool:
return self._journal.dirty
def edited_fields(self, track_id: str) -> set[str]:
return self._journal.fields_for(track_id)
def save(self) -> SaveOutcome:
"""Make the session's edits permanent.
`commit(autoinc=True)` is what assigns Rekordbox's update sequence
numbers — one increment per change, stamped onto each changed row. A real
Rekordbox was verified to accept a library written this way and to carry
on from the counter it was left at.
`snapshot` is None: a Rekordbox library is `master.db` plus its analysis
files plus a playlist XML, so there is no single blob to version, and
`capabilities.save.history` says so.
"""
summary = self._journal.summary()
self._db.commit(autoinc=True)
self._journal.clear()
# Reads go through the same session, so nothing needs re-projecting from
# scratch — but the grid cache is keyed by track and survives a save.
return SaveOutcome(summary=summary, snapshot=None, tag_results=[])
@@ -43,6 +43,7 @@ def capabilities_for(path: Path, editable_fields: list[str]) -> Capabilities:
version=nml_version(path),
writable=True,
cues=CueCapabilities(
editable=True,
hotcue_slots=8,
slot_labels="number",
# Traktor has no memory cues — every cue occupies a bank slot.
+1 -8
View File
@@ -42,7 +42,7 @@ from traktor_nml_utils.models.collection import (
)
from xsdata.formats.dataclass.serializers import XmlSerializer
from ...core.adapter import InvalidCommand
from ...core.adapter import InvalidCommand, SaveOutcome
from ...core.edit_journal import EditJournal
from ...core.pathmap import common_dir_prefix
from ...core.pathmap import PathMapping
@@ -73,13 +73,6 @@ class FileTagResult:
detail: str = ""
@dataclass
class SaveOutcome:
summary: str # human-readable edit summary, for the version-history message
snapshot: bytes # exactly the bytes written, for the version-history commit
tag_results: list[FileTagResult]
class TraktorStore:
def __init__(self, nml_path: Path):
self.nml_path = Path(nml_path)
+20 -3
View File
@@ -39,6 +39,17 @@ class AppState:
# One parse: the adapter builds its read projection from the same object
# graph the commands mutate.
adapter = registry.open_library(path)
# Release the previous library first. A file-backed platform (Rekordbox
# holds master.db open) would otherwise leak a handle — and a lingering
# write-ahead log beside a file another process replaces is how a SQLite
# library gets corrupted. Only close once the new one has parsed, so a
# failed open leaves the current library intact.
previous = self.adapter
if previous is not None and hasattr(previous, "close"):
try:
previous.close()
except Exception: # noqa: BLE001 — a failed close must not block the open
pass
# Apply this library's saved OS-path remapping (per-machine, keyed by the
# library's local path) so runtime translation is live on open.
saved = prefs.get_path_mapping(str(path))
@@ -58,9 +69,15 @@ class AppState:
"""
assert self.adapter is not None and self.path is not None
outcome = self.adapter.save()
commit = history.commit(
self.path, outcome.snapshot, outcome.summary, __version__
)
# 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
# capabilities rather than this module knowing which platforms those are.
versioned = self.adapter.capabilities().save.history
commit = None
if versioned and outcome.snapshot is not None:
commit = history.commit(
self.path, outcome.snapshot, outcome.summary, __version__
)
return outcome, commit
+23
View File
@@ -18,6 +18,7 @@ Two rules keep this honest:
"""
from __future__ import annotations
from dataclasses import dataclass, field
from pathlib import Path
from typing import Protocol, runtime_checkable
@@ -26,6 +27,28 @@ from .model import Facets, PlaylistNode, Stats, Track, TrackCues, TrackPage
from .pathmap import PathMapping
@dataclass
class SaveOutcome:
"""What a save produced, in terms every platform can answer.
Promoted here once a second adapter needed it (the two-platform rule). The
fields are deliberately optional because platforms differ in kind, not just
in detail:
* `snapshot` is the exact bytes written, for the version-history commit —
and it is None on a platform Konduktor does not version. A Rekordbox
library is `master.db` plus ~200 analysis files plus a playlist XML, so
there is no single blob that *is* the library, and restoring the database
alone would roll back the app's own auth and sampler state.
* `tag_results` reports embedded audio-file tag writes, which only a
platform that does them will populate.
"""
summary: str # human-readable edit summary, for the version-history message
snapshot: bytes | None = None
tag_results: list = field(default_factory=list)
class AdapterError(Exception):
"""Base for every failure an adapter reports to the HTTP layer."""
+4
View File
@@ -29,6 +29,10 @@ PlaylistKind = Literal["folder", "playlist", "smart"]
class CueCapabilities(BaseModel):
# Whether cues can be CREATED/CHANGED. Symmetric with GridCapabilities —
# a platform can be writable overall while its cue store is not yet
# implemented, which is exactly the Rekordbox milestone-2 state.
editable: bool = False
hotcue_slots: int = 8 # size of the addressable bank; 0 = no bank
slot_labels: Literal["number", "letter"] = "number"
# Memory cues are Rekordbox-only today, so they are modelled and PRESERVED
+1 -1
View File
@@ -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_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_phase3.py test_history.py; do
echo "──────────────────────────────────────────"
echo "▶ $t"
echo "──────────────────────────────────────────"
+70 -16
View File
@@ -34,12 +34,28 @@ from konduktor.adapters.rekordbox.cue_types import ( # noqa: E402
from konduktor.adapters.rekordbox.driver import RekordboxDriver # noqa: E402
from konduktor.adapters.rekordbox.projection import parse_key # noqa: E402
from konduktor.core import registry # noqa: E402
from konduktor.core.adapter import LibraryAdapter, Unsupported # noqa: E402
from konduktor.core.adapter import ( # noqa: E402
InvalidCommand,
LibraryAdapter,
NotFound,
Unsupported,
)
from konduktor.core.model import GridMarker # noqa: E402
failed = False
def _raises(fn, exc) -> bool:
"""True when `fn` raises exactly the expected adapter error."""
try:
fn()
except exc:
return True
except Exception: # noqa: BLE001 — the wrong error is still a failure
return False
return False
def check(label, cond, detail=""):
global failed
print(f" [{'PASS' if cond else 'FAIL'}] {label}" + (f" — {detail}" if detail and not cond else ""))
@@ -195,13 +211,15 @@ with tempfile.TemporaryDirectory() as d:
print("== capabilities gate the UI ==")
caps = adapter.capabilities()
check("platform is rekordbox", caps.platform == "rekordbox")
# The distinction that makes the UI honest: "cannot be written at all" is
# not the same as every per-feature flag happening to be false.
check("the library reports itself as NOT writable", caps.writable is False)
check("and says why, as a fact the UI can word",
caps.readonly_cause == "platform_incomplete", str(caps.readonly_cause))
# Milestone 2: the library IS writable, but only for what is implemented.
# The library-level flag and the per-feature flags are separate gates on
# purpose — see the cue/grid refusals below.
check("a local library is writable", caps.writable is True)
check("with no read-only cause", caps.readonly_cause is None, str(caps.readonly_cause))
check("per-feature flags still describe what Rekordbox CAN do",
caps.cues.memory_cues and caps.grid.flexible)
check("cues are NOT editable yet (milestone 3)", caps.cues.editable is False)
check("the grid is NOT editable yet (milestone 3)", caps.grid.editable is False)
check("8 hot cue slots, labelled by letter",
caps.cues.hotcue_slots == 8 and caps.cues.slot_labels == "letter")
check("memory cues are supported", caps.cues.memory_cues)
@@ -212,19 +230,19 @@ with tempfile.TemporaryDirectory() as d:
check("cue colour is a palette, not free RGB", caps.cues.color == "palette")
check("the grid is flexible but not editable yet",
caps.grid.flexible and not caps.grid.editable)
check("no field is advertised as editable", caps.tracks.editable_fields == [])
check("the editable field set is advertised", bool(caps.tracks.editable_fields))
# Rekordbox has no column for these; Traktor does. Mapping them onto its
# Composer field would silently write the wrong thing.
check("producer/mix are absent rather than approximated",
"producer" not in caps.tracks.editable_fields
and "mix" not in caps.tracks.editable_fields)
check("version history is off (multi-artefact library)", caps.save.history is False)
check("the save warning says Rekordbox holds the library open",
caps.save.overwrite_risk == "while_running")
check("library label is master.db", caps.save.library_label == "master.db")
print("== every command is refused, with a reason ==")
print("== the unimplemented stores still refuse, with a reason ==")
commands = {
"set_track_metadata": lambda: adapter.set_track_metadata(sample.id, {"title": "x"}),
"create_playlist": lambda: adapter.create_playlist("x"),
"rename_playlist": lambda: adapter.rename_playlist("1", "x"),
"delete_playlist": lambda: adapter.delete_playlist("1"),
"set_playlist_entries": lambda: adapter.set_playlist_entries("1", []),
"set_cover_art": lambda: adapter.set_cover_art(sample.id, b"", "image/jpeg"),
"set_cue": lambda: adapter.set_cue(sample.id, slot=1, start_sec=0.0, cue_type="cue"),
"set_cue_type": lambda: adapter.set_cue_type(sample.id, 1, "cue"),
@@ -239,7 +257,8 @@ with tempfile.TemporaryDirectory() as d:
"delete_grid": lambda: adapter.delete_grid(sample.id),
"set_grid_lock": lambda: adapter.set_grid_lock(sample.id, True),
"remap_locations": lambda: adapter.remap_locations(None),
"save": lambda: adapter.save(),
# save() works now; snapshot() must not, because a Rekordbox library is
# more than one file and there is nothing to version.
"snapshot": lambda: adapter.snapshot(),
}
refused = []
@@ -251,8 +270,43 @@ with tempfile.TemporaryDirectory() as d:
pass
except Exception as ex: # noqa: BLE001 — anything else is the wrong error
refused.append(f"{name} ({type(ex).__name__})")
check("every mutating command raises Unsupported", not refused, ", ".join(refused))
check("the adapter is never dirty while read-only", adapter.dirty is False)
check("every cue/grid command still raises Unsupported", not refused, ", ".join(refused))
check("refusing a command leaves the adapter clean", adapter.dirty is False)
print("== metadata writes, including the foreign-key fields ==")
# artist/album/genre/label are FKs into lookup tables, not columns. Setting
# one must (a) find-or-create the lookup row — pyrekordbox's add_* RAISES on
# an existing name — and (b) return a projection that reflects the new value,
# which needs a flush+expire or the ORM reads the stale relationship back.
writable_target = adapter.tracks[0]
updated = adapter.set_track_metadata(
writable_target.id,
{"genre": "Konduktor Probe Genre", "artist": "Konduktor Probe Artist", "rating": 4},
)
check("the command returns the refreshed projection", updated is not None)
if updated:
check("a NEW lookup value is reflected immediately",
updated.genre == "Konduktor Probe Genre" and updated.artist == "Konduktor Probe Artist",
f"{updated.genre!r} / {updated.artist!r}")
check("a direct column is reflected immediately", updated.rating == 4, str(updated.rating))
check("the index holds the same refreshed track",
adapter.track(writable_target.id).genre == "Konduktor Probe Genre")
# Re-using an EXISTING lookup value must not try to create it again.
existing_genre = next(
(t.genre for t in adapter.tracks if t.genre and t.id != writable_target.id), None
)
if existing_genre:
again = adapter.set_track_metadata(writable_target.id, {"genre": existing_genre})
check("an existing lookup value is reused, not re-created",
again is not None and again.genre == existing_genre,
str(again.genre if again else None))
check("an out-of-range rating is rejected",
_raises(lambda: adapter.set_track_metadata(writable_target.id, {"rating": 9}),
InvalidCommand))
check("an unknown track is a NotFound",
_raises(lambda: adapter.set_track_metadata("nope", {"title": "x"}), NotFound))
check("unknown fields are ignored, never guessed at",
adapter.set_track_metadata(writable_target.id, {"not_a_field": "x"}) is not None)
print("== a cloud-synced library is refused permanently, not pending a milestone ==")
# The one failure mode version history cannot undo: a local edit the sync
+241
View File
@@ -0,0 +1,241 @@
"""Rekordbox's analogue of `test_save_fidelity.py`.
The project's core safety property is: **an edit changes only what it was
supposed to change.** For Traktor that is a byte diff of the whole file. A byte
diff is meaningless against SQLite — page layout, free lists and vacuuming move
bytes that carry no meaning — so the equivalent here is a **full table dump
before and after, compared row by row**.
Runs against a TEMP COPY of the local Rekordbox library, and skips cleanly when
no Rekordbox is installed.
Two things about the expected diff are NOT noise and must stay asserted:
* `agentRegistry.localUpdateCount` changes on every save. It is Rekordbox's
global update counter, and NOT bumping it is what would corrupt the library.
* the edited row's own `rb_local_usn` is stamped with that new counter value.
A real Rekordbox 7 was verified to accept a library written exactly this way,
display the edit, leave the row untouched, and carry on from the counter it was
left at — see the handoff's Findings section.
"""
import os
import shutil
import sys
import tempfile
import warnings
from pathlib import Path
warnings.filterwarnings("ignore")
os.environ["KONDUKTOR_DATA_DIR"] = tempfile.mkdtemp(prefix="konduktor-rbfid-appdata-")
from konduktor.adapters.rekordbox import discovery # noqa: E402
from konduktor.adapters.rekordbox.adapter import RekordboxAdapter # noqa: E402
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
# ---- the row-level dump/diff harness -----------------------------------
def dump(db_path: Path) -> dict:
"""Every row of every table, keyed by primary key."""
import sqlcipher3.dbapi2 as sqlcipher
from pyrekordbox.db6.database import BLOB
from pyrekordbox.utils import deobfuscate
con = sqlcipher.connect(str(db_path))
con.execute(f"PRAGMA key='{deobfuscate(BLOB)}'")
cur = con.cursor()
# Materialise the table list FIRST: reusing one cursor for the outer and the
# inner queries silently truncates the outer iteration to a single row.
names = [
r[0]
for r in cur.execute(
"SELECT name FROM sqlite_master WHERE type='table' ORDER BY name"
).fetchall()
]
out: dict[str, dict] = {}
for table in names:
if table == "sqlite_sequence":
continue
cols = [r[1] for r in cur.execute(f'PRAGMA table_info("{table}")').fetchall()]
pk = "ID" if "ID" in cols else cols[0]
rows = {}
for r in cur.execute(f'SELECT * FROM "{table}"').fetchall():
d = dict(zip(cols, r))
rows[str(d.get(pk))] = d
out[table] = rows
con.close()
return out
def diff(before: dict, after: dict, ignore_columns=("updated_at", "created_at")) -> list:
"""(table, pk, kind, detail) for every row-level change."""
changes = []
for table in sorted(set(before) | set(after)):
rows_a, rows_b = before.get(table, {}), after.get(table, {})
for pk in sorted(set(rows_a) | set(rows_b)):
if pk not in rows_a:
changes.append((table, pk, "INSERT", rows_b[pk]))
elif pk not in rows_b:
changes.append((table, pk, "DELETE", rows_a[pk]))
else:
fields = {
k: (rows_a[pk][k], rows_b[pk].get(k))
for k in rows_a[pk]
if k not in ignore_columns and rows_a[pk][k] != rows_b[pk].get(k)
}
if fields:
changes.append((table, pk, "UPDATE", fields))
return changes
def describe(changes) -> str:
return "; ".join(f"{t}/{pk} {kind}" for t, pk, kind, _ in changes) or "(none)"
def clean_copy(src: Path, dest: Path, *, closing=()) -> None:
"""Copy a library WITHOUT any stale write-ahead log.
A `-wal` left beside a replaced `.db` is replayed onto it by SQLite and
corrupts it. This cost real debugging time during the research spike.
`closing` is any adapters still holding the destination open: replacing a
SQLite file under a live connection is an I/O error at best.
"""
for adapter in closing:
adapter.close()
for ext in ("-wal", "-shm"):
stale = Path(str(dest) + ext)
if stale.exists():
stale.unlink()
shutil.copy2(src, dest)
found = discovery.detect_libraries()
if not found:
print("== SKIPPED: no Rekordbox library found on this machine ==")
print("\nRESULT: ALL PASSED")
sys.exit(0)
REAL = Path(found[0]["path"])
print(f"(using a temp copy of {REAL})")
with tempfile.TemporaryDirectory() as d:
work = Path(d) / "master.db"
clean_copy(REAL, work)
share = REAL.parent / "share"
if share.is_dir():
shutil.copytree(share, Path(d) / "share")
# ---- A: a no-op save changes nothing --------------------------------
print("== A: opening and saving without editing changes no row ==")
before = dump(work)
adapter = RekordboxAdapter(work)
check("a freshly opened library is not dirty", adapter.dirty is False)
adapter.save()
changes = diff(before, dump(work))
check("a no-op save changes zero rows", not changes, describe(changes))
# ---- B: one metadata edit touches one row + the counter --------------
print("== B: a single metadata edit is localized ==")
clean_copy(REAL, work, closing=[adapter])
before = dump(work)
adapter = RekordboxAdapter(work)
target = adapter.tracks[0]
original_title = target.title
adapter.set_track_metadata(target.id, {"title": "KONDUKTOR FIDELITY PROBE"})
check("the edit makes the adapter dirty", adapter.dirty is True)
check("the projection updates immediately",
adapter.track(target.id).title == "KONDUKTOR FIDELITY PROBE")
adapter.save()
check("saving clears dirty", adapter.dirty is False)
changes = diff(before, dump(work))
tables_touched = {t for t, _, _, _ in changes}
check("exactly two rows change", len(changes) == 2, describe(changes))
check("they are the track and the update counter",
tables_touched == {"djmdContent", "agentRegistry"}, str(tables_touched))
content = [c for c in changes if c[0] == "djmdContent"]
check("the changed track is the one edited",
len(content) == 1 and content[0][1] == target.id, describe(content))
if content:
fields = content[0][3]
check("only Title and the row's USN changed",
set(fields) == {"Title", "rb_local_usn"}, str(sorted(fields)))
check("Title holds the new value", fields.get("Title", (None, None))[1] == "KONDUKTOR FIDELITY PROBE")
registry = [c for c in changes if c[0] == "agentRegistry"]
check("the global update counter is the registry row that changed",
len(registry) == 1 and registry[0][1] == "localUpdateCount", describe(registry))
if registry:
old_usn, new_usn = registry[0][3]["int_1"]
check("the counter increments by exactly one edit", new_usn == old_usn + 1,
f"{old_usn} -> {new_usn}")
# This is the invariant Rekordbox itself relies on to notice the change.
if content:
check("the edited row is stamped with the new counter value",
content[0][3].get("rb_local_usn", (None, None))[1] == new_usn,
str(content[0][3].get("rb_local_usn")))
# ---- C: the edit survives a reopen ----------------------------------
print("== C: the edit is really on disk ==")
reopened = RekordboxAdapter(work)
check("the new title is there after reopening",
reopened.track(target.id).title == "KONDUKTOR FIDELITY PROBE",
str(reopened.track(target.id).title))
check("the original title is gone", original_title != "KONDUKTOR FIDELITY PROBE")
# ---- D: an unsaved edit is not on disk ------------------------------
print("== D: edits are held until save, like every other platform ==")
clean_copy(REAL, work, closing=[adapter, reopened])
before = dump(work)
adapter = RekordboxAdapter(work)
adapter.set_track_metadata(adapter.tracks[0].id, {"title": "NEVER SAVED"})
changes = diff(before, dump(work))
check("an unsaved edit has written nothing to disk", not changes, describe(changes))
# ---- E: playlist edits -----------------------------------------------
print("== E: a playlist round-trips ==")
clean_copy(REAL, work, closing=[adapter])
adapter = RekordboxAdapter(work)
before_tree = adapter.playlist_tree()
ids = [t.id for t in adapter.tracks[:3]]
node_id = adapter.create_playlist("Konduktor Test Playlist")
adapter.set_playlist_entries(node_id, ids)
adapter.save()
reopened = RekordboxAdapter(work)
names = {n.name for n in reopened.playlist_tree()}
check("the playlist exists after a reopen", "Konduktor Test Playlist" in names, str(names))
check("its entries are the tracks added, in order",
reopened.playlist_entries(node_id) == ids,
f"{reopened.playlist_entries(node_id)} vs {ids}")
tracks = reopened.playlist_tracks(node_id)
check("and they resolve to real projected tracks",
tracks is not None and [t.id for t in tracks] == ids)
reopened.rename_playlist(node_id, "Konduktor Renamed")
reopened.save()
again = RekordboxAdapter(work)
check("a rename round-trips",
"Konduktor Renamed" in {n.name for n in again.playlist_tree()})
again.delete_playlist(node_id)
again.save()
final = RekordboxAdapter(work)
check("a delete round-trips",
"Konduktor Renamed" not in {n.name for n in final.playlist_tree()})
check("the rest of the tree is untouched",
len(final.playlist_tree()) == len(before_tree),
f"{len(final.playlist_tree())} vs {len(before_tree)}")
print("\nRESULT:", "FAILED" if failed else "ALL PASSED")
sys.exit(1 if failed else 0)
+3
View File
@@ -147,6 +147,9 @@ export interface TrackCues {
}
export interface CueCapabilities {
/** Whether cues can be created or changed. Symmetric with grid.editable: a
* platform can be writable overall while its cue store is not implemented. */
editable: boolean
hotcue_slots: number
slot_labels: 'number' | 'letter'
memory_cues: boolean
+37 -19
View File
@@ -563,13 +563,31 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props)
// ---- capability-derived -----------------------------------------------
const caps = useCaps()
// A read-only library refuses every edit. Guarding at the point of INTENT
// means the user gets the reason instead of a 422 from the adapter's backstop,
// and the deck stays fully usable for listening — which is most of its value
// on a library you cannot write.
const refuseIfReadOnly = () => {
if (caps.writable) return false
onError?.(readOnlyNotice(caps) ?? 'This library is read-only.')
// Edits are guarded at the point of INTENT, so the user gets the reason
// instead of a 422 from the adapter's backstop, and the deck stays fully
// usable for listening — which is most of its value on a library you cannot
// write.
//
// TWO gates, not one. `writable` is the library; `cues.editable` and
// `grid.editable` are the features. A platform can be writable overall while
// its cue or grid store is not implemented yet, so gating only on `writable`
// would re-expose these controls the moment that flips — which is exactly how
// this would regress unnoticed when Rekordbox writes land.
const canEditCues = caps.writable && caps.cues.editable
const canEditGrid = caps.writable && caps.grid.editable
const refuseCueEdit = () => {
if (canEditCues) return false
onError?.(
readOnlyNotice(caps) ?? `Cues cannot be edited on ${caps.save.app_name} libraries yet.`,
)
return true
}
const refuseGridEdit = () => {
if (canEditGrid) return false
onError?.(
readOnlyNotice(caps) ??
`The beatgrid cannot be edited on ${caps.save.app_name} libraries yet.`,
)
return true
}
const slotCount = caps.cues.hotcue_slots
@@ -623,7 +641,7 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props)
return
}
if (!cue) {
if (refuseIfReadOnly()) return
if (refuseCueEdit()) return
try {
// Setting a hotcue while a loop is active stores it as a loop hotcue.
if (loopActive && loopRegion) {
@@ -663,7 +681,7 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props)
const canAutoCue = grid != null
const runAutoHotcues = async () => {
if (!track || !canAutoCue || autoBusy) return
if (refuseIfReadOnly()) return
if (refuseCueEdit()) return
const hotcueCount = (c: TrackCues | null) =>
c?.cues.filter((x) => x.role === 'hotcue' && x.slot != null).length ?? 0
if (hotcueCount(cueData) >= slotCount) {
@@ -690,7 +708,7 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props)
const changeSelectedType = async (type: CueType) => {
if (!track || selectedSlot == null) return
if (refuseIfReadOnly()) return
if (refuseCueEdit()) return
try {
applyCueEdit(await api.setCueType(track.id, selectedSlot, type))
} catch (e) {
@@ -700,7 +718,7 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props)
const deleteSelected = async () => {
if (!track || selectedSlot == null) return
if (refuseIfReadOnly()) return
if (refuseCueEdit()) return
try {
applyCueEdit(await api.deleteCue(track.id, selectedSlot))
setSelectedSlot(null)
@@ -713,7 +731,7 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props)
const existing = hotcueAt(slot)
if (!track || !existing) return // nothing to remove in an empty slot
if (existing.grid_marker != null) return // beatgrid-owned: delete the marker instead
if (refuseIfReadOnly()) return
if (refuseCueEdit()) return
try {
applyCueEdit(await api.deleteCue(track.id, slot))
if (selectedSlot === slot) setSelectedSlot(null)
@@ -738,7 +756,7 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props)
const editMarker = async (index: number, patch: { bpm?: number; start?: number }) => {
if (!track || index < 0) return
if (refuseIfReadOnly()) return
if (refuseGridEdit()) return
try {
applyCueEdit(await api.setGridMarker(track.id, index, patch))
} catch (e) {
@@ -760,7 +778,7 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props)
// Uses the raw playhead, not snapTime: a marker defines where beats are.
const addMarkerHere = async () => {
if (!track) return
if (refuseIfReadOnly()) return
if (refuseGridEdit()) return
try {
applyCueEdit(await api.addGridMarker(track.id, playheadNow()))
} catch (e) {
@@ -769,7 +787,7 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props)
}
const deleteMarkerHere = async () => {
if (!track || activeMarkerIndex < 0) return
if (refuseIfReadOnly()) return
if (refuseGridEdit()) return
try {
applyCueEdit(await api.deleteGridMarker(track.id, activeMarkerIndex))
} catch (e) {
@@ -786,7 +804,7 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props)
const resetGrid = async () => {
const o = originalGridRef.current
if (!track || !o) return
if (refuseIfReadOnly()) return
if (refuseGridEdit()) return
try {
applyCueEdit(await api.replaceGridMarkers(track.id, o))
} catch (e) {
@@ -795,7 +813,7 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props)
}
const toggleLock = async () => {
if (!track) return
if (refuseIfReadOnly()) return
if (refuseGridEdit()) return
try {
applyCueEdit(await api.setGridLock(track.id, !cueData?.grid_locked))
} catch (e) {
@@ -804,7 +822,7 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props)
}
const deleteGrid = async () => {
if (!track) return
if (refuseIfReadOnly()) return
if (refuseGridEdit()) return
try {
applyCueEdit(await api.deleteGrid(track.id))
} catch (e) {
@@ -814,7 +832,7 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props)
// Analyze: backend detects BPM + first beat, sets the grid anchor and hotcue 1.
const runAnalyzeGrid = async () => {
if (!track || gridBusy) return
if (refuseIfReadOnly()) return
if (refuseGridEdit()) return
setGridBusy(true)
try {
applyCueEdit(await api.autoGrid(track.id))
+15 -3
View File
@@ -1,4 +1,4 @@
import { useEffect, useRef, useState, type MutableRefObject } from 'react'
import { useEffect, useMemo, useRef, useState, type MutableRefObject } from 'react'
import {
flexRender,
getCoreRowModel,
@@ -11,6 +11,7 @@ import {
type VisibilityState,
} from '@tanstack/react-table'
import { useVirtualizer } from '@tanstack/react-virtual'
import { useCaps } from '../lib/capabilities'
import {
DndContext,
PointerSensor,
@@ -31,6 +32,15 @@ import { CSS } from '@dnd-kit/utilities'
import type { Track } from '../api'
import { TRACK_COLUMNS } from '../lib/trackColumns'
/** Fields this platform can persist, for the table's per-cell edit gating.
* Platforms differ in WHICH fields they accept, so the all-or-nothing
* `onEditField` handler is not enough on its own. */
function useEditableFields(): ReadonlySet<string> {
const caps = useCaps()
return useMemo(() => new Set(caps.tracks.editable_fields), [caps.tracks.editable_fields])
}
const ROW_HEIGHT = 44
// Stable reference. A controlled `state.sorting` that's a fresh `[]` each render
// (with no `onSortingChange`) makes TanStack Table re-sync its internal state
@@ -259,11 +269,12 @@ export function TrackTable({
onEditField,
activeTrackId,
}: Props) {
const editableFields = useEditableFields()
const table = useReactTable({
data: tracks,
columns: TRACK_COLUMNS,
state: { sorting, columnVisibility, columnOrder, columnSizing },
meta: { onEditField },
meta: { onEditField, editableFields },
onSortingChange: (updater) =>
onSortingChange(typeof updater === 'function' ? updater(sorting) : updater),
onColumnSizingChange: (updater) =>
@@ -457,11 +468,12 @@ export function PlaylistTable({
const [items, setItems] = useState<Track[]>(tracks)
useEffect(() => setItems(tracks), [tracks])
const editableFields = useEditableFields()
const table = useReactTable({
data: items,
columns: TRACK_COLUMNS,
state: { sorting: NO_SORTING, columnVisibility, columnOrder, columnSizing },
meta: { onEditField },
meta: { onEditField, editableFields },
enableSorting: false, // playlist order is manual
onColumnSizingChange: (updater) =>
onColumnSizingChange(typeof updater === 'function' ? updater(columnSizing) : updater),
+34 -1
View File
@@ -22,6 +22,12 @@ declare module '@tanstack/react-table' {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
interface TableMeta<TData extends RowData> {
onEditField?: (track: Track, field: keyof Track, value: string | number) => void
/** Fields the loaded platform can actually persist
* (`capabilities.tracks.editable_fields`). A field outside this set renders
* read-only: the platform-level `onEditField` gate is all-or-nothing, and
* platforms genuinely differ in WHICH fields they accept. Undefined means
* "not gated" — every field with a handler stays editable. */
editableFields?: ReadonlySet<string>
}
}
@@ -34,11 +40,14 @@ function InlineEdit({
display,
onCommit,
className = 'w-full min-w-0 truncate text-muted',
readOnly = false,
}: {
value: string | null
display?: ReactNode
onCommit: (v: string) => void
className?: string
/** Render the value without offering an editor. */
readOnly?: boolean
}) {
const [editing, setEditing] = useState(false)
const [val, setVal] = useState('')
@@ -70,6 +79,13 @@ function InlineEdit({
/>
)
}
if (readOnly) {
return (
<div className={className}>
{display ?? (value?.trim() ? value : <span className="text-faint">—</span>)}
</div>
)
}
return (
<div
onDoubleClick={(e) => {
@@ -85,12 +101,20 @@ function InlineEdit({
)
}
/** Whether this table may edit `field`, per the platform's capabilities. */
function canEdit(c: CellContext<Track, unknown>, field: string): boolean {
const meta = c.table.options.meta
if (!meta?.onEditField) return false
return meta.editableFields ? meta.editableFields.has(field) : true
}
// Cell renderer factory for a plain editable text field.
function editable(field: keyof Track, className?: string) {
return (c: CellContext<Track, unknown>) => (
<InlineEdit
value={c.getValue() as string | null}
className={className}
readOnly={!canEdit(c, field)}
onCommit={(v) => c.table.options.meta?.onEditField?.(c.row.original, field, v)}
/>
)
@@ -111,11 +135,13 @@ export const TRACK_COLUMNS: ColumnDef<Track, any>[] = [
value={title}
display={title || <span className="text-faint">Untitled</span>}
className="w-full min-w-0 truncate font-medium text-text"
readOnly={!canEdit(c, 'title')}
onCommit={(v) => edit?.(r, 'title', v)}
/>
<InlineEdit
value={r.artist}
className="w-full min-w-0 truncate text-xs text-muted"
readOnly={!canEdit(c, 'artist')}
onCommit={(v) => edit?.(r, 'artist', v)}
/>
</div>
@@ -185,7 +211,13 @@ export const TRACK_COLUMNS: ColumnDef<Track, any>[] = [
cell: (c) => (
<RatingStars
value={c.getValue() as number}
onChange={(v) => c.table.options.meta?.onEditField?.(c.row.original, 'rating', v)}
// RatingStars is read-only without an onChange, which is exactly the
// behaviour wanted when the platform cannot persist a rating.
onChange={
canEdit(c, 'rating')
? (v) => c.table.options.meta?.onEditField?.(c.row.original, 'rating', v)
: undefined
}
/>
),
}),
@@ -257,6 +289,7 @@ export const TRACK_COLUMNS: ColumnDef<Track, any>[] = [
<InlineEdit
value={c.getValue() as string | null}
display={<span className="tabular-nums text-muted">{formatDate(c.getValue() as string | null)}</span>}
readOnly={!canEdit(c, 'release_date')}
onCommit={(v) => c.table.options.meta?.onEditField?.(c.row.original, 'release_date', v)}
/>
),