diff --git a/CLAUDE.md b/CLAUDE.md index c7f1079..69cc0f3 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -168,7 +168,8 @@ Two independent apps that talk over HTTP: 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. - `prefs.py` — persisted user prefs (`userprefs.json` in the per-OS app-data - dir). Last-opened collection, library column layout, prep-deck zoom. Best-effort. + dir). Last-opened collection (global AND per-platform), library column + layout, prep-deck zoom, import destination. Best-effort. - `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 @@ -176,6 +177,17 @@ Two independent apps that talk over HTTP: `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). + The picker's three routes are all **scoped by `?platform=`**, because it + asks which platform first: `/api/platforms` (the pre-load equivalent of + capabilities — reports `selects`, `removable` and `found`, sorted so a menu + does not reshuffle between launches), `/api/library/options` (that + platform's detections + its own last-opened) and `/api/fs/list` (that + platform's suffixes; a directory-selecting platform contributes none, so its + browse shows folders only). `/api/library/open` checks `exists()`, **not + `is_file()`** — which shapes are valid is `can_open()`'s business, and a + OneLibrary library is a drive. `prefs` keeps last-opened **per platform**: + offering a Rekordbox `master.db` to someone who just chose Traktor is an + offer that cannot be taken. - **`frontend/`** — React + TypeScript + Vite. A dark, virtualized track explorer. Entry: [frontend/src/App.tsx](frontend/src/App.tsx). - `api.ts` — typed client + all API types. **Generic, not Traktor-shaped**: @@ -192,8 +204,21 @@ Two independent apps that talk over HTTP: adapter supplies (`app_name`, `library_label`, `overwrite_risk`), so "Close Traktor before saving — it overwrites collection.nml on exit" stays specific without being hard-coded. Never put finished sentences in the API. - - `components/` — `CollectionPicker` (startup chooser: Automatic / Open last / - Find manually — the last reveals a file browser), `Sidebar` (playlist tree + + - `components/` — `CollectionPicker` (**two steps: which PLATFORM, then which + library** — Automatic / Open last / Find manually, the last revealing a file + browser. The platform comes first because every later answer depends on it: + asked the other way round, "Automatic" had to guess ACROSS platforms and did + it by adapter registration order, so a plugged-in stick could be opened as + the user's collection. Scoping removes that by construction rather than by + ranking candidates better. Nothing is remembered between launches — the + platform list is where every session starts. `selects` decides whether the + browser offers files or a folder to confirm, because a library is a file on + some platforms and a DIRECTORY on others), `Sidebar` (a header naming the + open library, which is also the only way to switch to another one — the + picker used to be a one-way door with `forcePicker` never set, so changing + library meant restarting; switching confirms first when there are unsaved + edits, since the adapter holds them in a native model that opening another + library replaces — plus the playlist tree + create/rename/delete), `SaveBar`, `Toolbar` (search/filters + `ColumnsMenu`), `TrackTable` (All Tracks — TanStack Table + **virtualized** grid; per-row play button, configurable columns, inline double-click editing) and `PlaylistTable` @@ -323,6 +348,14 @@ serialization path.** It enforces: companion cue is invented), that the existing 8,485 entries render byte-identically, that the job registry runs/fails/cancels, and that a cancelled import leaves **no orphaned audio and an untouched collection**. +- `test_picker.py` — the picker's routes. Pins the scoping, because the bug it + replaced was invisible: `/api/library/options` flattened every driver's + detections and returned `[0]`, so a plugged-in USB stick could be offered as + the user's collection and nothing failed — it just opened the wrong library. + Also pins that a drive is named the same whichever of its two valid paths was + opened. Needs nothing installed: every assertion is about the SHAPE of the + answer, and prefs are redirected to a temp file so a test can never rewrite + the user's last-opened library. - `test_layering.py` — `core/` imports nothing platform-specific, and no adapter imports another platform's library (checked on real imports via AST, so merely naming a platform in a comment is fine). Rekordbox and OneLibrary deliberately diff --git a/backend/konduktor/adapters/onelibrary/driver.py b/backend/konduktor/adapters/onelibrary/driver.py index ad16ebe..df216b6 100644 --- a/backend/konduktor/adapters/onelibrary/driver.py +++ b/backend/konduktor/adapters/onelibrary/driver.py @@ -21,6 +21,11 @@ class OneLibraryDriver: removable = True suffixes = (".db",) library_label = "exportLibrary.db" + # What a user PICKS is the mount point, not the database buried three levels + # down inside it — `DriveLayout.locate()` accepts either, but only one of + # them is a thing anybody browses to. The file browser reads this to offer + # folders rather than files. + selects = "directory" def can_open(self, path: Path) -> bool: """Recognise a OneLibrary drive, by layout and then by schema. @@ -77,6 +82,17 @@ class OneLibraryDriver: def describe(self, path: Path) -> dict: return discovery.describe(path) + def display_name_for(self, path: Path) -> str: + """What to call this library on screen: the DRIVE's name. + + The filename is not a stable answer here. A OneLibrary library can be + opened by its mount point OR by the database three levels inside it — + `DriveLayout.locate()` accepts both on purpose — so the same stick would + be "Hardy" opened one way and "exportLibrary.db" opened the other. + """ + layout = DriveLayout.locate(Path(path)) + return layout.root.name if layout is not None else Path(path).name + def restore(self, path: Path, data: bytes) -> None: """Not supported: a drive is a database plus analysis files plus audio. diff --git a/backend/konduktor/adapters/rekordbox/driver.py b/backend/konduktor/adapters/rekordbox/driver.py index f58ffa3..f6040b0 100644 --- a/backend/konduktor/adapters/rekordbox/driver.py +++ b/backend/konduktor/adapters/rekordbox/driver.py @@ -17,6 +17,7 @@ class RekordboxDriver: display_name = "Rekordbox" suffixes = (".db",) library_label = "master.db" + selects = "file" def can_open(self, path: Path) -> bool: """Recognise an encrypted Rekordbox database. diff --git a/backend/konduktor/adapters/traktor/driver.py b/backend/konduktor/adapters/traktor/driver.py index 27bbd78..413a6c8 100644 --- a/backend/konduktor/adapters/traktor/driver.py +++ b/backend/konduktor/adapters/traktor/driver.py @@ -12,6 +12,7 @@ class TraktorDriver: display_name = "Traktor" suffixes = (".nml",) library_label = "collection.nml" + selects = "file" def can_open(self, path: Path) -> bool: """Recognise an NML without parsing 14 MB of it.""" diff --git a/backend/konduktor/core/adapter.py b/backend/konduktor/core/adapter.py index c963eab..4bdfe55 100644 --- a/backend/konduktor/core/adapter.py +++ b/backend/konduktor/core/adapter.py @@ -192,8 +192,19 @@ class LibraryDriver(Protocol): # can offer them as import SOURCES. Optional, and False for a platform that # does not set it, because most keep one library in a known place. removable: bool + # Whether a user picks a FILE or a DIRECTORY for this platform. Both exist: + # Traktor's library is `collection.nml`, OneLibrary's is the drive, and + # Serato's will be a `_Serato_` folder. The file browser and the open route + # both read this rather than assuming everything is a file. Defaults to + # "file" for a driver that does not set it. + selects: str def can_open(self, path: Path) -> bool: ... def open(self, path: Path) -> LibraryAdapter: ... + # OPTIONAL. What to call an opened library on screen. Only the adapter can + # answer for a platform where one library has more than one valid path — + # the filename is otherwise assumed, and that assumption is wrong for a + # library that is a drive. Omitted means "the path's own name". + def display_name_for(self, path: Path) -> str: ... def detect(self) -> list: ... def describe(self, path: Path) -> object: ... diff --git a/backend/konduktor/core/model.py b/backend/konduktor/core/model.py index 854486e..ea90066 100644 --- a/backend/konduktor/core/model.py +++ b/backend/konduktor/core/model.py @@ -177,13 +177,23 @@ class LibraryInfo(BaseModel): class PlatformOption(BaseModel): - """A platform the picker can offer before any library is open.""" + """A platform the picker can offer before any library is open. + + Facts only, never finished sentences: `lib/platformCopy.ts` composes the + wording. The distinction that matters is `removable` — a platform with no + library found is "not installed" for Traktor and "nothing plugged in" for + OneLibrary, and only the driver knows which of those is true. + """ platform: str name: str library_label: str selects: Literal["file", "directory"] = "file" installed: bool = False + #: How many libraries this platform has right now; `installed` is `found > 0`. + found: int = 0 + #: The library lives on a plugged-in drive, so `found` changes between calls. + removable: bool = False class RemapSample(BaseModel): diff --git a/backend/konduktor/core/registry.py b/backend/konduktor/core/registry.py index dc5b6fa..4105d8b 100644 --- a/backend/konduktor/core/registry.py +++ b/backend/konduktor/core/registry.py @@ -25,6 +25,14 @@ def drivers() -> list[LibraryDriver]: return list(_DRIVERS) +def driver_by_platform(platform: str) -> LibraryDriver: + """The driver for a platform name, e.g. ``"traktor"``.""" + for d in _DRIVERS: + if d.platform == platform: + return d + raise LibraryNotSupported(f"No adapter registered for platform {platform!r}") + + def driver_for(path: Path) -> LibraryDriver: """The first registered driver that recognises `path`.""" for d in _DRIVERS: @@ -64,6 +72,21 @@ def describe(path: Path) -> dict: } +def detect_for(platform: str) -> list: + """Every library one platform has right now, best first. + + The picker asks which platform FIRST, so detection is scoped to the answer. + Unscoped detection (``detect_all``) concatenates drivers in registration + order, which made "the best candidate" mean "whatever the first-registered + driver found" — with a removable drive registered first, a plugged-in stick + could be offered as the user's collection. + """ + try: + return driver_by_platform(platform).detect() + except (LibraryNotSupported, OSError): + return [] + + def detect_all() -> list: """Every library found in the platforms' default install locations.""" out: list = [] @@ -75,10 +98,21 @@ def detect_all() -> list: return out -def browsable_suffixes() -> tuple[str, ...]: - """File extensions the in-app browser should show, across all platforms.""" +def browsable_suffixes(platform: str | None = None) -> tuple[str, ...]: + """File extensions the in-app browser should show, for one platform or all. + + A platform that selects a DIRECTORY contributes nothing, even though it has + suffixes: its libraries are not the thing a user picks, so listing them + would offer a file the browser's Open cannot act on. + """ + try: + targets = [driver_by_platform(platform)] if platform else _DRIVERS + except LibraryNotSupported: + targets = [] seen: list[str] = [] - for d in _DRIVERS: + for d in targets: + if getattr(d, "selects", "file") != "file": + continue for suffix in d.suffixes: if suffix not in seen: seen.append(suffix) diff --git a/backend/konduktor/main.py b/backend/konduktor/main.py index 7b37600..13c06cc 100644 --- a/backend/konduktor/main.py +++ b/backend/konduktor/main.py @@ -129,29 +129,46 @@ def collection_status() -> CollectionStatus: @app.post("/api/library/open", response_model=CollectionStatus) def open_collection(body: OpenCollection) -> CollectionStatus: path = Path(body.path).expanduser() - if not path.exists() or not path.is_file(): - raise HTTPException(400, f"File not found: {path}") + # Deliberately NOT `is_file()`. A library is a file on some platforms and a + # DIRECTORY on others — OneLibrary's is the drive, Serato's will be a + # `_Serato_` folder — and which shapes are valid is the driver's business. + # This checks only that the path is there at all; `can_open()` decides. + if not path.exists(): + raise HTTPException(400, f"Not found: {path}") try: STATE.open(path) except AdapterError as ex: raise HTTPException(400, f"Not a valid collection: {ex}") except Exception as ex: # noqa: BLE001 raise HTTPException(400, f"Could not open that collection: {ex}") - prefs.set_last_collection(str(path)) + prefs.set_last_collection(str(path), require_adapter().capabilities().platform) return collection_status() @app.get("/api/library/options", response_model=CollectionOptions) -def collection_options() -> CollectionOptions: - """Startup shortcuts for the picker: the best auto-detected Traktor - collection and the last one opened (may no longer exist → exists=False).""" - detected = registry.detect_all() - auto = CollectionCandidate(**detected[0]) if detected else None +def collection_options(platform: str | None = None) -> CollectionOptions: + """Startup shortcuts for the picker, scoped to one platform. + + Scoped because the picker asks which platform first, and both shortcuts are + only meaningful inside that answer: unscoped, "auto" meant "whatever the + first-registered driver happened to find" — so a plugged-in USB stick could + be offered as the user's collection — and "last opened" could name a library + of the platform they had just declined. + + `recent` may no longer exist (→ `exists=False`), which the picker shows + rather than hides: a library that has moved is worth saying so about. + """ + detected = registry.detect_for(platform) if platform else registry.detect_all() + candidates = [CollectionCandidate(**d) for d in detected] recent = None - last = prefs.get_last_collection() + last = prefs.get_last_collection(platform) if last: recent = CollectionCandidate(**registry.describe(Path(last))) - return CollectionOptions(auto=auto, recent=recent) + return CollectionOptions( + auto=candidates[0] if candidates else None, + detected=candidates, + recent=recent, + ) @app.get("/api/library/path-mapping", response_model=PathMappingInfo) @@ -229,12 +246,19 @@ def patch_prefs(patch: dict) -> dict: @app.get("/api/fs/list", response_model=FsListing) -def fs_list(path: str | None = None) -> FsListing: - """List directories and .nml files for the in-app file browser.""" +def fs_list(path: str | None = None, platform: str | None = None) -> FsListing: + """List directories and openable library files for the in-app file browser. + + `platform` narrows the files to that platform's own: a Traktor browse that + also listed `master.db` would be offering a file the chosen adapter cannot + open. A platform whose library is a directory contributes no suffixes at + all, so its browse shows folders only. + """ base = Path(path).expanduser() if path else Path.home() if not base.exists() or not base.is_dir(): base = Path.home() base = base.resolve() + suffixes = registry.browsable_suffixes(platform) dirs: list[FsEntry] = [] files: list[FsEntry] = [] try: @@ -244,7 +268,7 @@ def fs_list(path: str | None = None) -> FsListing: try: if entry.is_dir(): dirs.append(FsEntry(name=entry.name, path=str(entry))) - elif entry.suffix.lower() in registry.browsable_suffixes(): + elif entry.suffix.lower() in suffixes: files.append(FsEntry(name=entry.name, path=str(entry))) except OSError: continue @@ -267,12 +291,22 @@ def health() -> dict: def _library_info() -> LibraryInfo: """Identity of the loaded library, for display and for composing warnings.""" caps = require_adapter().capabilities() + path = Path(str(STATE.path)) + # A library's on-screen name is the driver's to give when it cares: a drive + # has one library reachable by two valid paths, and the filename would name + # it differently depending on which one the user happened to pick. + driver = next((d for d in registry.drivers() if d.platform == caps.platform), None) + namer = getattr(driver, "display_name_for", None) + try: + display_name = namer(path) if namer else path.name + except OSError: + display_name = path.name return LibraryInfo( platform=caps.platform, name=caps.save.app_name, library_label=caps.save.library_label, path=str(STATE.path), - display_name=Path(str(STATE.path)).name, + display_name=display_name, version=caps.version, ) @@ -293,10 +327,17 @@ def platforms() -> list[PlatformOption]: platform=d.platform, name=d.display_name, library_label=getattr(d, "library_label", ""), - selects="file", + selects=getattr(d, "selects", "file"), installed=bool(found), + found=len(found), + removable=bool(getattr(d, "removable", False)), ) ) + # Registration order is an import-order accident, and this list is a MENU — + # it must not reshuffle itself between two launches. Sorted so the platforms + # that keep a library in a known place come before the ones that are a + # plugged-in drive, which is the real distinction a chooser is making. + out.sort(key=lambda o: (o.removable, o.name.lower())) return out diff --git a/backend/konduktor/prefs.py b/backend/konduktor/prefs.py index 5981ec0..f7d70aa 100644 --- a/backend/konduktor/prefs.py +++ b/backend/konduktor/prefs.py @@ -81,12 +81,36 @@ def set_path_mapping( save_prefs(prefs) -def get_last_collection() -> str | None: - val = load_prefs().get("last_collection") +def get_last_collection(platform: str | None = None) -> str | None: + """The last library opened — overall, or on one platform. + + Per-platform because the picker asks which platform FIRST: offering a + Rekordbox ``master.db`` under "Open last" to someone who just chose Traktor + is an offer that cannot be taken. A platform with no record returns None + rather than falling back to the global one, for the same reason. + + The flat ``last_collection`` stays: it is the global answer, and it is what + libraries opened before this existed are recorded in. + """ + prefs = load_prefs() + if platform: + by_platform = prefs.get("last_collection_by_platform") + if isinstance(by_platform, dict): + val = by_platform.get(platform) + return val if isinstance(val, str) else None + return None + val = prefs.get("last_collection") return val if isinstance(val, str) else None -def set_last_collection(path: str) -> None: +def set_last_collection(path: str, platform: str | None = None) -> None: + """Record a library as the last opened, globally and for its platform.""" prefs = load_prefs() prefs["last_collection"] = path + if platform: + by_platform = prefs.get("last_collection_by_platform") + if not isinstance(by_platform, dict): + by_platform = {} + by_platform[platform] = path + prefs["last_collection_by_platform"] = by_platform save_prefs(prefs) diff --git a/backend/konduktor/schemas.py b/backend/konduktor/schemas.py index f2f3f79..8c31f6a 100644 --- a/backend/konduktor/schemas.py +++ b/backend/konduktor/schemas.py @@ -126,6 +126,12 @@ class CollectionCandidate(BaseModel): class CollectionOptions(BaseModel): auto: CollectionCandidate | None = None # best auto-detected (latest version) + # EVERY library detected, best first. `auto` is simply the first of these. + # Carried in full because one platform can genuinely have several at once — + # two Traktor versions installed, or two sticks plugged in — and silently + # anointing one of them is how the old single-candidate route could open a + # USB drive as the user's collection. + detected: list[CollectionCandidate] = [] recent: CollectionCandidate | None = None # last opened (from userprefs) diff --git a/backend/run_tests.sh b/backend/run_tests.sh index d4d3f50..4a1fedb 100755 --- a/backend/run_tests.sh +++ b/backend/run_tests.sh @@ -6,7 +6,7 @@ cd "$(dirname "${BASH_SOURCE[0]}")" source .venv/bin/activate fail=0 -for t in test_layering.py test_save_fidelity.py test_traktor_adapter.py test_rekordbox_adapter.py test_rekordbox_fidelity.py test_onelibrary_adapter.py test_import.py test_phase3.py test_history.py; do +for t in test_layering.py test_save_fidelity.py test_traktor_adapter.py test_rekordbox_adapter.py test_rekordbox_fidelity.py test_onelibrary_adapter.py test_import.py test_picker.py test_phase3.py test_history.py; do echo "──────────────────────────────────────────" echo "▶ $t" echo "──────────────────────────────────────────" diff --git a/backend/test_picker.py b/backend/test_picker.py new file mode 100644 index 0000000..e506f0d --- /dev/null +++ b/backend/test_picker.py @@ -0,0 +1,147 @@ +"""The library picker's routes: platform first, then library. + +Worth pinning because the bug this flow replaced was invisible. `/api/library/ +options` used to flatten every driver's detections and return `[0]`, so "the +best candidate" actually meant "whatever the first-registered driver found" — +and since adapters register in import order, a plugged-in USB stick could be +offered as the user's *collection*. Nothing failed; it just opened the wrong +library. The guarantee now is scoping, and scoping is easy to lose again the +next time a route grows a shortcut. + +Runs on whatever this machine has: every assertion is about the SHAPE of the +answer, so a laptop with no Traktor, no Rekordbox and nothing plugged in still +exercises the same rules. Prefs are redirected to a temp file — a test must +never rewrite the user's last-opened library. +""" +import tempfile +from pathlib import Path + +from konduktor import prefs + +# Redirect prefs BEFORE anything reads them. +_TMP = tempfile.TemporaryDirectory() +prefs._PREFS_PATH = Path(_TMP.name) / "userprefs.json" +prefs._LEGACY_PREFS_PATH = Path(_TMP.name) / "absent.json" + +from konduktor.core import registry # noqa: E402 +from konduktor.main import collection_options, fs_list, platforms # 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 + + +opts = platforms() +by_name = {p.platform: p for p in opts} + +print("== /api/platforms reports the facts the platform step needs ==") +check("every registered driver is offered", len(opts) == len(registry.drivers()), + f"{len(opts)} of {len(registry.drivers())}") +check("all three platforms present", {"traktor", "rekordbox", "onelibrary"} <= set(by_name)) +check("selects is per-platform, not assumed", + by_name["traktor"].selects == "file" + and by_name["rekordbox"].selects == "file" + # A OneLibrary library is the DRIVE. Getting this wrong sends the browser + # hunting for a file three levels down that nobody would navigate to. + and by_name["onelibrary"].selects == "directory", + {p: by_name[p].selects for p in by_name}) +check("only OneLibrary is removable", + by_name["onelibrary"].removable + and not by_name["traktor"].removable + and not by_name["rekordbox"].removable) +check("installed agrees with found", all((p.found > 0) == p.installed for p in opts)) +# The list is a MENU. Registration order is an import-order accident, so sorting +# is what stops it reshuffling between two launches. +check("ordered fixed-location first, then by name", + [p.platform for p in opts] == [p.platform for p in + sorted(opts, key=lambda o: (o.removable, o.name.lower()))], + [p.platform for p in opts]) +check("a second call gives the same order", [p.platform for p in platforms()] == [p.platform for p in opts]) + +print("== /api/library/options is scoped to ONE platform ==") +for plat in ("traktor", "rekordbox", "onelibrary"): + o = collection_options(plat) + driver = registry.driver_by_platform(plat) + own = {c["path"] for c in registry.detect_for(plat)} + got = {c.path for c in o.detected} + check(f"{plat}: detected is exactly that platform's own", got == own, f"{got} vs {own}") + check(f"{plat}: auto is the first detected", + (o.auto.path if o.auto else None) == (o.detected[0].path if o.detected else None)) + # The old bug, stated directly: nothing removable may surface under a + # platform that keeps its library in a fixed place. + if not getattr(driver, "removable", False): + removable_paths = {c["path"] for d in registry.drivers() + if getattr(d, "removable", False) for c in d.detect()} + check(f"{plat}: no removable drive leaks in", not (got & removable_paths)) + +check("unscoped still answers (nothing depends on it, but it must not raise)", + collection_options() is not None) +check("an unknown platform detects nothing rather than raising", + collection_options("nonesuch").detected == []) + +print("== per-platform 'open last' does not cross platforms ==") +prefs.set_last_collection("/tmp/a/collection.nml", "traktor") +prefs.set_last_collection("/tmp/b/master.db", "rekordbox") +check("traktor remembers its own", prefs.get_last_collection("traktor") == "/tmp/a/collection.nml") +check("rekordbox remembers its own", prefs.get_last_collection("rekordbox") == "/tmp/b/master.db") +# Offering a Rekordbox master.db to someone who just chose Traktor is an offer +# that cannot be taken, so an unknown platform gets None, NOT the global value. +check("a platform with no record gets None, not the global one", + prefs.get_last_collection("onelibrary") is None + and prefs.get_last_collection() == "/tmp/b/master.db") +check("the picker surfaces it as `recent`", + (collection_options("traktor").recent or None) is not None + and collection_options("traktor").recent.path == "/tmp/a/collection.nml") +check("a remembered library that has gone is offered as exists=False", + collection_options("traktor").recent.exists is False) + +print("== /api/fs/list only lists what the chosen platform can open ==") +root = Path(tempfile.mkdtemp()) +(root / "collection.nml").write_text("x") +(root / "master.db").write_bytes(b"x") +(root / "notes.txt").write_text("x") +(root / "SomeDrive").mkdir() + +names = lambda plat: {f.name for f in fs_list(str(root), plat).files} # noqa: E731 +check("traktor sees only .nml", names("traktor") == {"collection.nml"}, names("traktor")) +check("rekordbox sees only .db", names("rekordbox") == {"master.db"}, names("rekordbox")) +# Not "the .db files it might contain": its library is a folder, so listing any +# file would offer something the Open action cannot act on. +check("onelibrary, which picks a folder, sees no files at all", names("onelibrary") == set()) +check("unscoped still sees the union", names(None) == {"collection.nml", "master.db"}) +check("never the unopenable", all("notes.txt" not in names(p) + for p in (None, "traktor", "rekordbox", "onelibrary"))) +check("folders are listed for every platform", + all({d.name for d in fs_list(str(root), p).dirs} == {"SomeDrive"} + for p in (None, "traktor", "rekordbox", "onelibrary"))) + +print("== a library may be a DIRECTORY, not just a file ==") +drives = registry.detect_for("onelibrary") +if drives: + # `describe()` returns the database, but the drive root is what a user picks + # in the browser. Both must name the same library or the picker and the + # last-opened shortcut would disagree about what is valid. + db = Path(drives[0]["path"]) + root_dir = db.parent.parent.parent + driver = registry.driver_by_platform("onelibrary") + check("the mount point opens", driver.can_open(root_dir), str(root_dir)) + check("so does the database it points at", driver.can_open(db)) + # ...and both must be CALLED the same thing. The sidebar names the open + # library, and a filename would call one stick two different names purely + # by which end of it the user happened to click. + check("both ends of the drive give one display name", + driver.display_name_for(root_dir) == driver.display_name_for(db) == root_dir.name, + f"{driver.display_name_for(root_dir)!r} vs {driver.display_name_for(db)!r}") + check("a path that is not a drive falls back to its own name", + driver.display_name_for(Path("/nope/whatever.db")) == "whatever.db") +else: + print(" [SKIP] no OneLibrary drive connected") + +print("\n" + ("❌ FAILED" if failed else "✅ PASSED")) +_TMP.cleanup() +raise SystemExit(1 if failed else 0) diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 6070fe1..5b4c6dd 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -397,6 +397,7 @@ export default function App() { onError={onError} onOpenHistory={() => setShowHistory(true)} onImport={() => setImporting(true)} + onSwitchLibrary={() => setForcePicker(true)} /> diff --git a/frontend/src/api.ts b/frontend/src/api.ts index bf07b0b..22340b5 100644 --- a/frontend/src/api.ts +++ b/frontend/src/api.ts @@ -212,8 +212,14 @@ export interface PlatformOption { platform: Platform name: string library_label: string + /** Whether picking this platform's library means picking a file or a folder. */ selects: 'file' | 'directory' installed: boolean + /** How many libraries this platform has right now; `installed` is `found > 0`. */ + found: number + /** The library lives on plugged-in media, so `found` changes between calls — + * and `found === 0` means "nothing plugged in", not "not installed". */ + removable: boolean } export interface EditState { @@ -238,7 +244,11 @@ export interface CollectionCandidate { } export interface CollectionOptions { - auto: CollectionCandidate | null // best auto-detected (latest Traktor version) + auto: CollectionCandidate | null // best auto-detected; the first of `detected` + /** EVERY library detected for the platform, best first. One platform can + * genuinely have several at once — two Traktor versions, two sticks — and + * the picker offers the choice rather than anointing one. */ + detected: CollectionCandidate[] recent: CollectionCandidate | null // last opened (may no longer exist) } @@ -416,9 +426,12 @@ export const api = { collection: () => getJSON('/api/library'), openCollection: (path: string) => send('POST', '/api/library/open', { path }), - collectionOptions: () => getJSON('/api/library/options'), - listDir: (path?: string) => - getJSON(`/api/fs/list${path ? `?path=${encodeURIComponent(path)}` : ''}`), + // Both take the chosen platform, because the picker asks for it FIRST: the + // shortcuts and the browsable files are only meaningful inside that answer. + collectionOptions: (platform?: string) => + getJSON(`/api/library/options${qs({ platform })}`), + listDir: (path?: string, platform?: string) => + getJSON(`/api/fs/list${qs({ path, platform })}`), // ---- path remapping (per-collection OS-path prefix translation) ---- getPathMapping: () => getJSON('/api/library/path-mapping'), diff --git a/frontend/src/components/CollectionPicker.tsx b/frontend/src/components/CollectionPicker.tsx index 22686c6..718edb3 100644 --- a/frontend/src/components/CollectionPicker.tsx +++ b/frontend/src/components/CollectionPicker.tsx @@ -1,10 +1,27 @@ import { useState } from 'react' import { useMutation, useQuery } from '@tanstack/react-query' -import { api, type CollectionStatus } from '../api' +import { api, type CollectionCandidate, type CollectionStatus, type PlatformOption } from '../api' +import { browsePrompt, platformAvailability } from '../lib/platformCopy' + +/** + * Choose a library to open, in two steps: WHICH PLATFORM, then which library. + * + * The platform comes first because it is the question every later answer + * depends on. Asked the other way round — one flat list of everything found — + * "Automatic" had to guess across platforms, and it guessed by adapter + * REGISTRATION ORDER: a plugged-in USB stick could be offered as the user's + * collection because its driver happened to be imported first. Scoping the + * shortcuts to a chosen platform removes that class of mistake by construction + * rather than by ranking candidates more cleverly. + * + * Nothing is remembered between launches. The platform list is where every + * session starts, so the choice is always visible and never inherited from a + * decision made days ago. + */ interface Props { onOpened: (status: CollectionStatus) => void - onCancel?: () => void // shown only when switching from an already-loaded collection + onCancel?: () => void // shown only when switching from an already-loaded library } function formatWhen(sec: number | null): string { @@ -47,22 +64,25 @@ function OptionCard({ } export function CollectionPicker({ onOpened, onCancel }: Props) { - const [mode, setMode] = useState<'choose' | 'browse'>('choose') + const [step, setStep] = useState<'platform' | 'library' | 'browse'>('platform') + const [platform, setPlatform] = useState(null) const [dir, setDir] = useState(undefined) // undefined => home const [manual, setManual] = useState('') - const options = useQuery({ queryKey: ['collectionOptions'], queryFn: api.collectionOptions }) // The picker runs BEFORE a library is open, so capabilities do not exist yet — - // /api/platforms is the pre-load equivalent. - const { data: platforms } = useQuery({ queryKey: ['platforms'], queryFn: api.platforms }) - // One platform today, so name it; with more, stay general rather than listing. - const only = platforms?.length === 1 ? platforms[0] : null - const appName = only?.name ?? 'DJ' - const fileLabel = only?.library_label ?? 'library file' + // /api/platforms is the pre-load equivalent, and it is the whole of step one. + const platforms = useQuery({ queryKey: ['platforms'], queryFn: api.platforms }) + + const options = useQuery({ + queryKey: ['collectionOptions', platform?.platform], + queryFn: () => api.collectionOptions(platform!.platform), + enabled: !!platform, + }) + const listing = useQuery({ - queryKey: ['fs', dir ?? '~'], - queryFn: () => api.listDir(dir), - enabled: mode === 'browse', + queryKey: ['fs', dir ?? '~', platform?.platform], + queryFn: () => api.listDir(dir, platform?.platform), + enabled: step === 'browse', }) const open = useMutation({ @@ -75,30 +95,59 @@ export function CollectionPicker({ onOpened, onCancel }: Props) { const auto = opt?.auto ?? null const recent = opt?.recent ?? null const recentAvailable = !!recent && recent.exists + // `auto` is the first of these, so the rest are the ones a single "Automatic" + // card would have thrown away. Two Traktor versions, or two sticks, is normal. + const alsoFound = (opt?.detected ?? []).slice(1) + // A drive is not a file: its browse lists folders and confirms the one you are + // standing in, the way the import folder picker does. + const picksDirectory = platform?.selects === 'directory' + + const goPlatform = () => { + setStep('platform') + setPlatform(null) + setDir(undefined) + setManual('') + open.reset() + } + + const subtitle = + step === 'platform' + ? 'Konduktor opens libraries from each of these.' + : step === 'library' + ? 'Open automatically, resume your last one, or browse.' + : platform + ? browsePrompt(platform) + : '' + + const openError = open.isError ? (open.error as Error).message : null return (
{/* Header */}
-
+
- Select your {appName} library -
-
- {mode === 'choose' - ? 'Open automatically, resume your last one, or browse.' - : `Choose a ${fileLabel} to open.`} + {platform ? `Select your ${platform.name} library` : 'Select your DJ platform'}
+
{subtitle}
- {mode === 'browse' && ( + {step === 'browse' && ( )} + {step === 'library' && ( + + )} {onCancel && ( + ))} +
+
+ )} + + {openError && (
- {(open.error as Error).message} + {openError}
)}
) : ( - /* ---- Manual browser ---- */ + /* ---- Step 3: browse for it ---- */ <> {/* Path bar */}
@@ -179,11 +279,15 @@ export function CollectionPicker({ onOpened, onCancel }: Props) {
- {/* Listing */} + {/* Listing. Files are filtered server-side to this platform's own, + so a Traktor browse never offers a master.db it cannot open — and + a drive-selecting platform gets no files at all. */}
{listing.isLoading &&
Loading…
} {data && data.dirs.length === 0 && data.files.length === 0 && ( -
No folders or .nml files here.
+
+ {picksDirectory ? 'No folders here.' : 'Nothing openable here.'} +
)} {data?.dirs.map((d) => ( +
+ )} + {/* Manual path + errors */}
- {open.isError && ( + {openError && (
- {(open.error as Error).message} + {openError}
)}
@@ -225,7 +348,11 @@ export function CollectionPicker({ onOpened, onCancel }: Props) { onKeyDown={(e) => { if (e.key === 'Enter' && manual.trim()) open.mutate(manual.trim()) }} - placeholder={`…or paste a full path to ${fileLabel}`} + placeholder={ + picksDirectory + ? '…or paste a full path to the drive' + : `…or paste a full path to ${platform!.library_label}` + } className="min-w-0 flex-1 rounded-md border border-line bg-ink-850 px-3 py-2 font-mono text-xs text-text outline-none placeholder:text-faint focus:border-accent" /> +