From 40630ff78e55412ec924e67fb912385b874deaef Mon Sep 17 00:00:00 2001 From: Benjamin Hardy Date: Mon, 12 Oct 2026 09:23:34 +0200 Subject: [PATCH] Added support for remote file exploring --- CLAUDE.md | 41 +++++- backend/konduktor/adapters/remote/adapter.py | 77 ++++++++++- backend/konduktor/adapters/remote/client.py | 23 ++++ backend/konduktor/adapters/remote/folder.py | 102 ++++++++++++++ backend/konduktor/importer.py | 26 +++- backend/konduktor/main.py | 136 +++++++++++++++++-- backend/konduktor/remote_protocol.py | 3 +- backend/konduktor/schemas.py | 12 +- backend/konduktor/server/app.py | 72 ++++++++++ backend/test_folders.py | 6 +- backend/test_remote_adapter.py | 85 ++++++++++++ frontend/src/App.tsx | 119 ++++++++++++---- frontend/src/api.ts | 17 ++- frontend/src/components/AddFilesDialog.tsx | 26 +++- frontend/src/components/DevicesSection.tsx | 18 ++- frontend/src/components/TrackTable.tsx | 5 +- frontend/src/lib/trackColumns.tsx | 17 +++ frontend/src/lib/trackQueries.ts | 2 + 18 files changed, 717 insertions(+), 70 deletions(-) create mode 100644 backend/konduktor/adapters/remote/folder.py diff --git a/CLAUDE.md b/CLAUDE.md index c30fdf3..d699892 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -568,7 +568,11 @@ Two independent apps that talk over HTTP: / `removed`), `audio` (Range), `art`, `upload` (into a folder CONFINED to the content folder — resolve then `is_relative_to`, so neither `..` nor a symlink escapes — never overwriting, `-2` suffixes, per-session - so a cancel deletes only its own), `fs/list|space`, `save`, `discard`, + so a cancel deletes only its own), `fs/list|space`, `folder/tracks|audio|leads` + (the content folder as a Files tree: tags via the shared `FolderScanner`, + file facts, `held` = file → the library's id; audio only for a file a + listing returned, confined; `leads` = the analysis lead per file, None + unless the platform analyses), `save`, `discard`, `history`, `export-sets`, and the stems routes below. Capabilities are the adapter's plus `tracks.audio_destination="library"`, `reference=False`, `paths.remappable=False`, `overwrite_risk="none"`. @@ -617,6 +621,21 @@ Two independent apps that talk over HTTP: Rekordbox's add analysis — waveform, grid AND key — is computed HERE (`core/add_analysis.prepare` with the lead the upload reports, sent as `NewTrack.analysis`). + **The content folder browsed like a drive** (decided 2026-10-10, + `folder.py`): `/api/fs/drives` lists the server FIRST (`kind: + "server"`, path `server:`) while a remote is open, and the ordinary + Files routes (`/api/fs/folders`, `/api/folder/*`) take `server:` + + the path ON THE SERVER — so the folder view, deck and add dialog need no + second set of routes, and a server path is never taken for the same path + here. `RemoteAdapter.folder_listing` remembers what was listed + (`ServerFiles`, a read-only source); `folder_audio` downloads into the + shared cache by the same facts as a library track's. Adding one is IN + PLACE (`on_library_host` → `importer.plan_on_host` + `run(reference=True)`): + nothing uploaded, nothing asked; files the library holds map to their + ids; where the server reports a lead the file is fetched and analysed + here, as an upload is. Server paths go back to the server in its own + spelling (`_server_paths`), never `str(Path(…))`, which rewrites them on + Windows. **Convert to Stems** (`stems/remote_convert.py`): the server plans (`/v1/stems/plan`, its `convert.plan`), this computer downloads, separates and encodes, uploads each verified file (`/v1/stems/stage`, @@ -791,9 +810,17 @@ Two independent apps that talk over HTTP: expandable Local Storage. A drive carrying a OneLibrary library opens as a device as before, and EVERY drive has a lazily-fetched **Files** tree; clicking a folder is the `folder` source kind — its audio in the ordinary - table, read-only via `readonly_cause: 'not_in_library'`, with files the - collection already holds checked off in the # column (`TrackTable`'s - `marked`). A browsed device is read-only (cause `browsing`); **"Open for + table, with files the collection already holds checked off in the # + column (`TrackTable`'s `marked`). **A held file's row IS the collection + track** (decided 2026-10-10: `main._folder_rows`; `FolderTracks.files` maps + its collection id back to the folder id that adding takes): it shows the + collection's key/rating/cues/plays, loads into the deck as origin + `collection` (`loadTrack`), edits inline and from the menu, and drops onto + a playlist directly. The table runs on the COLLECTION's capabilities; a + LOOSE row's edit — inline (`TableMeta.mayEdit`, asked before the editor + opens), rating, Edit Tags / Analyze / Auto Hotcues / Stems — asks to add + it first (`askToAdd`), and in the deck it stays read-only + (`not_in_library`). A browsed device is read-only (cause `browsing`); **"Open for editing…"** — the drive row's right-click menu, and a button while browsing a device whose caps say `browsing` — opens it as THE library via App's `openForEditing` (unsaved-edits confirm, source closed, library opened). @@ -1413,7 +1440,11 @@ serialization path.** It enforces: only the edited `` THROUGH the trip, one download per file, Analyze on the cached copy, export (and a re-export copying nothing), an upload stored in the mapping's stored form, takeover → read-only at once, - reopening names the holder and the edits left, leaving releases. + reopening names the holder and the edits left, leaving releases. And the + content folder as a drive: listed first, confined, held files ticked off, + auditioned with one download, an add IN PLACE (no upload, the held one not + added twice, both into the playlist, analysed here when the server reports + a lead). - `test_remote_stems.py` — Convert to Stems on a remote with the FAKE engine: the plan's transfer and two-machine space, Replace parks and swaps ON THE SERVER (saved file untouched until Save, which deletes the parked diff --git a/backend/konduktor/adapters/remote/adapter.py b/backend/konduktor/adapters/remote/adapter.py index 949557f..fb85628 100644 --- a/backend/konduktor/adapters/remote/adapter.py +++ b/backend/konduktor/adapters/remote/adapter.py @@ -30,6 +30,7 @@ from ... import remote_protocol as rp from ...core.adapter import ( AudioFacts, FileTagResult, + NotFound, SaveOutcome, Unavailable, Unsupported, @@ -39,6 +40,7 @@ from ...core.query import TrackIndex from .cache import RemoteAudioCache, StaleFacts from .cache import shared as shared_cache from .client import RemoteClient, SessionLost +from .folder import ServerFile, ServerFiles from .session import RemoteSession _NOT_HERE = "A remote library's paths are the server's configuration" @@ -60,6 +62,13 @@ class RemoteAdapter: self._facts: dict[str, AudioFacts] = {} #: Server path of an upload → (the local file it came from, its analysis lead). self._uploads: dict[str, tuple[Path, float | None]] = {} + #: Content-folder files a listing returned, by their server path. + self._listed: dict[str, ServerFile] = {} + #: `str(Path(p))` → `p` for every server path this side has turned into + #: a `Path` (an upload's target, a listed file): on Windows that + #: conversion rewrites the separators, and the server must get its own + #: spelling back. + self._server_paths: dict[str, str] = {} self._dirty = bool(hello.get("dirty")) self._load() @@ -260,6 +269,7 @@ class RemoteAdapter: self.session.lost(ex.holder) raise self._uploads[landed["path"]] = (Path(source), landed.get("analysis_lead")) + self._server_paths[str(Path(landed["path"]))] = landed["path"] return Path(landed["path"]) def free_space(self, path: str) -> int: @@ -268,8 +278,13 @@ class RemoteAdapter: def delete_upload(self, path) -> None: """Undo `upload_audio` (a cancelled or failed import).""" - self._uploads.pop(str(path), None) - self.client.delete_upload(str(path)) + key = self._server_key(path) + self._uploads.pop(key, None) + self.client.delete_upload(key) + + def _server_key(self, path) -> str: + text = str(path) + return self._server_paths.get(text, text) def add_tracks(self, items, *, checkpoint=None): """Add uploaded files. Where the platform analyses what it adds (the @@ -279,10 +294,20 @@ class RemoteAdapter: wire = [] total = len(items) - for n, item in enumerate(items, start=1): - key = str(item.audio_path) + keys = [self._server_key(item.audio_path) for item in items] + # Files already in the content folder (added in place): the server says + # whether the platform analyses, and only then is the file fetched. + in_place = [k for k, item in zip(keys, items) + if item.analysis is None and k not in self._uploads and k in self._listed] + leads = self.client.folder_leads(in_place) if in_place else {} + for n, (item, key) in enumerate(zip(items, keys), start=1): source, lead = self._uploads.get(key, (None, None)) analysis = item.analysis + if analysis is None and source is None and leads.get(key) is not None: + lead = leads[key] + if checkpoint is not None: + checkpoint(f"Downloading {item.track.title or Path(key).name} ({n}/{total})", step=n, of=total) + source = self.folder_audio(key) if analysis is None and lead is not None and source is not None: if checkpoint is not None: checkpoint(f"Analysing {item.track.title or source.name} ({n}/{total})", step=n, of=total) @@ -302,8 +327,8 @@ class RemoteAdapter: self.session.lost(ex.holder) raise self._apply(envelope) - for item in items: - self._uploads.pop(str(item.audio_path), None) + for key in keys: + self._uploads.pop(key, None) return envelope["result"] def apply_stem_swaps(self, swaps, *, add_to_playlist=None): @@ -393,6 +418,46 @@ class RemoteAdapter: facts = self.audio_facts([track_id]).get(track_id) return self.cache.get(facts) if facts else None + # ---- the content folder, browsed -------------------------------------------------- + def folder_listing(self, path: str | None) -> ServerFiles: + """The audio directly inside a content folder (None: the folder itself), + as the server lists it — and remembered, so a file can then be played + or added by its path.""" + listing = ServerFiles.from_wire(self, self.client.folder_tracks(path)) + with self._lock: + self._listed = {k: f for k, f in self._listed.items() if f.folder != listing.path} + self._listed.update(listing.files) + self._server_paths.update({str(Path(k)): k for k in listing.files}) + return listing + + def listed_files(self, paths) -> ServerFiles | None: + """The listed files among `paths` as one source (they may come from + several folders); None when none of them was listed.""" + with self._lock: + found = [self._listed[p] for p in paths if p in self._listed] + return ServerFiles(self, found[0].folder, found) if found else None + + def folder_audio(self, path: str, *, progress=None) -> Path: + """A local copy of a listed file, downloaded into the shared cache — + keyed by the same facts as a library track's, so a file that is both + downloads once.""" + for attempt in range(2): + with self._lock: + found = self._listed.get(path) + if found is None: + raise NotFound("File not found — browse to its folder first") + cached = self.cache.get(found.facts) + if cached is not None: + return cached + try: + return self.cache.fetch( + found.facts, lambda partial: self.client.folder_download(path, partial, progress=progress)) + except StaleFacts: + if attempt: + raise + self.folder_listing(found.folder) # changed on the server: re-read it + raise NotFound(path) + # ---- paths: the server's business ------------------------------------------------ def set_path_mapping(self, mapping): raise Unsupported(_NOT_HERE) diff --git a/backend/konduktor/adapters/remote/client.py b/backend/konduktor/adapters/remote/client.py index 2291bad..9e45487 100644 --- a/backend/konduktor/adapters/remote/client.py +++ b/backend/konduktor/adapters/remote/client.py @@ -246,6 +246,29 @@ class RemoteClient: def fs_list(self, path: str | None) -> dict: return self.request("GET", "/v1/fs/list", params={"path": path} if path else None).json() + def folder_tracks(self, path: str | None) -> dict: + return self.request("GET", "/v1/folder/tracks", params={"path": path} if path else None, + timeout=None).json() + + def folder_leads(self, paths: list[str]) -> dict[str, float | None]: + return self.request("POST", "/v1/folder/leads", json={"paths": paths}).json()["leads"] + + def folder_download(self, path: str, target: Path, *, progress=None) -> dict: + """Stream a listed content-folder file into `target` (as `download`).""" + with self.stream("GET", "/v1/folder/audio", params={"path": path}, timeout=None) as response: + if response.status_code >= 400: + response.read() + self.check(response) + with open(target, "wb") as out: + for chunk in response.iter_bytes(1 << 20): + out.write(chunk) + if progress is not None: + progress(len(chunk)) + return { + "size": int(response.headers.get("X-Konduktor-Size") or 0), + "mtime_ns": int(response.headers.get("X-Konduktor-Mtime-Ns") or 0), + } + def fs_space(self, path: str | None) -> int: return int(self.request("GET", "/v1/fs/space", params={"path": path} if path else None).json()["free"]) diff --git a/backend/konduktor/adapters/remote/folder.py b/backend/konduktor/adapters/remote/folder.py new file mode 100644 index 0000000..16273b7 --- /dev/null +++ b/backend/konduktor/adapters/remote/folder.py @@ -0,0 +1,102 @@ +"""The server's content folder, browsed from this computer like a drive. + +The sidebar's Files trees read folders on THIS computer (`core/folder.py`). On a +remote library the music lives in the server's content folder, which this +computer cannot see — so the server lists it (`/v1/folder/tracks`: tags, file +facts, and which files the library already holds) and this module holds the +answer as a read-only SOURCE, the shape the table, the deck and the importer +already read. + +Adding one of these files never uploads anything: it is already where the +library can reach it, so it is added IN PLACE (`on_library_host`), and the +importer skips both the copy and the copy-or-reference question. + +Ids are the file's path ON THE SERVER — a string, never a `Path` on this side +until the importer needs one, because a server path is not a path here (on a +Windows laptop `Path("/music/x.mp3")` is `\\music\\x.mp3`). +""" +from __future__ import annotations + +from dataclasses import dataclass +from pathlib import Path + +from ...core.adapter import AudioFacts +from ...core.model import PlaylistNode, Track, TrackCues + + +@dataclass +class ServerFile: + folder: str + track: Track + facts: AudioFacts + #: The library's id for this file, when it already points at it. + held: str | None = None + + +class ServerFiles: + """Files in the content folder, as the read half of a source.""" + + #: The importer's cue that these are already on the machine holding the + #: library: added where they are, neither copied nor uploaded. + on_library_host = True + + def __init__(self, adapter, path: str, files: list[ServerFile]): + self.adapter = adapter + self.path = path + self._files = {f.track.id: f for f in files} + + @classmethod + def from_wire(cls, adapter, body: dict) -> "ServerFiles": + folder = body["path"] + facts = body.get("files") or {} + held = body.get("held") or {} + files = [] + for raw in body.get("tracks") or []: + track = Track.model_validate(raw) + fact = facts.get(track.id) + if fact is None: + continue + files.append(ServerFile( + folder=folder, track=track, + facts=AudioFacts(key=track.id, size=int(fact["size"]), mtime_ns=int(fact["mtime_ns"])), + held=held.get(track.id), + )) + return cls(adapter, folder, files) + + @property + def files(self) -> dict[str, ServerFile]: + return self._files + + @property + def tracks(self) -> list[Track]: + return [f.track for f in self._files.values()] + + def track(self, track_id: str) -> Track | None: + found = self._files.get(track_id) + return found.track if found else None + + def held(self, track_id: str) -> str | None: + found = self._files.get(track_id) + return found.held if found else None + + def size(self, track_id: str) -> int: + found = self._files.get(track_id) + return found.facts.size if found else 0 + + def track_cues(self, track_id: str) -> TrackCues | None: + return TrackCues(cues=[], grid_markers=[]) if track_id in self._files else None + + def audio_facts(self, track_ids) -> dict[str, AudioFacts]: + return {t: self._files[t].facts for t in track_ids if t in self._files} + + def audio_path(self, track_id: str, *, progress=None) -> Path | None: + """A local copy (downloaded into the shared cache, like a library track).""" + if track_id not in self._files: + return None + return self.adapter.folder_audio(track_id, progress=progress) + + def playlist_tree(self) -> list[PlaylistNode]: + return [] + + def playlist_tracks(self, node_id: str) -> list[Track] | None: + return None diff --git a/backend/konduktor/importer.py b/backend/konduktor/importer.py index e0e0e58..69decb5 100644 --- a/backend/konduktor/importer.py +++ b/backend/konduktor/importer.py @@ -191,6 +191,30 @@ def plan(source, dest, destination: Path | None, *, track_ids=None, playlist_ids return plan +def plan_on_host(source, track_ids) -> ImportPlan: + """A plan for files that are already on the machine holding the library — a + remote library's content folder, browsed from this computer + (`source.on_library_host`). Nothing is checked on THIS disk, where those + paths mean nothing: the source says each file's size and which ones the + library already holds. Added in place (`run(reference=True)`), so there is + no destination and nothing to copy. + """ + plan = ImportPlan(destination=None) + for track_id in dict.fromkeys(track_ids): + track = source.track(track_id) + if track is None: + continue + name = track_id.replace("\\", "/").rsplit("/", 1)[-1] + plan.tracks.append(PlannedTrack( + track_id=track_id, + title=track.title or name, + source_path=Path(track_id), + size=source.size(track_id), + existing_id=source.held(track_id), + )) + return plan + + def _playlist_name(source, node_id: str) -> str | None: for nid, name in _all_playlists(source): if nid == node_id: @@ -321,7 +345,7 @@ def run( # a folder on the server, instead of copied here. Nothing can be left in # place — the server cannot see this computer's files. uploads = not places and uploads_audio(dest) - if uploads and reference: + if uploads and reference and not getattr(source, "on_library_host", False): raise ValueError("A remote library cannot reference files on this computer") if not reference and not places and not uploads: assert destination is not None diff --git a/backend/konduktor/main.py b/backend/konduktor/main.py index fd40059..e8e49c9 100644 --- a/backend/konduktor/main.py +++ b/backend/konduktor/main.py @@ -2183,6 +2183,50 @@ def source_track_stems(track_id: str) -> dict: FOLDERS = FolderScanner() +# A remote library's content folder rides the same routes. Its paths carry this +# prefix, so a path on the server can never be taken for the same path on this +# computer — and the UI's folder view, deck and add dialog need no second set of +# routes. The prefix alone is the content folder itself. +SERVER_FOLDER = "server:" + + +def _on_server(path: str) -> str | None: + """The server path behind a prefixed one ('' = the content folder), else None.""" + return path[len(SERVER_FOLDER):] if path.startswith(SERVER_FOLDER) else None + + +def _server_track(track: Track) -> Track: + return track.model_copy(update={"id": SERVER_FOLDER + track.id}) + + +def _folder_rows(dest, tracks: list[Track], held_of) -> tuple[list[Track], dict[str, str]]: + """A folder's files as table rows. Where the library holds a file, the row + IS the library's track — its key, rating, comments, cues and plays, and + its id, so it plays, edits and drags as the collection track it is + (decided 2026-10-10) — else the file's own tags. Also returns library id → + the file's folder id, for the rows that are library tracks: adding still + speaks in folder ids.""" + rows: list[Track] = [] + files: dict[str, str] = {} + for track in tracks: + known = held_of(track) + held = dest.track(known) if known else None + if held is None or held.id in files: + rows.append(track) + continue + rows.append(held) + files[held.id] = track.id + return rows, files + + +def _server_file(track_id: str) -> tuple[object, str]: + """The remote adapter and the server path of a listed content-folder file.""" + adapter = _require_remote() + raw = _on_server(track_id) or "" + if adapter.listed_files([raw]) is None: + raise HTTPException(404, "Track not found — browse to its folder first") + return adapter, raw + def _drive_of(path: Path, drives: list[dict]) -> dict | None: """The drive `path` lives on: the longest drive root that contains it.""" @@ -2209,6 +2253,10 @@ def fs_drives() -> list[Drive]: found = places.drives() libraries = sources() out = [Drive(**d) for d in found] + if STATE.remote is not None and STATE.remote_config is not None: + # The server holding the library, first: its content folder is where + # this library's music is, and this computer cannot see it otherwise. + out.insert(0, Drive(name=STATE.remote_config.name, path=SERVER_FOLDER, kind="server")) externals = [d for d in found if d["path"] != "/"] for lib in libraries: home = _drive_of(Path(lib.path), externals) @@ -2223,6 +2271,11 @@ def fs_drives() -> list[Drive]: @app.get("/api/fs/folders", response_model=list[FsEntry]) def fs_folders(path: str) -> list[FsEntry]: """The visible folders directly inside `path` — one level of a Files tree.""" + raw = _on_server(path) + if raw is not None: + listing = _require_remote().client.fs_list(raw or None) + return [FsEntry(name=e["name"], path=SERVER_FOLDER + e["path"]) + for e in listing["entries"] if e["is_dir"]] base = Path(path).expanduser() if not base.is_dir(): raise HTTPException(404, f"Not a folder: {base}") @@ -2236,16 +2289,27 @@ def _formats() -> list[str]: @app.get("/api/folder/tracks", response_model=FolderTracks) def folder_tracks(path: str) -> FolderTracks: """The audio files directly inside a folder, and which are already held.""" + raw = _on_server(path) + if raw is not None: + adapter = _require_remote() + listing = adapter.folder_listing(raw or None) + rows, files = _folder_rows(adapter, [_server_track(t) for t in listing.tracks], + lambda t: listing.held(t.id[len(SERVER_FOLDER):])) + return FolderTracks(path=SERVER_FOLDER + listing.path, tracks=rows, + in_collection=list(files), files=files, removable=False) base = Path(path).expanduser() if not base.is_dir(): raise HTTPException(404, f"Not a folder: {base}") source = FOLDERS.scan(base, _formats()) - held = importer._existing_files(require_adapter()) + dest = require_adapter() + held = importer._existing_files(dest) + rows, files = _folder_rows(dest, source.tracks, lambda t: held.get(importer._key(Path(t.id)))) drive = _drive_of(base, places.drives()) return FolderTracks( path=str(base), - tracks=source.tracks, - in_collection=[t.id for t in source.tracks if importer._key(Path(t.id)) in held], + tracks=rows, + in_collection=list(files), + files=files, removable=drive is None or drive["kind"] == "external", ) @@ -2263,11 +2327,17 @@ def _folder_track(track_id: str) -> FolderSource: def folder_capabilities(path: str) -> Capabilities: from .core.folder import capabilities_for + raw = _on_server(path) + if raw is not None: + return capabilities_for(Path(raw) if raw else Path(STATE.remote_config.name if STATE.remote_config else "Server")) return capabilities_for(Path(path)) @app.get("/api/folder/tracks/cues", response_model=TrackCues) def folder_track_cues(track_id: str) -> TrackCues: + if _on_server(track_id) is not None: + _server_file(track_id) + return TrackCues(cues=[], grid_markers=[]) cues = _folder_track(track_id).track_cues(track_id) assert cues is not None return cues @@ -2275,7 +2345,11 @@ def folder_track_cues(track_id: str) -> TrackCues: @app.get("/api/folder/tracks/audio") def folder_track_audio(track_id: str, stem: int | None = None) -> FileResponse: - path = _folder_track(track_id).audio_path(track_id) + if _on_server(track_id) is not None: + adapter, raw = _server_file(track_id) + path = adapter.folder_audio(raw) # this computer's copy, as for a library track + else: + path = _folder_track(track_id).audio_path(track_id) if path is None or not path.is_file(): raise HTTPException(404, "Audio file not found") if stem is not None: @@ -2286,6 +2360,9 @@ def folder_track_audio(track_id: str, stem: int | None = None) -> FileResponse: @app.get("/api/folder/tracks/stems") def folder_track_stems(track_id: str) -> dict: + if _on_server(track_id) is not None: + adapter, raw = _server_file(track_id) + return _stem_layout_of(adapter.folder_audio(raw)) return _stem_layout_of(_folder_track(track_id).audio_path(track_id)) @@ -2295,6 +2372,34 @@ def _require_addable(dest) -> None: raise HTTPException(422, "Tracks cannot be added to this library") +def _check_add_targets(dest, body: FolderAddRequest) -> None: + if body.playlist_id is not None and dest.playlist_entries(body.playlist_id) is None: + raise HTTPException(404, f"Playlist not found: {body.playlist_id}") + if body.export_id is not None: + if STATE.library_id is None or exports.get(STATE.library_id, body.export_id) is None: + raise HTTPException(404, f"Export not found: {body.export_id}") + + +def _is_server_add(body: FolderAddRequest) -> bool: + on_server = [_on_server(t) is not None for t in body.track_ids] + if any(on_server) and not all(on_server): + raise HTTPException(400, "Files on the server and on this computer are added separately") + return bool(on_server) and all(on_server) + + +def _server_add_plan(body: FolderAddRequest): + """Files in the remote library's content folder: already where the library + can reach them, so they are added IN PLACE — nothing uploaded, nothing asked.""" + dest = _require_remote() + _require_addable(dest) + paths = [_on_server(t) for t in body.track_ids] + source = dest.listed_files(paths) + if source is None: + raise HTTPException(400, "No tracks to add") + _check_add_targets(dest, body) + return source, dest, importer.plan_on_host(source, paths) + + def _folder_add_plan(body: FolderAddRequest): dest = require_adapter() _require_addable(dest) @@ -2315,11 +2420,7 @@ def _folder_add_plan(body: FolderAddRequest): if not body.destination: raise HTTPException(400, "Copying needs a destination folder") destination = Path(body.destination).expanduser() - if body.playlist_id is not None and dest.playlist_entries(body.playlist_id) is None: - raise HTTPException(404, f"Playlist not found: {body.playlist_id}") - if body.export_id is not None: - if STATE.library_id is None or exports.get(STATE.library_id, body.export_id) is None: - raise HTTPException(404, f"Export not found: {body.export_id}") + _check_add_targets(dest, body) return source, dest, destination, importer.plan( source, dest, destination, track_ids=[t.id for t in tracks] ) @@ -2327,6 +2428,11 @@ def _folder_add_plan(body: FolderAddRequest): @app.post("/api/folder/add/preview") def folder_add_preview(body: FolderAddRequest) -> dict: + if _is_server_add(body): + _source, _dest, plan = _server_add_plan(body) + out = plan.as_dict() + out.update(total_bytes=0, free_bytes=None, enough_space=None, removable=False) + return out _source, dest, destination, plan = _folder_add_plan(body) out = plan.as_dict(free_bytes=importer.free_bytes(destination, dest) if destination else None) if importer.places_audio(dest): @@ -2343,10 +2449,16 @@ def folder_add_preview(body: FolderAddRequest) -> dict: def folder_add(body: FolderAddRequest) -> JobStatus: """Add browsed files to the collection. A job, like import: copying can be long.""" _require_no_pending_stems("Adding files") - source, dest, destination, plan = _folder_add_plan(body) + in_place = _is_server_add(body) + if in_place: + source, dest, plan = _server_add_plan(body) + destination = None + else: + source, dest, destination, plan = _folder_add_plan(body) if not plan.importable and not plan.existing: raise HTTPException(400, "Nothing to add (none of those files exist)") - if body.mode == "copy" or importer.places_audio(dest): + # Nothing is copied in place, so there is no space to check. + if not in_place and (body.mode == "copy" or importer.places_audio(dest)): free = importer.free_bytes(destination, dest) needed = importer.placed_bytes(dest, plan) if importer.places_audio(dest) else plan.total_bytes if free is not None and free < needed + importer.SPACE_HEADROOM: @@ -2362,7 +2474,7 @@ def folder_add(body: FolderAddRequest) -> JobStatus: def work(handle): result = importer.run( source, dest, plan, handle, - reference=body.mode == "reference", + reference=in_place or body.mode == "reference", into_playlist=body.playlist_id, ) # Export sets are Konduktor's own data, not the library's, so they are diff --git a/backend/konduktor/remote_protocol.py b/backend/konduktor/remote_protocol.py index 0198931..4319e1e 100644 --- a/backend/konduktor/remote_protocol.py +++ b/backend/konduktor/remote_protocol.py @@ -35,7 +35,8 @@ from .core.model import AutoHotcue, Track, TrackCues #: at least its own: minors only add. Bump the minor for an added route or #: method, the major for anything an older client would misread. #: 1.1 — `move_playlist` (sidebar drag and drop). -API_VERSION: tuple[int, int] = (1, 1) +#: 1.2 — `/v1/folder/*`: the content folder browsed as a Files tree. +API_VERSION: tuple[int, int] = (1, 2) #: How long a session survives without a heartbeat, and how often the holder #: sends one. Long enough to ride out a Wi-Fi blip or a switch to the fallback diff --git a/backend/konduktor/schemas.py b/backend/konduktor/schemas.py index aa3e1c0..d051a21 100644 --- a/backend/konduktor/schemas.py +++ b/backend/konduktor/schemas.py @@ -521,11 +521,15 @@ class Drive(BaseModel): candidate `/api/sources` reports, attached to the drive it lives on so the sidebar can show one row per drive rather than a device list and a drive list that disagree about what is plugged in. + + `server` is a remote library's content folder (path `server:`), listed + first while a remote library is open — the one place its music can be + browsed by folder from this computer. """ name: str path: str - kind: Literal["local", "external"] + kind: Literal["local", "external", "server"] library: SourceCandidate | None = None @@ -533,9 +537,13 @@ class FolderTracks(BaseModel): """The audio files directly inside one folder, projected as tracks.""" path: str + # A file the collection holds is listed AS the collection's track (its id, + # key, rating, cues…); any other file as its own tags, id = its path. tracks: list[Track] - # Ids (= absolute paths) of the files the collection already points at. + # Collection ids of the rows that are collection tracks. in_collection: list[str] + # Those rows' collection id → the file's folder id, which adding takes. + files: dict[str, str] = {} # On an external drive: a track referenced in place goes missing when the # drive is unplugged, which the add dialog has to say. removable: bool diff --git a/backend/konduktor/server/app.py b/backend/konduktor/server/app.py index f2f6741..ca0d239 100644 --- a/backend/konduktor/server/app.py +++ b/backend/konduktor/server/app.py @@ -44,6 +44,7 @@ from ..core.adapter import ( NotFound, Unsupported, ) +from ..core.folder import FolderScanner from ..core.places import is_os_housekeeping from .config import ConfigError, ServerConfig from .session import InUse, Lost, SessionLock @@ -65,6 +66,10 @@ class Server: self.lock = lock or SessionLock() self.rev = 0 self._rev_lock = threading.Lock() + #: The content folder's audio as browsed from a client's Files tree — + #: tags read once per folder state, and the gatekeeper for streaming + #: one of those files (only a file a listing found is served). + self.folders = FolderScanner() # ---- opening --------------------------------------------------------------- def open(self) -> None: @@ -388,6 +393,73 @@ def create_app(server: Server) -> FastAPI: "entries": entries, } + @app.get("/v1/folder/tracks") + def folder_tracks(path: str | None = None) -> dict: + """The audio directly inside a content folder, projected as tracks — the + client's Files tree for the server, like `/api/folder/tracks` for a + drive of its own. Tags only (no decoding). `held` maps each file the + library already points at to the library's id for it, so the client + can tick it off and add it to a playlist without adding it twice.""" + from .. import importer + + folder = server.confine(path) + if not folder.is_dir(): + raise HTTPException(404, f"Not a folder: {folder}") + adapter = server.adapter + source = server.folders.scan(folder, adapter.capabilities().tracks.audio_formats) + library = importer._existing_files(adapter) + files, held = {}, {} + for track in source.tracks: + try: + st = Path(track.id).stat() + except OSError: + continue + files[track.id] = {"size": st.st_size, "mtime_ns": st.st_mtime_ns} + known = library.get(importer._key(Path(track.id))) + if known is not None: + held[track.id] = known + return { + "path": str(folder), + "tracks": [t.model_dump(mode="json") for t in source.tracks if t.id in files], + "files": files, + "held": held, + } + + def listed_file(path: str) -> Path: + # Confined (a symlink in a listing cannot lead out of the content + # folder), and only a file a listing found: this is not a way to read + # any path on the server. + server.confine(path) + source = server.folders.source_for_file(path) + if source is None: + raise HTTPException(404, "File not found — list its folder first") + target = Path(path) + if not target.is_file(): + raise HTTPException(404, "The audio file is missing") + return target + + @app.get("/v1/folder/audio") + def folder_audio(path: str): + target = listed_file(path) + st = target.stat() + media = mimetypes.guess_type(str(target))[0] or "application/octet-stream" + return FileResponse(target, media_type=media, headers={ + "X-Konduktor-Size": str(st.st_size), + "X-Konduktor-Mtime-Ns": str(st.st_mtime_ns), + }) + + @app.post("/v1/folder/leads") + def folder_leads(body: dict = Body(...)) -> dict: + """The analysis lead of each listed file, as an upload reports it: what + a client adding these files IN PLACE measures with. None for every file + when the platform does not analyse what it adds.""" + lead = getattr(server.adapter, "analysis_lead", None) + out = {} + for path in body.get("paths") or []: + target = listed_file(str(path)) + out[str(path)] = lead(target) if lead else None + return {"leads": out} + @app.get("/v1/fs/space") def fs_space(path: str | None = None) -> dict: folder = server.confine(path) diff --git a/backend/test_folders.py b/backend/test_folders.py index 1047c8a..4672e3f 100644 --- a/backend/test_folders.py +++ b/backend/test_folders.py @@ -154,7 +154,11 @@ with TestClient(main.app, raise_server_exceptions=False) as c: check("it is in the playlist", a.playlist_entries(playlist) == [added]) check("it was saved, not left pending", not a.dirty) body = c.get("/api/folder/tracks", params={"path": str(music)}).json() - check("the folder now marks it as held", body["in_collection"] == [str(one)], str(body["in_collection"])) + check("the folder now marks it as held", body["in_collection"] == [added], str(body["in_collection"])) + row = next((t for t in body["tracks"] if t["id"] == added), None) + check("…its row IS the collection track (its id and data), mapped back to the file", + row is not None and body["files"] == {added: str(one)} + and row["import_date"] == a.track(added).import_date, str(body["files"])) print("== a held file is never added twice, but still reaches its target ==") library = STATE.library_id diff --git a/backend/test_remote_adapter.py b/backend/test_remote_adapter.py index 67cd0cf..f7ad125 100644 --- a/backend/test_remote_adapter.py +++ b/backend/test_remote_adapter.py @@ -293,6 +293,91 @@ with tempfile.TemporaryDirectory() as d: check("…and to the mirror here", any((tr.filepath or "").endswith("Brand New.mp3") for tr in main.require_adapter().tracks)) + print("== the content folder, browsed like a drive ==") + loose = make_mp3(content / "Crate" / "Loose One.mp3", seconds=3, seed=11) + drives = c.get("/api/fs/drives").json() + check("the server is listed first among the drives, under the remote's name", + drives and drives[0] == {"name": "NAS", "path": "server:", "kind": "server", "library": None}, + drives[:1]) + tops = c.get("/api/fs/folders", params={"path": "server:"}).json() + check("its Files tree starts at the content folder", + {e["name"] for e in tops} >= {"Crate", "Mapped"} + and all(e["path"].startswith("server:") for e in tops), tops) + r = c.get("/api/folder/tracks", params={"path": f"server:{content}/Mapped"}) + listed = r.json() + check("a folder's files the library holds are listed AS its tracks, ticked off", + r.status_code == 200 and sorted(tr["id"] for tr in listed["tracks"]) == sorted(ids) + and sorted(listed["in_collection"]) == sorted(ids) and not listed["removable"] + and all(v.startswith("server:") for v in listed["files"].values()), r.text[:300]) + check("…with the collection's data, not the file's tags", + next(tr for tr in listed["tracks"] if tr["id"] == target)["genre"] == "Remote Edit") + r = c.get("/api/folder/tracks", params={"path": "server:/etc"}) + check("…and nothing outside the content folder is listed", r.status_code == 400, r.text[:200]) + crate = c.get("/api/folder/tracks", params={"path": f"server:{content}/Crate"}).json() + loose_id = f"server:{loose}" + check("a file the library does not hold is listed unticked", + [tr["id"] for tr in crate["tracks"]] == [loose_id] and crate["in_collection"] == []) + caps = c.get("/api/folder/capabilities", params={"path": f"server:{content}/Crate"}).json() + check("…read-only, like any browsed folder", not caps["writable"] + and caps["readonly_cause"] == "not_in_library") + folder_downloads = [] + real_folder_download = adapter.client.folder_download + adapter.client.folder_download = lambda *a, **k: (folder_downloads.append(a[0]), + real_folder_download(*a, **k))[1] + r = c.get("/api/folder/tracks/audio", params={"track_id": loose_id}) + check("the deck can audition it", r.status_code == 200 and r.content == loose.read_bytes()) + c.get("/api/folder/tracks/audio", params={"track_id": loose_id}) + check("…downloaded once", folder_downloads == [str(loose)], folder_downloads) + r = c.get("/api/folder/tracks/audio", params={"track_id": f"server:{content}/Crate/nope.mp3"}) + check("a file no listing returned is not served", r.status_code == 404) + srv_unlisted = httpx.get(f"http://127.0.0.1:{port}/v1/folder/audio", + params={"path": str(work)}, auth=("dj", "secret")) + check("…nor, asked of the server directly, anything outside the content folder", + srv_unlisted.status_code == 400, srv_unlisted.text[:200]) + + pl = c.post("/api/playlists", json={"name": "From the server"}).json()["id"] + held_track = listed["in_collection"][0] + held_id = listed["files"][held_track] # adding speaks in folder ids + add = {"track_ids": [loose_id, held_id], "mode": "reference", "playlist_id": pl} + r = c.post("/api/folder/add/preview", json=add) + pv = r.json() + check("(preview) one new, one already held, nothing to copy", + r.status_code == 200 and pv["importable"] == 1 and len(pv["existing"]) == 1 + and pv["total_bytes"] == 0 and pv["enough_space"] is None, r.text[:300]) + mixed = c.post("/api/folder/add/preview", json={**add, "track_ids": [loose_id, str(incoming)]}) + check("files here and on the server are not mixed in one add", mixed.status_code == 400) + # Pretend the platform analyses what it adds (as Rekordbox does): the file + # is then fetched and analysed HERE, and the server receives the result. + received = [] + real_add = server_adapter.add_tracks + server_adapter.add_tracks = lambda items, **k: (received.extend(items), real_add(items, **k))[1] + server_adapter.analysis_lead = lambda path: 0.0 + before = sorted(p.name for p in content.rglob("*") if p.is_file()) + job = c.post("/api/folder/add", json=add).json() + for _ in range(400): + j = c.get(f"/api/jobs/{job['id']}").json() + if j["state"] != "running": + break + time.sleep(0.05) + del server_adapter.analysis_lead + server_adapter.add_tracks = real_add + added = [tr for tr in server_adapter.tracks if server_adapter.audio_path(tr.id) == loose] + check("the file is added to the library WHERE IT IS", j["state"] == "done" and len(added) == 1, + j.get("error")) + check("…nothing uploaded or copied", sorted(p.name for p in content.rglob("*") if p.is_file()) == before) + check("…analysed here on the cached copy, the result sent along", + len(received) == 1 and received[0].analysis is not None and folder_downloads == [str(loose)], + f"{len(received)} {folder_downloads}") + entries = server_adapter.playlist_entries(pl) or [] + check("…both land in the playlist, the held one not added twice", + added and entries == [added[0].id, held_track] + and len(server_adapter.tracks) == len(main.require_adapter().tracks), entries) + crate = c.get("/api/folder/tracks", params={"path": f"server:{content}/Crate"}).json() + check("…and the folder now shows it ticked off, as the collection track", + crate["in_collection"] == [added[0].id] and crate["files"] == {added[0].id: loose_id} + if added else False, crate) + check("the save is versioned on the server", not server_adapter.dirty) + print("== another computer takes over ==") other = RemoteClient(remote_config.Remote(id="o", name="NAS", host=f"127.0.0.1:{port}", username="dj"), "secret") other.acquire("other-client", "Studio iMac", takeover=True) diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index ce3f938..c630aec 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -8,6 +8,7 @@ import { addTracksToPlaylist } from './lib/addTracks' import { useDropTarget } from './lib/drag' import { api, type AnalyzeOptions, type AnalyzeResult, type CueBatchResult, type AutoCueSlot, type PlaylistNode, type StemBatchResult, type Track, type TrackOrigin } from './api' import { confirmDiscardUnsaved } from './lib/unsaved' +import { askConfirm } from './lib/confirm' import { COLUMN_MENU, DEFAULT_COLUMN_ORDER, @@ -80,6 +81,9 @@ export default function App() { const [prepOrigin, setPrepOrigin] = useState('collection') // The view's origin, read by the load callbacks below (defined before it). const viewOriginRef = useRef('collection') + // The browsed folder's rows that ARE collection tracks: collection id → the + // file's folder id. A ref, for the callbacks below that outlive a render. + const folderFilesRef = useRef>({}) // Browsed files being added to the collection (and maybe a playlist/export). const [adding, setAdding] = useState<{ ids: string[]; target: AddTarget | null } | null>(null) const [playRequest, setPlayRequest] = useState(0) // bump → deck loads & auto-plays @@ -108,7 +112,9 @@ export default function App() { const loadTrack = useCallback((t: Track, origin: TrackOrigin = viewOriginRef.current) => { setPrepTrack(t) - setPrepOrigin(origin) + // A folder row the collection holds IS the collection track, so the deck + // loads it as one: its cues and grid, and editable (decided 2026-10-10). + setPrepOrigin(origin === 'folder' && folderFilesRef.current[t.id] ? 'collection' : origin) }, []) const playTrack = useCallback( (t: Track) => { @@ -307,6 +313,11 @@ export default function App() { () => new Set(folderView.data?.in_collection ?? []), [folderView.data], ) + const folderFiles = useMemo(() => folderView.data?.files ?? {}, [folderView.data]) + folderFilesRef.current = viewingFolder ? folderFiles : {} + // Adding speaks in FOLDER ids; a row the collection holds carries its + // collection id, and maps back (the add dialog then reports it as held). + const toFolderIds = (ids: string[]) => ids.map((id) => folderFiles[id] ?? id) viewOriginRef.current = viewingDevice ? 'device' : viewingFolder ? 'folder' : 'collection' // Tracks in view belong to ANOTHER library (a device) or to none (a folder), // so no collection command may be offered on them: their ids mean nothing to @@ -368,10 +379,16 @@ export default function App() { // asked (decided 2026-10-06). const addForeign = useCallback( (origin: TrackOrigin, ids: string[], target: AddTarget) => { - if (origin === 'folder') setAdding({ ids, target }) - else if (origin === 'device') setImportDrop({ ids, target }) + if (origin === 'folder') { + const files = folderFilesRef.current + // Rows that are all collection tracks already: nothing to add first. + if (ids.every((id) => files[id])) { + if (target.kind === 'playlist') void addToPlaylist(target.id, ids) + else void addToExport(target.id, ids) + } else setAdding({ ids: ids.map((id) => files[id] ?? id), target }) + } else if (origin === 'device') setImportDrop({ ids, target }) }, - [], + [addToPlaylist, addToExport], ) const [deckDropRef, deckOver] = useDropTarget({ hint: (p) => (p.kind === 'tracks' ? true : null), @@ -407,7 +424,10 @@ export default function App() { : origin === 'folder' ? (folderCaps.data ?? readOnlyCaps('not_in_library')) : capabilities.data! - const viewCaps = capsFor(viewOriginRef.current) + // A folder's table runs on the COLLECTION's: the rows it holds are collection + // tracks and edit as such, and a loose row asks to be added first + // (`folderMayEdit`) rather than rendering inert. + const viewCaps = viewingFolder ? capabilities.data! : capsFor(viewOriginRef.current) // The deck follows its TRACK's library, not the view's. const deckCaps = capsFor(prepOrigin) @@ -443,9 +463,12 @@ export default function App() { // PrepStrip keys its audio on the id, so a new object for the same id // reloads nothing. useEffect(() => { - if (!prepTrack || viewOriginRef.current !== prepOrigin) return + if (!prepTrack) return const fresh = tracks.find((t) => t.id === prepTrack.id) - if (fresh && JSON.stringify(fresh) !== JSON.stringify(prepTrack)) setPrepTrack(fresh) + if (!fresh) return + const origin = + viewOriginRef.current === 'folder' && folderFilesRef.current[fresh.id] ? 'collection' : viewOriginRef.current + if (origin === prepOrigin && JSON.stringify(fresh) !== JSON.stringify(prepTrack)) setPrepTrack(fresh) // Only a refetch of the list matters; prepTrack is read, not tracked. // eslint-disable-next-line react-hooks/exhaustive-deps }, [tracks]) @@ -636,7 +659,7 @@ export default function App() { } // ---- Convert to Stems ------------------------------------------------------ - const canStems = canEdit && !viewForeign && !!capabilities.data?.tracks.stem_convertible + const canStems = canEdit && !viewingDevice && !!capabilities.data?.tracks.stem_convertible const finishStemBatch = (state: string, r: StemBatchResult | null, error: string | null) => { qc.invalidateQueries({ queryKey: ['state'] }) if (state === 'failed' || !r) { @@ -788,7 +811,7 @@ export default function App() { // the rest with a reason. const canAnalyzeGrid = !!capabilities.data?.grid.editable const canAnalyzeKey = !!capabilities.data?.tracks.key_writable - const canAnalyze = canEdit && !viewForeign && (canAnalyzeGrid || canAnalyzeKey) + const canAnalyze = canEdit && !viewingDevice && (canAnalyzeGrid || canAnalyzeKey) const startCueBatch = (ids: string[]) => { const byId = new Map(tracks.map((t) => [t.id, t])) @@ -801,7 +824,7 @@ export default function App() { setBatchCancelling(false) setBatchJob({ id: job.id, kind: 'cues' }) } - const canAutoCue = canEdit && !viewForeign && (capabilities.data?.cues.hotcue_slots ?? 0) > 0 + const canAutoCue = canEdit && !viewingDevice && (capabilities.data?.cues.hotcue_slots ?? 0) > 0 // ---- Remove ▸ ----------------------------------------------------------- @@ -934,12 +957,48 @@ export default function App() { }), }) - const canClearGrids = canEdit && !viewForeign && !!capabilities.data?.grid.editable + const canClearGrids = canEdit && !viewingDevice && !!capabilities.data?.grid.editable const canClearCues = canAutoCue - const canRemoveTracks = canEdit && !viewForeign && !!capabilities.data?.tracks.removable + const canRemoveTracks = canEdit && !viewingDevice && !!capabilities.data?.tracks.removable // The COLLECTION's capabilities, deliberately: adding happens while a folder // or device is on screen, whose own capabilities are read-only. const canAddTracks = canEdit && !!capabilities.data?.tracks.addable + + // In a folder, only the rows the collection holds can be edited. Anything + // that would edit a loose file says so and offers to add it, rather than + // being absent or silently inert (decided 2026-10-10). + const askToAdd = async (ids: string[]) => { + const loose = ids.filter((id) => !folderFiles[id]) + if (!loose.length) return + const first = tracks.find((t) => t.id === loose[0]) + const what = + loose.length === 1 + ? `“${first?.title || 'This file'}” is not in your collection` + : `${loose.length} of these files are not in your collection` + if (!canAddTracks) { + notify('error', `${what}, and tracks cannot be added to this library.`) + return + } + const add = await askConfirm({ + title: 'Add to your collection first', + body: `${what} yet. Add ${loose.length === 1 ? 'it' : 'them'} to edit tags, cues or the beatgrid.`, + confirmLabel: 'Add to Collection…', + tone: 'primary', + }) + if (add) setAdding({ ids: loose, target: null }) + } + const folderEditField = (track: Track, field: keyof Track, value: string | number) => { + if (folderFiles[track.id]) editField(track, field, value) + else void askToAdd([track.id]) + } + const folderMayEdit = (track: Track) => { + if (folderFiles[track.id]) return true + void askToAdd([track.id]) + return false + } + // The open menu's loose files: every editing item then asks to add them. + const menuLoose = menu && viewingFolder ? menu.ids.filter((id) => !folderFiles[id]) : [] + const gated = (fn: () => void) => (menuLoose.length ? () => void askToAdd(menuLoose) : fn) const exportRootId = source.kind === 'export' ? source.id : source.kind === 'export-other' ? source.exportId : null const removeItems = (ids: string[]): MenuItem[] => [ @@ -1023,8 +1082,8 @@ export default function App() { : []), // 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 && !viewForeign && menu.ids.length === 1 - ? [{ label: 'Edit Tags…', onClick: () => setEditing(menu.track) }] + ...(canEdit && !viewingDevice && menu.ids.length === 1 + ? [{ label: 'Edit Tags…', onClick: gated(() => setEditing(menu.track)) }] : []), ...(canAnalyze ? [ @@ -1032,7 +1091,7 @@ export default function App() { label: 'Analyze…', hint: batchJob ? 'busy' : menu.ids.length > 1 ? String(menu.ids.length) : undefined, disabled: !!batchJob, - onClick: () => setAnalyzing(menu.ids), + onClick: gated(() => setAnalyzing(menu.ids)), }, ] : []), @@ -1044,20 +1103,20 @@ export default function App() { label: 'Auto Hotcues…', hint: batchJob ? 'busy' : menu.ids.length > 1 ? String(menu.ids.length) : undefined, disabled: !!batchJob, - onClick: () => startCueBatch(menu.ids), + onClick: gated(() => startCueBatch(menu.ids)), }, ] : []), // Shown disabled WITH a reason where the platform cannot play stem // files as stems, rather than hidden: a missing item reads as a bug. - ...(canEdit && !viewForeign + ...(canEdit && !viewingDevice ? [ canStems ? { label: 'Convert to Stems…', hint: batchJob ? 'busy' : menu.ids.length > 1 ? String(menu.ids.length) : undefined, disabled: !!batchJob, - onClick: () => setStemDialog(menu.ids), + onClick: gated(() => setStemDialog(menu.ids)), } : { label: 'Convert to Stems…', @@ -1070,12 +1129,14 @@ export default function App() { // A device's track ids belong to the stick, not the collection, so // there is nothing they could be added to. A folder's files CAN be // added — through the add dialog, which puts them in the - // collection first. + // collection first; rows it already holds are collection tracks. ...(viewingFolder - ? canAddTracks + ? !menuLoose.length + ? [{ label: 'Add to', submenu: addToItems(menu.ids) }] + : canAddTracks ? [ - { label: 'Add to Collection…', onClick: () => setAdding({ ids: menu.ids, target: null }) }, - { label: 'Add to', submenu: folderAddToItems(menu.ids) }, + { label: 'Add to Collection…', onClick: () => setAdding({ ids: menuLoose, target: null }) }, + { label: 'Add to', submenu: folderAddToItems(toFolderIds(menu.ids)) }, ] : [{ label: 'Add to Collection…', @@ -1092,7 +1153,7 @@ export default function App() { ? [{ label: 'Set Position…', onClick: () => setPositioning(menu.ids) }] : []), ...(() => { - const items = removeItems(menu.ids) + const items = menuLoose.length ? [] : removeItems(menu.ids) return items.length ? [{ label: 'Remove', submenu: items }] : [] })(), ]} @@ -1315,9 +1376,11 @@ export default function App() { {' · this folder only'} - - Not in collection - + {tracks.length > heldInFolder.size && ( + + Not in collection + + )} {tracks.length > 0 && canAddTracks && (