Added Rekordbox capabilities handling

This commit is contained in:
patben8 committed 2026-09-18 09:36:05 +02:00
1 parent 4592e13228
commit 010f67cd2d
14 files changed
+266 -12

No files matched your search

+60
View File
@@ -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 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 unit-tested as the inverse of the read projection, so the grid write has a
starting point. 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.
+17 -2
View File
@@ -88,7 +88,7 @@ Two independent apps that talk over HTTP:
- `schemas.py` — HTTP request bodies + envelopes; re-exports `core.model`. - `schemas.py` — HTTP request bodies + envelopes; re-exports `core.model`.
- `main.py` — thin FastAPI routes (all under `/api`), talking only to the - `main.py` — thin FastAPI routes (all under `/api`), talking only to the
adapter. Starts **unloaded**; the library is chosen at runtime via 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 `GET /api/capabilities` feeds the UI's gating; `GET /api/fs/list` powers the
file browser; `GET`/`PATCH /api/prefs` persist UI prefs. Setting file browser; `GET`/`PATCH /api/prefs` persist UI prefs. Setting
`KONDUKTOR_NML` auto-loads on startup (dev/tests). `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 analysis + paint), `beatgrid.ts` (the marker-list beat math — every
beat/bar/snap/jump calculation goes through it), `cues.ts` (draw beat/bar/snap/jump calculation goes through it), `cues.ts` (draw
cues/loop/beatgrid/cue-point). See "Prep engine" below. 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 - Capability-gated today: hotcue bank size (`HotcueBar`, the auto-cue guard and
the digit shortcuts all read `cues.hotcue_slots`), the cue-type dropdown the digit shortcuts all read `cues.hotcue_slots`), the cue-type dropdown
(`cues.types`), the rating scale (`tracks.rating_max`), the grid Lock button (`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 exists: `slot_labels: 'letter'`, `palette`, `loops: 'separate_bank'`, and
memory-cue *editing* (one-platform features stay preserved-but-uneditable). memory-cue *editing* (one-platform features stay preserved-but-uneditable).
- `lib/trackColumns.tsx` — single source of truth for the library table's - `lib/trackColumns.tsx` — single source of truth for the library table's
@@ -37,9 +37,14 @@ HOTCUE_SLOTS = 8
def capabilities_for( def capabilities_for(
path, version: str | None = None, *, cloud_synced: bool = False path, version: str | None = None, *, cloud_synced: bool = False
) -> Capabilities: ) -> 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( return Capabilities(
platform="rekordbox", platform="rekordbox",
version=version, version=version,
writable=False,
readonly_cause="cloud_synced" if cloud_synced else "platform_incomplete",
cues=CueCapabilities( cues=CueCapabilities(
hotcue_slots=HOTCUE_SLOTS, hotcue_slots=HOTCUE_SLOTS,
slot_labels="letter", slot_labels="letter",
@@ -41,6 +41,7 @@ def capabilities_for(path: Path, editable_fields: list[str]) -> Capabilities:
return Capabilities( return Capabilities(
platform="traktor", platform="traktor",
version=nml_version(path), version=nml_version(path),
writable=True,
cues=CueCapabilities( cues=CueCapabilities(
hotcue_slots=8, hotcue_slots=8,
slot_labels="number", slot_labels="number",
+17
View File
@@ -15,6 +15,13 @@ from typing import Literal
from pydantic import BaseModel 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"] CueType = Literal["cue", "fade_in", "fade_out", "load", "loop"]
CueRole = Literal["hotcue", "memory"] CueRole = Literal["hotcue", "memory"]
MediaKind = Literal["audio", "stem", "video"] MediaKind = Literal["audio", "stem", "video"]
@@ -74,6 +81,16 @@ class SaveCapabilities(BaseModel):
class Capabilities(BaseModel): class Capabilities(BaseModel):
platform: str platform: str
version: str | None = None 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() cues: CueCapabilities = CueCapabilities()
grid: GridCapabilities = GridCapabilities() grid: GridCapabilities = GridCapabilities()
tracks: TrackCapabilities = TrackCapabilities() tracks: TrackCapabilities = TrackCapabilities()
+41
View File
@@ -195,6 +195,13 @@ with tempfile.TemporaryDirectory() as d:
print("== capabilities gate the UI ==") print("== capabilities gate the UI ==")
caps = adapter.capabilities() caps = adapter.capabilities()
check("platform is rekordbox", caps.platform == "rekordbox") 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", check("8 hot cue slots, labelled by letter",
caps.cues.hotcue_slots == 8 and caps.cues.slot_labels == "letter") caps.cues.hotcue_slots == 8 and caps.cues.slot_labels == "letter")
check("memory cues are supported", caps.cues.memory_cues) 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("every mutating command raises Unsupported", not refused, ", ".join(refused))
check("the adapter is never dirty while read-only", adapter.dirty is False) 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 ==") print("== reads that must still work ==")
page = adapter.query_tracks(limit=5) page = adapter.query_tracks(limit=5)
check("query_tracks paginates", len(page.items) <= 5 and page.total == len(adapter.tracks)) check("query_tracks paginates", len(page.items) <= 5 and page.total == len(adapter.tracks))
+2
View File
@@ -80,6 +80,8 @@ with tempfile.TemporaryDirectory() as d:
adapter = TraktorAdapter(work) adapter = TraktorAdapter(work)
caps = adapter.capabilities() caps = adapter.capabilities()
check("platform reported", caps.platform == "traktor") 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("version read from the NML header", caps.version == "20", str(caps.version))
check("8 hotcue slots", caps.cues.hotcue_slots == 8) check("8 hotcue slots", caps.cues.hotcue_slots == 8)
check("no memory cues on Traktor", caps.cues.memory_cues is False) check("no memory cues on Traktor", caps.cues.memory_cues is False)
+12 -4
View File
@@ -136,7 +136,11 @@ export default function App() {
}, []) }, [])
const onError = useCallback((msg: string) => notify('error', msg), [notify]) 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( const editField = useCallback(
(track: Track, field: keyof Track, value: string | number) => { (track: Track, field: keyof Track, value: string | number) => {
api api
@@ -265,7 +269,11 @@ export default function App() {
y={menu.y} y={menu.y}
items={[ items={[
{ label: 'Load to Deck', onClick: () => setPrepTrack(menu.track) }, { 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)} onClose={() => setMenu(null)}
/> />
@@ -348,7 +356,7 @@ export default function App() {
}} }}
onRowContextMenu={(track, x, y) => setMenu({ track, x, y })} onRowContextMenu={(track, x, y) => setMenu({ track, x, y })}
onPlay={playTrack} onPlay={playTrack}
onEditField={editField} onEditField={canEdit ? editField : undefined}
activeTrackId={prepTrack?.id ?? null} activeTrackId={prepTrack?.id ?? null}
columnVisibility={columnVisibility} columnVisibility={columnVisibility}
columnOrder={columnOrder} columnOrder={columnOrder}
@@ -374,7 +382,7 @@ export default function App() {
tracks={filtered} tracks={filtered}
onRowContextMenu={(track, x, y) => setMenu({ track, x, y })} onRowContextMenu={(track, x, y) => setMenu({ track, x, y })}
onPlay={playTrack} onPlay={playTrack}
onEditField={editField} onEditField={canEdit ? editField : undefined}
activeTrackId={prepTrack?.id ?? null} activeTrackId={prepTrack?.id ?? null}
columnVisibility={columnVisibility} columnVisibility={columnVisibility}
columnOrder={columnOrder} columnOrder={columnOrder}
+12
View File
@@ -168,9 +168,21 @@ export interface SaveCapabilities {
history: boolean 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 { export interface Capabilities {
platform: Platform platform: Platform
version: string | null 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 cues: CueCapabilities
grid: { editable: boolean; flexible: boolean; lockable: boolean } grid: { editable: boolean; flexible: boolean; lockable: boolean }
tracks: { tracks: {
+33
View File
@@ -4,6 +4,7 @@ import { api, type CueType, type GridMarker, type Track, type TrackCues } from '
import { buildBeatGrid, GRID_EPS } from '../lib/beatgrid' import { buildBeatGrid, GRID_EPS } from '../lib/beatgrid'
import { slotLabeller, useCaps } from '../lib/capabilities' import { slotLabeller, useCaps } from '../lib/capabilities'
import { CUE_TYPE_LABELS } from '../lib/cues' import { CUE_TYPE_LABELS } from '../lib/cues'
import { readOnlyShort, readOnlyNotice } from '../lib/platformCopy'
import { analyzeWaveform, type WaveColumn } from '../lib/waveform' import { analyzeWaveform, type WaveColumn } from '../lib/waveform'
import { ScratchEngine } from '../lib/scratchEngine' import { ScratchEngine } from '../lib/scratchEngine'
import { PlaybackEngine } from '../lib/playbackEngine' import { PlaybackEngine } from '../lib/playbackEngine'
@@ -562,6 +563,15 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props)
// ---- capability-derived ----------------------------------------------- // ---- capability-derived -----------------------------------------------
const caps = useCaps() 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 slotCount = caps.cues.hotcue_slots
const slotLabel = slotLabeller(caps) const slotLabel = slotLabeller(caps)
// Loops are a cue TYPE on some platforms and a separate bank on others; the // 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 return
} }
if (!cue) { if (!cue) {
if (refuseIfReadOnly()) return
try { try {
// Setting a hotcue while a loop is active stores it as a loop hotcue. // Setting a hotcue while a loop is active stores it as a loop hotcue.
if (loopActive && loopRegion) { if (loopActive && loopRegion) {
@@ -652,6 +663,7 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props)
const canAutoCue = grid != null const canAutoCue = grid != null
const runAutoHotcues = async () => { const runAutoHotcues = async () => {
if (!track || !canAutoCue || autoBusy) return if (!track || !canAutoCue || autoBusy) return
if (refuseIfReadOnly()) return
const hotcueCount = (c: TrackCues | null) => const hotcueCount = (c: TrackCues | null) =>
c?.cues.filter((x) => x.role === 'hotcue' && x.slot != null).length ?? 0 c?.cues.filter((x) => x.role === 'hotcue' && x.slot != null).length ?? 0
if (hotcueCount(cueData) >= slotCount) { if (hotcueCount(cueData) >= slotCount) {
@@ -678,6 +690,7 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props)
const changeSelectedType = async (type: CueType) => { const changeSelectedType = async (type: CueType) => {
if (!track || selectedSlot == null) return if (!track || selectedSlot == null) return
if (refuseIfReadOnly()) return
try { try {
applyCueEdit(await api.setCueType(track.id, selectedSlot, type)) applyCueEdit(await api.setCueType(track.id, selectedSlot, type))
} catch (e) { } catch (e) {
@@ -687,6 +700,7 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props)
const deleteSelected = async () => { const deleteSelected = async () => {
if (!track || selectedSlot == null) return if (!track || selectedSlot == null) return
if (refuseIfReadOnly()) return
try { try {
applyCueEdit(await api.deleteCue(track.id, selectedSlot)) applyCueEdit(await api.deleteCue(track.id, selectedSlot))
setSelectedSlot(null) setSelectedSlot(null)
@@ -699,6 +713,7 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props)
const existing = hotcueAt(slot) const existing = hotcueAt(slot)
if (!track || !existing) return // nothing to remove in an empty 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 (existing.grid_marker != null) return // beatgrid-owned: delete the marker instead
if (refuseIfReadOnly()) return
try { try {
applyCueEdit(await api.deleteCue(track.id, slot)) applyCueEdit(await api.deleteCue(track.id, slot))
if (selectedSlot === slot) setSelectedSlot(null) 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 }) => { const editMarker = async (index: number, patch: { bpm?: number; start?: number }) => {
if (!track || index < 0) return if (!track || index < 0) return
if (refuseIfReadOnly()) return
try { try {
applyCueEdit(await api.setGridMarker(track.id, index, patch)) applyCueEdit(await api.setGridMarker(track.id, index, patch))
} catch (e) { } 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. // Uses the raw playhead, not snapTime: a marker defines where beats are.
const addMarkerHere = async () => { const addMarkerHere = async () => {
if (!track) return if (!track) return
if (refuseIfReadOnly()) return
try { try {
applyCueEdit(await api.addGridMarker(track.id, playheadNow())) applyCueEdit(await api.addGridMarker(track.id, playheadNow()))
} catch (e) { } catch (e) {
@@ -752,6 +769,7 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props)
} }
const deleteMarkerHere = async () => { const deleteMarkerHere = async () => {
if (!track || activeMarkerIndex < 0) return if (!track || activeMarkerIndex < 0) return
if (refuseIfReadOnly()) return
try { try {
applyCueEdit(await api.deleteGridMarker(track.id, activeMarkerIndex)) applyCueEdit(await api.deleteGridMarker(track.id, activeMarkerIndex))
} catch (e) { } catch (e) {
@@ -768,6 +786,7 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props)
const resetGrid = async () => { const resetGrid = async () => {
const o = originalGridRef.current const o = originalGridRef.current
if (!track || !o) return if (!track || !o) return
if (refuseIfReadOnly()) return
try { try {
applyCueEdit(await api.replaceGridMarkers(track.id, o)) applyCueEdit(await api.replaceGridMarkers(track.id, o))
} catch (e) { } catch (e) {
@@ -776,6 +795,7 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props)
} }
const toggleLock = async () => { const toggleLock = async () => {
if (!track) return if (!track) return
if (refuseIfReadOnly()) return
try { try {
applyCueEdit(await api.setGridLock(track.id, !cueData?.grid_locked)) applyCueEdit(await api.setGridLock(track.id, !cueData?.grid_locked))
} catch (e) { } catch (e) {
@@ -784,6 +804,7 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props)
} }
const deleteGrid = async () => { const deleteGrid = async () => {
if (!track) return if (!track) return
if (refuseIfReadOnly()) return
try { try {
applyCueEdit(await api.deleteGrid(track.id)) applyCueEdit(await api.deleteGrid(track.id))
} catch (e) { } 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. // Analyze: backend detects BPM + first beat, sets the grid anchor and hotcue 1.
const runAnalyzeGrid = async () => { const runAnalyzeGrid = async () => {
if (!track || gridBusy) return if (!track || gridBusy) return
if (refuseIfReadOnly()) return
setGridBusy(true) setGridBusy(true)
try { try {
applyCueEdit(await api.autoGrid(track.id)) applyCueEdit(await api.autoGrid(track.id))
@@ -900,6 +922,17 @@ export function PrepStrip({ track, playRequest = 0, onError, onNotify }: Props)
<div className="truncate text-xs text-muted" title={track.artist ?? ''}> <div className="truncate text-xs text-muted" title={track.artist ?? ''}>
{track.artist ?? 'Unknown artist'} {track.artist ?? 'Unknown artist'}
</div> </div>
{/* The deck stays usable for listening on a read-only library, so
say which it is rather than leaving the edit controls looking
live. The controls themselves report the reason when pressed. */}
{readOnlyShort(caps) && (
<div
className="mt-1 inline-block rounded bg-ink-800 px-1.5 py-0.5 text-[10px] uppercase tracking-wider text-faint"
title={readOnlyNotice(caps) ?? ''}
>
{readOnlyShort(caps)}
</div>
)}
</> </>
) : ( ) : (
<div className="text-xs uppercase tracking-wider text-faint">No track loaded</div> <div className="text-xs uppercase tracking-wider text-faint">No track loaded</div>
+15 -1
View File
@@ -2,7 +2,7 @@ import { useState } from 'react'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { api } from '../api' import { api } from '../api'
import { useCaps } from '../lib/capabilities' import { useCaps } from '../lib/capabilities'
import { overwriteWarning, saveLabel } from '../lib/platformCopy' import { overwriteWarning, readOnlyNotice, saveLabel } from '../lib/platformCopy'
interface Props { interface Props {
onError: (msg: string) => void onError: (msg: string) => void
@@ -31,6 +31,20 @@ export function SaveBar({ onError }: Props) {
const caps = useCaps() const caps = useCaps()
const warning = overwriteWarning(caps.save) const warning = overwriteWarning(caps.save)
const dirty = state?.dirty ?? false const dirty = state?.dirty ?? false
const readOnly = readOnlyNotice(caps)
// A read-only library has no save to offer, and saying so plainly is the whole
// point: a greyed-out button with no explanation reads as a bug.
if (readOnly) {
return (
<div className="border-t border-line bg-ink-900 px-3 py-3">
<div className="rounded-md bg-ink-800 px-2 py-2 text-[11px] leading-snug text-faint">
<span className="font-medium text-ink-200">Read-only</span>
<div className="mt-1">{readOnly}</div>
</div>
</div>
)
}
return ( return (
<div className="border-t border-line bg-ink-900 px-3 py-3"> <div className="border-t border-line bg-ink-900 px-3 py-3">
+19 -4
View File
@@ -1,6 +1,7 @@
import { useState } from 'react' import { useState } from 'react'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { api, type PlaylistKind, type PlaylistNode } from '../api' import { api, type PlaylistKind, type PlaylistNode } from '../api'
import { useCaps } from '../lib/capabilities'
import { SaveBar } from './SaveBar' import { SaveBar } from './SaveBar'
export type Source = { kind: 'all' } | { kind: 'playlist'; id: string; name: string } export type Source = { kind: 'all' } | { kind: 'playlist'; id: string; name: string }
@@ -115,8 +116,10 @@ function NodeRow({
)} )}
</button> </button>
{node.can_rename && !renaming && ( {/* Each action gates on ITS OWN flag: a platform may allow renaming but
<> not deleting. The count shows either way — it is information, not an
action, and hiding it on a read-only library loses real data. */}
{!renaming && node.can_rename && (
<button <button
title="Rename" title="Rename"
onClick={() => { onClick={() => {
@@ -127,6 +130,8 @@ function NodeRow({
> >
✎ ✎
</button> </button>
)}
{!renaming && node.can_delete && (
<button <button
title="Delete playlist" title="Delete playlist"
onClick={() => { onClick={() => {
@@ -136,10 +141,15 @@ function NodeRow({
> >
× ×
</button> </button>
<span className="shrink-0 rounded bg-ink-800 px-1.5 py-0.5 text-[10px] tabular-nums text-faint group-hover:hidden"> )}
{!renaming && !isFolder && (
<span
className={`shrink-0 rounded bg-ink-800 px-1.5 py-0.5 text-[10px] tabular-nums text-faint ${
node.can_rename || node.can_delete ? 'group-hover:hidden' : ''
}`}
>
{node.count} {node.count}
</span> </span>
</>
)} )}
</div> </div>
{isFolder && open && node.children.length > 0 && ( {isFolder && open && node.children.length > 0 && (
@@ -162,6 +172,9 @@ function NodeRow({
export function Sidebar({ source, onSelect, onError, onOpenHistory }: Props) { export function Sidebar({ source, onSelect, onError, onOpenHistory }: Props) {
const qc = useQueryClient() const qc = useQueryClient()
// There is no per-node flag for "you may create a NEW playlist" — the node
// flags describe existing nodes — so this is the library-level gate.
const canCreate = useCaps().writable
const [creating, setCreating] = useState(false) const [creating, setCreating] = useState(false)
const [newName, setNewName] = useState('') const [newName, setNewName] = useState('')
const { data: playlists, isLoading } = useQuery({ const { data: playlists, isLoading } = useQuery({
@@ -205,6 +218,7 @@ export function Sidebar({ source, onSelect, onError, onOpenHistory }: Props) {
<span className="text-[10px] font-semibold uppercase tracking-wider text-faint"> <span className="text-[10px] font-semibold uppercase tracking-wider text-faint">
Playlists Playlists
</span> </span>
{canCreate && (
<button <button
title="New playlist" title="New playlist"
onClick={() => { onClick={() => {
@@ -215,6 +229,7 @@ export function Sidebar({ source, onSelect, onError, onOpenHistory }: Props) {
> >
+ +
</button> </button>
)}
</div> </div>
<div className="mt-1 flex-1 overflow-y-auto px-2 pb-4"> <div className="mt-1 flex-1 overflow-y-auto px-2 pb-4">
+6
View File
@@ -30,3 +30,9 @@ export function slotLabeller(caps: Capabilities): (slot: number) => string {
? (slot) => String.fromCharCode(65 + slot) ? (slot) => String.fromCharCode(65 + slot)
: (slot) => String(slot + 1) : (slot) => String(slot + 1)
} }
/** Whether the loaded library accepts edits at all. Gate every edit affordance
* on this in addition to the relevant per-feature capability. */
export function useWritable(): boolean {
return useCaps().writable
}
+26 -1
View File
@@ -6,7 +6,7 @@
* staying genuinely specific — the pre-save warning is a real, per-platform * staying genuinely specific — the pre-save warning is a real, per-platform
* hazard and must not be watered down into something vague. * hazard and must not be watered down into something vague.
*/ */
import type { SaveCapabilities } from '../api' import type { Capabilities, SaveCapabilities } from '../api'
export function saveLabel(save: SaveCapabilities): string { export function saveLabel(save: SaveCapabilities): string {
return `Save to ${save.app_name}` return `Save to ${save.app_name}`
@@ -39,3 +39,28 @@ export function restoreWarning(save: SaveCapabilities): string | null {
export function writeHint(save: SaveCapabilities): string { export function writeHint(save: SaveCapabilities): string {
return `Save to ${save.app_name} to write it to disk` return `Save to ${save.app_name} to write it to disk`
} }
/**
* Why this library is read-only, or null when it is editable.
*
* The two causes need genuinely different wording: a missing feature is a gap
* the user should expect Konduktor to close, whereas a cloud-synced library is
* a deliberate, permanent refusal that protects their other machines — and a
* user told only "read-only" would reasonably file the second as a bug.
*/
export function readOnlyNotice(caps: Capabilities): string | null {
if (caps.writable) return null
switch (caps.readonly_cause) {
case 'cloud_synced':
return `This ${caps.save.app_name} library is synced with ${caps.save.app_name} Cloud, so Konduktor will not write to it — an edit it did not make could break syncing on your other devices.`
case 'platform_incomplete':
default:
return `Konduktor can read ${caps.save.app_name} libraries but cannot save changes to them yet.`
}
}
/** Compact form for a badge or a disabled control's tooltip. */
export function readOnlyShort(caps: Capabilities): string | null {
if (caps.writable) return null
return caps.readonly_cause === 'cloud_synced' ? 'Read-only · cloud-synced' : 'Read-only'
}