diff --git a/.claude/handoffs/rekordbox-adapter.md b/.claude/handoffs/rekordbox-adapter.md index aed3bd1..c701392 100644 --- a/.claude/handoffs/rekordbox-adapter.md +++ b/.claude/handoffs/rekordbox-adapter.md @@ -698,3 +698,63 @@ advertised as editable); the raise is the backstop. see §8.2 and §8.4. `beatgrid.beats_from_markers()` is already written and unit-tested as the inverse of the read projection, so the grid write has a starting point. + +--- + +## 10. The read-only capability landed + +`Capabilities` now carries **`writable: bool`** and **`readonly_cause`** +(`platform_incomplete` | `cloud_synced`), backend and frontend in the same +change. `./run_tests.sh` is green at **225 assertions**; `npm run build` and +`npm run test` (25) pass. + +This was §9's prerequisite, and building it surfaced that the gap was bigger than +"the UI lacks a label": + +**Almost nothing gated on editability.** `capabilities.tracks.editable_fields` +and `grid.editable` were modelled but consulted by **no component at all** — only +`hotcue_slots`, `cues.types` and `rating_max` were ever read. So on a Rekordbox +library the UI would have cheerfully offered Edit Tags, inline editing, +click-to-rate, playlist create/rename/delete and every prep-deck control, each +one 422-ing at the adapter. The adapter's `Unsupported` was doing all the work, +as a backstop for a UI that never gated. + +Now gated on `writable`: `SaveBar` (replaces the save button with the reason), +`App`'s `onEditField` (inline edit + rating go inert), the "Edit Tags…" context +item, `Sidebar`'s new-playlist button, and all 12 `PrepStrip` edit handlers — +which report the reason instead of firing the request. The deck stays fully +usable for listening, with a "Read-only" badge, because that is most of its value +on a library you cannot write. + +**Two latent bugs fixed in passing**, both only reachable once a second platform +existed: +- The sidebar's **delete** button was gated on `can_rename`, not `can_delete`, so + a platform allowing one but not the other would offer both. +- The playlist **track-count badge** was inside that same block, so a read-only + library would have shown no counts at all — information hidden as though it + were an action. + +**Verified end to end**, not just in tests: opening a Rekordbox library reports +`writable: false, readonly_cause: platform_incomplete` over HTTP, and switching +to the Traktor collection at runtime flips it to `writable: true, cause: null` +with 11 editable fields. + +**The cloud-synced branch is tested for real**, not asserted: the test forges a +server-issued `usn` on a throwaway copy, confirms detection flips to +`cloud_synced`, and confirms the refusal names Rekordbox Cloud rather than the +milestone. That is the one failure mode version history cannot undo, so it is +worth the setup. + +Also corrected: CLAUDE.md documented the runtime open route as +`POST /api/collection/open`; it is `POST /api/library/open`. + +### Note for whoever does milestone 2 + +When Rekordbox writes land, `writable` flips to true for a *local* library while +staying false for a cloud-synced one — the two causes already distinguish that, +and `RekordboxAdapter._readonly_reason()` already words both. The per-feature +flags (`editable_fields`, `grid.editable`, …) then become the finer gate, and +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. diff --git a/CLAUDE.md b/CLAUDE.md index be4725e..e0dc140 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -88,7 +88,7 @@ Two independent apps that talk over HTTP: - `schemas.py` — HTTP request bodies + envelopes; re-exports `core.model`. - `main.py` — thin FastAPI routes (all under `/api`), talking only to the adapter. Starts **unloaded**; the library is chosen at runtime via - `POST /api/collection/open` (data routes 409 until then). + `POST /api/library/open` (data routes 409 until then). `GET /api/capabilities` feeds the UI's gating; `GET /api/fs/list` powers the file browser; `GET`/`PATCH /api/prefs` persist UI prefs. Setting `KONDUKTOR_NML` auto-loads on startup (dev/tests). @@ -146,10 +146,25 @@ Two independent apps that talk over HTTP: analysis + paint), `beatgrid.ts` (the marker-list beat math — every beat/bar/snap/jump calculation goes through it), `cues.ts` (draw cues/loop/beatgrid/cue-point). See "Prep engine" below. + - **`capabilities.writable`** is the library-level gate, and it is deliberately + NOT the same as every per-feature flag being false: "the platform has no such + feature" and "this library cannot be written at all" look identical to a UI + that only sees per-feature flags, and silently inert controls read as a bug. + `readonly_cause` says which kind (`platform_incomplete` / `cloud_synced`) and + `platformCopy.readOnlyNotice()` words it — the two need very different + sentences, since one is a roadmap gap and the other a permanent refusal that + protects the user's other machines. Gated on it: `SaveBar` (replaces the save + button with the reason), `App`'s `onEditField` (inline edit + click-to-rate + go inert), the "Edit Tags…" context item, `Sidebar`'s new-playlist button, + and all 12 `PrepStrip` edit handlers (which report the reason rather than + firing a request the adapter would refuse — the deck stays fully usable for + listening, and shows a "Read-only" badge). - Capability-gated today: hotcue bank size (`HotcueBar`, the auto-cue guard and the digit shortcuts all read `cues.hotcue_slots`), the cue-type dropdown (`cues.types`), the rating scale (`tracks.rating_max`), the grid Lock button - (`grid.lockable`). Carried but deliberately unused until a second adapter + (`grid.lockable`). Per-node playlist flags (`can_rename`, `can_delete`, + `can_add_tracks`) gate the sidebar and `SelectionBar` — each on its OWN flag, + since a platform may allow renaming but not deleting. Carried but deliberately unused until a second adapter exists: `slot_labels: 'letter'`, `palette`, `loops: 'separate_bank'`, and memory-cue *editing* (one-platform features stay preserved-but-uneditable). - `lib/trackColumns.tsx` — single source of truth for the library table's diff --git a/backend/konduktor/adapters/rekordbox/capabilities.py b/backend/konduktor/adapters/rekordbox/capabilities.py index 838c3e1..dbaa09f 100644 --- a/backend/konduktor/adapters/rekordbox/capabilities.py +++ b/backend/konduktor/adapters/rekordbox/capabilities.py @@ -37,9 +37,14 @@ HOTCUE_SLOTS = 8 def capabilities_for( path, version: str | None = None, *, cloud_synced: bool = False ) -> 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 + # to the user's other machines, which version history cannot undo. return Capabilities( platform="rekordbox", version=version, + writable=False, + readonly_cause="cloud_synced" if cloud_synced else "platform_incomplete", cues=CueCapabilities( hotcue_slots=HOTCUE_SLOTS, slot_labels="letter", diff --git a/backend/konduktor/adapters/traktor/capabilities.py b/backend/konduktor/adapters/traktor/capabilities.py index f684c49..2e98f33 100644 --- a/backend/konduktor/adapters/traktor/capabilities.py +++ b/backend/konduktor/adapters/traktor/capabilities.py @@ -41,6 +41,7 @@ def capabilities_for(path: Path, editable_fields: list[str]) -> Capabilities: return Capabilities( platform="traktor", version=nml_version(path), + writable=True, cues=CueCapabilities( hotcue_slots=8, slot_labels="number", diff --git a/backend/konduktor/core/capabilities.py b/backend/konduktor/core/capabilities.py index a0f7485..b08fe42 100644 --- a/backend/konduktor/core/capabilities.py +++ b/backend/konduktor/core/capabilities.py @@ -15,6 +15,13 @@ from typing import Literal from pydantic import BaseModel +# Why a library cannot be edited. A FACT, not a sentence — the UI composes the +# wording (lib/platformCopy.ts), and the two causes need very different ones: +# "Konduktor cannot write this platform YET" is a roadmap gap the user should +# expect to close, whereas "this library is synced with Rekordbox Cloud" is a +# permanent refusal protecting their other machines. +ReadonlyCause = Literal["platform_incomplete", "cloud_synced"] + CueType = Literal["cue", "fade_in", "fade_out", "load", "loop"] CueRole = Literal["hotcue", "memory"] MediaKind = Literal["audio", "stem", "video"] @@ -74,6 +81,16 @@ class SaveCapabilities(BaseModel): class Capabilities(BaseModel): platform: str version: str | None = None + # Whether ANY edit can be persisted to this library. + # + # This is deliberately NOT the same as every individual capability being + # false. "The platform has no such feature" and "this library cannot be + # written at all" look identical to a UI that only sees the per-feature + # flags, and the second one needs saying out loud — silently inert controls + # read as a bug. When this is false the per-feature flags are still reported + # honestly, so the UI can show what the platform *would* support. + writable: bool = True + readonly_cause: ReadonlyCause | None = None cues: CueCapabilities = CueCapabilities() grid: GridCapabilities = GridCapabilities() tracks: TrackCapabilities = TrackCapabilities() diff --git a/backend/test_rekordbox_adapter.py b/backend/test_rekordbox_adapter.py index 5816f03..f3f7b55 100644 --- a/backend/test_rekordbox_adapter.py +++ b/backend/test_rekordbox_adapter.py @@ -195,6 +195,13 @@ 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)) + check("per-feature flags still describe what Rekordbox CAN do", + caps.cues.memory_cues and caps.grid.flexible) 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) @@ -247,6 +254,40 @@ with tempfile.TemporaryDirectory() as d: check("every mutating command raises Unsupported", not refused, ", ".join(refused)) check("the adapter is never dirty while read-only", adapter.dirty is False) + 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 + # server did not issue could corrupt the user's OTHER machines. Detection is + # a server-issued `usn`, so forge one on a throwaway copy and check it flips. + synced = Path(d) / "synced.db" + shutil.copy2(work, synced) + import sqlcipher3.dbapi2 as sqlcipher + from pyrekordbox.db6.database import BLOB + from pyrekordbox.utils import deobfuscate + + con = sqlcipher.connect(str(synced)) + con.execute(f"PRAGMA key='{deobfuscate(BLOB)}'") + con.execute("UPDATE djmdContent SET usn = 42 WHERE ID = (SELECT ID FROM djmdContent LIMIT 1)") + con.commit() + con.execute("PRAGMA wal_checkpoint(TRUNCATE)") + con.close() + for ext in ("-wal", "-shm"): + stale = Path(str(synced) + ext) + if stale.exists(): + stale.unlink() # a stale WAL beside a copied .db corrupts it + + cloud = RekordboxAdapter(synced) + ccaps = cloud.capabilities() + check("a server-issued usn marks the library cloud-synced", cloud.cloud_synced) + check("the read-only cause distinguishes it from a missing feature", + ccaps.readonly_cause == "cloud_synced", str(ccaps.readonly_cause)) + try: + cloud.set_track_metadata(cloud.tracks[0].id, {"title": "x"}) + check("a cloud-synced library refuses edits", False, "no refusal") + except Unsupported as ex: + check("a cloud-synced library refuses edits", True) + check("and the refusal names the real reason, not the milestone", + "Cloud" in str(ex), str(ex)) + print("== reads that must still work ==") page = adapter.query_tracks(limit=5) check("query_tracks paginates", len(page.items) <= 5 and page.total == len(adapter.tracks)) diff --git a/backend/test_traktor_adapter.py b/backend/test_traktor_adapter.py index d37d77d..3cca19b 100644 --- a/backend/test_traktor_adapter.py +++ b/backend/test_traktor_adapter.py @@ -80,6 +80,8 @@ with tempfile.TemporaryDirectory() as d: adapter = TraktorAdapter(work) caps = adapter.capabilities() check("platform reported", caps.platform == "traktor") + check("the library is writable, with no read-only cause", + caps.writable is True and caps.readonly_cause is None) check("version read from the NML header", caps.version == "20", str(caps.version)) check("8 hotcue slots", caps.cues.hotcue_slots == 8) check("no memory cues on Traktor", caps.cues.memory_cues is False) diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 4b0bd55..854d9ac 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -136,7 +136,11 @@ export default function App() { }, []) const onError = useCallback((msg: string) => notify('error', msg), [notify]) - // Inline single-field edit from a double-clicked table cell. + // Inline single-field edit from a double-clicked table cell. Only offered when + // the library can take an edit: passing `undefined` makes those cells inert + // rather than firing a request the adapter will refuse. Defaults to false, so + // no edit is ever offered before capabilities have resolved. + const canEdit = capabilities.data?.writable ?? false const editField = useCallback( (track: Track, field: keyof Track, value: string | number) => { api @@ -265,7 +269,11 @@ export default function App() { y={menu.y} items={[ { label: 'Load to Deck', onClick: () => setPrepTrack(menu.track) }, - { label: 'Edit Tags…', onClick: () => setEditing(menu.track) }, + // Offering "Edit Tags…" on a read-only library would open a dialog + // whose every save is refused, so it is not offered at all. + ...(canEdit + ? [{ label: 'Edit Tags…', onClick: () => setEditing(menu.track) }] + : []), ]} onClose={() => setMenu(null)} /> @@ -348,7 +356,7 @@ export default function App() { }} onRowContextMenu={(track, x, y) => setMenu({ track, x, y })} onPlay={playTrack} - onEditField={editField} + onEditField={canEdit ? editField : undefined} activeTrackId={prepTrack?.id ?? null} columnVisibility={columnVisibility} columnOrder={columnOrder} @@ -374,7 +382,7 @@ export default function App() { tracks={filtered} onRowContextMenu={(track, x, y) => setMenu({ track, x, y })} onPlay={playTrack} - onEditField={editField} + onEditField={canEdit ? editField : undefined} activeTrackId={prepTrack?.id ?? null} columnVisibility={columnVisibility} columnOrder={columnOrder} diff --git a/frontend/src/api.ts b/frontend/src/api.ts index e6e2a4e..5bb1675 100644 --- a/frontend/src/api.ts +++ b/frontend/src/api.ts @@ -168,9 +168,21 @@ export interface SaveCapabilities { history: boolean } +/** Why a library cannot be edited. A fact — lib/platformCopy.ts words it. */ +export type ReadonlyCause = 'platform_incomplete' | 'cloud_synced' + export interface Capabilities { platform: Platform version: string | null + /** Whether ANY edit can be persisted. + * + * Deliberately not the same as every per-feature flag being false: "the + * platform has no such feature" and "this library cannot be written at all" + * look identical to a UI that only sees the per-feature flags, and silently + * inert controls read as a bug. Gate edit affordances on this AND on the + * per-feature flag. */ + writable: boolean + readonly_cause: ReadonlyCause | null cues: CueCapabilities grid: { editable: boolean; flexible: boolean; lockable: boolean } tracks: { diff --git a/frontend/src/components/PrepStrip.tsx b/frontend/src/components/PrepStrip.tsx index 4b201c2..ce3fb29 100644 --- a/frontend/src/components/PrepStrip.tsx +++ b/frontend/src/components/PrepStrip.tsx @@ -4,6 +4,7 @@ import { api, type CueType, type GridMarker, type Track, type TrackCues } from ' import { buildBeatGrid, GRID_EPS } from '../lib/beatgrid' import { slotLabeller, useCaps } from '../lib/capabilities' import { CUE_TYPE_LABELS } from '../lib/cues' +import { readOnlyShort, readOnlyNotice } from '../lib/platformCopy' import { analyzeWaveform, type WaveColumn } from '../lib/waveform' import { ScratchEngine } from '../lib/scratchEngine' import { PlaybackEngine } from '../lib/playbackEngine' @@ -562,6 +563,15 @@ 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.') + return true + } const slotCount = caps.cues.hotcue_slots const slotLabel = slotLabeller(caps) // Loops are a cue TYPE on some platforms and a separate bank on others; the @@ -613,6 +623,7 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props) return } if (!cue) { + if (refuseIfReadOnly()) return try { // Setting a hotcue while a loop is active stores it as a loop hotcue. if (loopActive && loopRegion) { @@ -652,6 +663,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 const hotcueCount = (c: TrackCues | null) => c?.cues.filter((x) => x.role === 'hotcue' && x.slot != null).length ?? 0 if (hotcueCount(cueData) >= slotCount) { @@ -678,6 +690,7 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props) const changeSelectedType = async (type: CueType) => { if (!track || selectedSlot == null) return + if (refuseIfReadOnly()) return try { applyCueEdit(await api.setCueType(track.id, selectedSlot, type)) } catch (e) { @@ -687,6 +700,7 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props) const deleteSelected = async () => { if (!track || selectedSlot == null) return + if (refuseIfReadOnly()) return try { applyCueEdit(await api.deleteCue(track.id, selectedSlot)) setSelectedSlot(null) @@ -699,6 +713,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 try { applyCueEdit(await api.deleteCue(track.id, slot)) if (selectedSlot === slot) setSelectedSlot(null) @@ -723,6 +738,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 try { applyCueEdit(await api.setGridMarker(track.id, index, patch)) } catch (e) { @@ -744,6 +760,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 try { applyCueEdit(await api.addGridMarker(track.id, playheadNow())) } catch (e) { @@ -752,6 +769,7 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props) } const deleteMarkerHere = async () => { if (!track || activeMarkerIndex < 0) return + if (refuseIfReadOnly()) return try { applyCueEdit(await api.deleteGridMarker(track.id, activeMarkerIndex)) } catch (e) { @@ -768,6 +786,7 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props) const resetGrid = async () => { const o = originalGridRef.current if (!track || !o) return + if (refuseIfReadOnly()) return try { applyCueEdit(await api.replaceGridMarkers(track.id, o)) } catch (e) { @@ -776,6 +795,7 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props) } const toggleLock = async () => { if (!track) return + if (refuseIfReadOnly()) return try { applyCueEdit(await api.setGridLock(track.id, !cueData?.grid_locked)) } catch (e) { @@ -784,6 +804,7 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props) } const deleteGrid = async () => { if (!track) return + if (refuseIfReadOnly()) return try { applyCueEdit(await api.deleteGrid(track.id)) } catch (e) { @@ -793,6 +814,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 setGridBusy(true) try { applyCueEdit(await api.autoGrid(track.id)) @@ -900,6 +922,17 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props)