From e8d2c66e06b3768f0132fdd0a3c87fbef5d5d951 Mon Sep 17 00:00:00 2001 From: Benjamin Hardy Date: Thu, 9 Jul 2026 10:20:49 +0200 Subject: [PATCH 1/4] Begun implementing collection history system --- .gitignore | 5 +- backend/konduktor-sidecar.spec | 4 +- backend/konduktor/history.py | 174 ++++++++++++++++ backend/konduktor/main.py | 55 ++++- backend/konduktor/paths.py | 36 ++++ backend/konduktor/playlist_store.py | 100 +++++++-- backend/konduktor/prefs.py | 25 ++- backend/konduktor/schemas.py | 10 +- backend/requirements.txt | 5 + backend/run_tests.sh | 2 +- backend/test_history.py | 113 +++++++++++ backend/test_phase3.py | 12 +- backend/test_save_fidelity.py | 5 + frontend/src/App.tsx | 16 +- frontend/src/api.ts | 19 +- frontend/src/components/HistoryPanel.tsx | 192 ++++++++++++++++++ frontend/src/components/PathMappingDialog.tsx | 6 +- frontend/src/components/SaveBar.tsx | 8 +- frontend/src/components/Sidebar.tsx | 11 +- 19 files changed, 744 insertions(+), 54 deletions(-) create mode 100644 backend/konduktor/history.py create mode 100644 backend/konduktor/paths.py create mode 100644 backend/test_history.py create mode 100644 frontend/src/components/HistoryPanel.tsx diff --git a/.gitignore b/.gitignore index f984724..1c4f2b2 100644 --- a/.gitignore +++ b/.gitignore @@ -18,11 +18,14 @@ frontend/dist-ssr/ # The collection is personal, large, and irreplaceable — don't commit it. # Remove this if you deliberately want to version a sample .nml. *.nml -# Backups Konduktor will create before any write (Phase 3+). +# Legacy pre-git backups (superseded by version history; left ignored so any +# old .bak files on disk stay out of git). *.nml.bak *.nml.backup *.nml.*.bak backups/ +# Version-history git repos, if a dev points KONDUKTOR_DATA_DIR inside the repo. +history/ # ---- Editor / OS ---- .vscode/ diff --git a/backend/konduktor-sidecar.spec b/backend/konduktor-sidecar.spec index cefe5a4..7ba891e 100644 --- a/backend/konduktor-sidecar.spec +++ b/backend/konduktor-sidecar.spec @@ -8,6 +8,8 @@ # - traktor-nml-utils parses/serializes via xsdata, which discovers plugins at # runtime → collect_submodules('xsdata') # - python-multipart is imported as `multipart` by starlette → hidden import +# - dulwich (version-history backups) imports git backends dynamically → +# collect_submodules('dulwich') from PyInstaller.utils.hooks import collect_submodules, collect_all hiddenimports = [] @@ -15,7 +17,7 @@ datas = [] binaries = [] # Dynamically-imported subpackages. -for pkg in ("uvicorn", "xsdata"): +for pkg in ("uvicorn", "xsdata", "dulwich"): hiddenimports += collect_submodules(pkg) # Native standard extras — grab modules + shared libs + any data. diff --git a/backend/konduktor/history.py b/backend/konduktor/history.py new file mode 100644 index 0000000..451c1b0 --- /dev/null +++ b/backend/konduktor/history.py @@ -0,0 +1,174 @@ +"""Per-collection version history backed by a purely-local git repo (dulwich). + +Replaces the old ``.bak`` copy-on-save. Every Konduktor write to a collection is +committed to a small git repo — one per collection — living in the app-data dir +(NOT next to the user's collection). Git's delta packing makes near-identical +NMLs almost free, so we keep full history forever; a manual "delete all history" +is the only pruning. + +Design rules: + * ALL git interaction is confined to this module. + * EVERY public function is best-effort: it swallows its own errors (returning a + safe empty/None value) so a history failure can never break a save or an open. + * The tracked file is a fixed name inside each repo (``collection.nml``); the + repo is keyed by a hash of the collection's absolute OS path (mirrors prefs' + path-based keying). Collection identity is therefore the OS path — moving the + collection starts a fresh history (same fragility prefs already accepts). +""" +from __future__ import annotations + +import hashlib +import json +import logging +import shutil +from dataclasses import dataclass +from datetime import datetime, timezone +from pathlib import Path + +from dulwich import porcelain +from dulwich.repo import Repo + +from . import paths + +log = logging.getLogger(__name__) + +_TRACKED_NAME = "collection.nml" +_AUTHOR = b"Konduktor " + + +@dataclass +class HistoryEntry: + id: str # full commit sha (hex) + timestamp: str # ISO 8601, UTC + summary: str # first line of the commit message + + +# ---- repo location ----------------------------------------------------------- + +def _key(nml_path: Path) -> str: + return hashlib.sha256(str(Path(nml_path).resolve()).encode()).hexdigest()[:16] + + +def _repo_dir(nml_path: Path) -> Path: + return paths.app_data_dir() / "history" / _key(nml_path) + + +def _tracked_file(repo_dir: Path) -> Path: + return repo_dir / _TRACKED_NAME + + +def _write_meta(repo_dir: Path, nml_path: Path) -> None: + """A tiny sidecar recording which collection this repo belongs to (for + debugging / a friendly display name). Best-effort.""" + try: + meta = {"path": str(Path(nml_path).resolve()), "name": Path(nml_path).parent.name} + (repo_dir / ".meta.json").write_text(json.dumps(meta, indent=2)) + except OSError: + pass + + +def _open_or_init(nml_path: Path) -> Path: + """Ensure the collection's repo exists; return its directory.""" + repo_dir = _repo_dir(nml_path) + if not (repo_dir / ".git").exists(): + repo_dir.mkdir(parents=True, exist_ok=True) + porcelain.init(str(repo_dir)) + _write_meta(repo_dir, nml_path) + return repo_dir + + +def _head_blob(repo: Repo) -> bytes | None: + """The tracked file's bytes at HEAD, or None if the repo has no commits.""" + try: + head = repo.head() + except KeyError: + return None + commit = repo[head] + tree = repo[commit.tree] + _mode, blob_sha = tree[_TRACKED_NAME.encode()] + return repo[blob_sha].data + + +# ---- public API -------------------------------------------------------------- + +def commit(nml_path: Path, data: bytes, message: str, app_version: str) -> str | None: + """Commit ``data`` as the collection's newest version. Deduped: if ``data`` + is byte-identical to HEAD, no commit is made and None is returned. Returns + the new commit sha (hex) on success, None on dedup or any failure.""" + try: + repo_dir = _open_or_init(nml_path) + with Repo(str(repo_dir)) as repo: + if _head_blob(repo) == data: + return None # nothing changed since last version + path = _tracked_file(repo_dir) + path.write_bytes(data) + porcelain.add(str(repo_dir), paths=[str(path)]) + msg = f"{message}\n\nApp-Version: {app_version}".encode() + sha = porcelain.commit(str(repo_dir), message=msg, author=_AUTHOR, committer=_AUTHOR) + return sha.decode() if isinstance(sha, bytes) else str(sha) + except Exception: # best-effort — history must never break a save + log.exception("history.commit failed for %s", nml_path) + return None + + +def ensure_baseline(nml_path: Path) -> None: + """Commit the current on-disk collection as an "as I found it" baseline. + Deduped, so re-opening an unchanged collection is a no-op. Best-effort.""" + try: + data = Path(nml_path).read_bytes() + except OSError: + return + commit(nml_path, data, "Baseline — opened collection", _app_version()) + + +def list_history(nml_path: Path) -> list[HistoryEntry]: + """All versions, newest first. Empty list if no history / on any failure.""" + repo_dir = _repo_dir(nml_path) + if not (repo_dir / ".git").exists(): + return [] + try: + entries: list[HistoryEntry] = [] + with Repo(str(repo_dir)) as repo: + try: + repo.head() + except KeyError: + return [] + for e in repo.get_walker(): + c = e.commit + ts = datetime.fromtimestamp(c.commit_time, tz=timezone.utc).isoformat() + summary = c.message.decode("utf-8", "replace").splitlines()[0] if c.message else "" + entries.append(HistoryEntry(id=c.id.decode(), timestamp=ts, summary=summary)) + return entries + except Exception: + log.exception("history.list_history failed for %s", nml_path) + return [] + + +def read_version(nml_path: Path, commit_id: str) -> bytes | None: + """The tracked collection bytes at a specific commit, or None on failure.""" + repo_dir = _repo_dir(nml_path) + if not (repo_dir / ".git").exists(): + return None + try: + with Repo(str(repo_dir)) as repo: + c = repo[commit_id.encode()] + tree = repo[c.tree] + _mode, blob_sha = tree[_TRACKED_NAME.encode()] + return repo[blob_sha].data + except Exception: + log.exception("history.read_version failed for %s @ %s", nml_path, commit_id) + return None + + +def clear_history(nml_path: Path) -> None: + """Delete ALL version history for a collection (removes its repo). Best-effort.""" + try: + shutil.rmtree(_repo_dir(nml_path), ignore_errors=True) + except Exception: + log.exception("history.clear_history failed for %s", nml_path) + + +def _app_version() -> str: + from . import __version__ + + return __version__ diff --git a/backend/konduktor/main.py b/backend/konduktor/main.py index 3ea2765..fbd3063 100644 --- a/backend/konduktor/main.py +++ b/backend/konduktor/main.py @@ -15,7 +15,7 @@ from fastapi.responses import FileResponse from . import __version__ from . import auto_hotcues as ah -from . import prefs +from . import history, prefs from .collection_service import CollectionService from .discovery import describe, detect_collections from .path_mapping import PathMapping @@ -36,6 +36,7 @@ from .schemas import ( FsEntry, FsListing, GridEdit, + HistoryEntry, OpenCollection, PathMappingInfo, PlaylistNode, @@ -94,6 +95,9 @@ class AppState: if saved: store.set_path_mapping(PathMapping.make(saved["from"], saved["to"])) self.path, self.service, self.store = path, service, store + # Version history: record an "as I found it" baseline (deduped, so + # re-opening an unchanged collection is a no-op). Best-effort. + history.ensure_baseline(path) STATE = AppState() @@ -211,17 +215,18 @@ def preview_path_mapping( @app.post("/api/collection/remap-paths", response_model=RemapResult) def remap_paths(body: PathMappingInfo) -> RemapResult: """Write-back: permanently rewrite matching track LOCATIONs (and the - playlist references that join to them) to the `to` prefix, then save - (backup-first). Destructive and OS-specific — the UI warns accordingly.""" + playlist references that join to them) to the `to` prefix, then save (a + version-history commit is written). Destructive and OS-specific — the UI + warns accordingly.""" store = require_store() mapping = PathMapping.make(body.from_, body.to) if mapping.empty: raise HTTPException(400, "Both a `from` and `to` prefix are required") count = store.remap_locations(mapping) if count == 0: - return RemapResult(rewritten=0, backup=None) + return RemapResult(rewritten=0, commit=None) outcome = store.save() - return RemapResult(rewritten=count, backup=str(outcome.backup)) + return RemapResult(rewritten=count, commit=outcome.commit) @app.get("/api/prefs") @@ -644,11 +649,47 @@ async def set_track_art(track_id: str = Form(...), file: UploadFile = File(...)) def save() -> SaveResult: store = require_store() if not store.dirty: - return SaveResult(saved=False, backup=None, playlists=store.count_playlists()) + return SaveResult(saved=False, commit=None, playlists=store.count_playlists()) outcome = store.save() return SaveResult( saved=True, - backup=str(outcome.backup), + commit=outcome.commit, playlists=store.count_playlists(), file_tags=[FileTagOutcome(**r.__dict__) for r in outcome.tag_results], ) + + +# ---- version history -------------------------------------------------- + + +@app.get("/api/history", response_model=list[HistoryEntry]) +def get_history() -> list[HistoryEntry]: + """All saved versions of the current collection, newest first.""" + require_store() + return [HistoryEntry(**e.__dict__) for e in history.list_history(STATE.path)] + + +@app.post("/api/history/{commit_id}/restore", response_model=CollectionStatus) +def restore_version(commit_id: str) -> CollectionStatus: + """Restore the collection to a past version. Writes that version back as a + NEW forward save (a fresh commit on top of history — never a rewind), then + reloads. The user should close Traktor first (it overwrites on exit).""" + require_store() + data = history.read_version(STATE.path, commit_id) + if data is None: + raise HTTPException(404, f"Version not found: {commit_id}") + path = STATE.path + tmp = path.with_suffix(path.suffix + ".tmp") + tmp.write_bytes(data) + tmp.replace(path) + history.commit(path, data, f"Restored version {commit_id[:8]}", __version__) + STATE.open(path) # rebuild read + edit models from the restored file + return collection_status() + + +@app.delete("/api/history") +def clear_history() -> dict: + """Permanently delete ALL version history for the current collection.""" + require_store() + history.clear_history(STATE.path) + return {"status": "cleared"} diff --git a/backend/konduktor/paths.py b/backend/konduktor/paths.py new file mode 100644 index 0000000..c9c7ca0 --- /dev/null +++ b/backend/konduktor/paths.py @@ -0,0 +1,36 @@ +"""Resolves the app's per-OS, user-writable data directory. + +Everything Konduktor persists that is NOT part of the user's collection lives +here: `userprefs.json` and the per-collection version-history git repos. It must +be a real writable location — the package-relative path prefs.py used to use is +read-only/ephemeral in a frozen PyInstaller build (`sys._MEIPASS`). + +Resolution order: + 1. ``KONDUKTOR_DATA_DIR`` env var (tests point this at a temp dir to stay + isolated from the real user data). + 2. platformdirs' per-OS user-data dir + (~/Library/Application Support/Konduktor, %LOCALAPPDATA%\\Konduktor, …). + +Best-effort: any failure to create the dir degrades to returning the path +anyway; callers already treat all data I/O as best-effort. +""" +from __future__ import annotations + +import os +from pathlib import Path + +import platformdirs + +_APP_NAME = "Konduktor" +_APP_AUTHOR = "Liquid Ice Studios" + + +def app_data_dir() -> Path: + """The user-writable directory for Konduktor's persisted app data.""" + override = os.environ.get("KONDUKTOR_DATA_DIR") + base = Path(override) if override else Path(platformdirs.user_data_dir(_APP_NAME, _APP_AUTHOR)) + try: + base.mkdir(parents=True, exist_ok=True) + except OSError: + pass # non-fatal — callers handle missing/unwritable data dirs + return base diff --git a/backend/konduktor/playlist_store.py b/backend/konduktor/playlist_store.py index 2625a50..c7ca624 100644 --- a/backend/konduktor/playlist_store.py +++ b/backend/konduktor/playlist_store.py @@ -6,7 +6,8 @@ Design goals: exact formatting; lxml does not), * surgical — the ~14 MB COLLECTION stays byte-identical (we splice only the span back into the original file bytes), - * safe — a timestamped .bak is written before every save. + * safe — every save is committed to the collection's version history (see + ``history.py``); the commit is additive and never alters the saved bytes. We edit the parsed dataclass model in memory (create/rename/delete/set-entries), then on save render the full model, extract just the freshly-rendered @@ -17,10 +18,9 @@ Playlists are identified by their stable UUID; folders by a synthetic path id """ from __future__ import annotations -import shutil import threading -import time import uuid as uuidlib +from collections import Counter from dataclasses import dataclass from pathlib import Path @@ -43,6 +43,7 @@ from traktor_nml_utils.models.collection import ( ) from xsdata.formats.dataclass.serializers import XmlSerializer +from . import __version__, history from .path_mapping import PathMapping from .schemas import PlaylistNode @@ -62,7 +63,7 @@ class FileTagResult: @dataclass class SaveOutcome: - backup: Path + commit: str | None # sha of the version-history commit (None if deduped/failed) tag_results: list[FileTagResult] @@ -91,8 +92,14 @@ class PlaylistStore: self._track_edits: dict[str, set[str]] = {} # track_id -> (image_bytes, mime) of staged replacement cover art self._track_art: dict[str, tuple[bytes, str]] = {} + # (category, detail) events accumulated this session -> commit summary + self._edit_events: list[tuple[str, str | None]] = [] self.dirty = False + def _note(self, category: str, detail: str | None = None) -> None: + """Record a human-meaningful edit for the next commit's summary.""" + self._edit_events.append((category, detail)) + def _root(self) -> Nodetype: node = self._nml.playlists.node if self._nml.playlists else None if node is None: @@ -199,6 +206,7 @@ class PlaylistStore: ) folder.subnodes.node.append(node) folder.subnodes.count = len(folder.subnodes.node) + self._note("playlist-create", name) self.dirty = True return new_uuid @@ -208,6 +216,7 @@ class PlaylistStore: if node is None: raise PlaylistError(f"Playlist not found: {playlist_uuid}") node.name = name + self._note("playlist-rename", name) self.dirty = True def delete_playlist(self, playlist_uuid: str) -> None: @@ -220,6 +229,7 @@ class PlaylistStore: raise PlaylistError("Cannot delete a top-level node") parent.subnodes.node.remove(node) parent.subnodes.count = len(parent.subnodes.node) + self._note("playlist-delete", node.name) self.dirty = True def set_entries(self, playlist_uuid: str, entries: list[tuple[str, str]]) -> None: @@ -233,6 +243,7 @@ class PlaylistStore: for key, ptype in entries ] pl.entries = len(pl.entry) + self._note("playlist-entries", node.name) self.dirty = True # ---- track metadata editing --------------------------------------- @@ -328,6 +339,7 @@ class PlaylistStore: grid=None, ) ) + self._note("hotcue-set") self.dirty = True def place_hotcues( @@ -364,12 +376,14 @@ class PlaylistStore: if cue is None: raise PlaylistError(f"Hotcue {slot} is not set") cue.type = cue_type + self._note("hotcue-type") self.dirty = True def delete_hotcue(self, track_id: str, slot: int) -> None: with self._lock: entry = self._entry_or_raise(track_id) entry.cue_v2 = [c for c in (entry.cue_v2 or []) if c.hotcue != slot] + self._note("hotcue-delete") self.dirty = True # ---- beatgrid ----------------------------------------------------- @@ -419,6 +433,7 @@ class PlaylistStore: grid=GridType(bpm=grid_bpm), ) ) + self._note("grid-edit") self.dirty = True def delete_grid(self, track_id: str) -> None: @@ -427,12 +442,14 @@ class PlaylistStore: entry.cue_v2 = [ c for c in (entry.cue_v2 or []) if getattr(c, "grid", None) is None ] + self._note("grid-delete") self.dirty = True def set_lock(self, track_id: str, locked: bool) -> None: with self._lock: entry = self._entry_or_raise(track_id) entry.lock = 1 if locked else None + self._note("lock-toggle") self.dirty = True # ---- cover art ----------------------------------------------------- @@ -585,6 +602,7 @@ class PlaylistStore: pk = entry.primarykey if pk and pk.key in key_remap: pk.key = key_remap[pk.key] + self._note("remap", str(len(key_remap))) self.dirty = True return len(key_remap) @@ -609,15 +627,69 @@ class PlaylistStore: # ---- persistence --------------------------------------------------- def save(self) -> "SaveOutcome": with self._lock: - backup = self._backup() new_data = self._render() tmp = self.nml_path.with_suffix(self.nml_path.suffix + ".tmp") tmp.write_bytes(new_data) tmp.replace(self.nml_path) # Best-effort: sync the edited fields into each edited track's file. tag_results = self._sync_file_tags() - self._load() # clears dirty + _track_edits - return SaveOutcome(backup=backup, tag_results=tag_results) + # Version history: commit the saved bytes (additive — never touches the + # file we just wrote). Summary is computed before _load() clears state. + commit = history.commit(self.nml_path, new_data, self._edit_summary(), __version__) + self._load() # clears dirty + _track_edits + _edit_events + return SaveOutcome(commit=commit, tag_results=tag_results) + + def _edit_summary(self) -> str: + """A one-line, human-readable summary of this session's edits, used as the + version-history commit message (e.g. "Edited 3 tracks; renamed playlist + 'House'; set 2 hotcues").""" + parts: list[str] = [] + counts = Counter(cat for cat, _ in self._edit_events) + details: dict[str, list[str]] = {} + for cat, detail in self._edit_events: + if detail: + details.setdefault(cat, []).append(detail) + + n_tracks = len(self._track_edits.keys() | self._track_art.keys()) + if n_tracks: + parts.append(f"edited {n_tracks} track{'' if n_tracks == 1 else 's'}") + + for cat, verb in ( + ("playlist-create", "created"), + ("playlist-rename", "renamed"), + ("playlist-delete", "deleted"), + ("playlist-entries", "reordered"), + ): + names = details.get(cat, []) + if not names: + continue + if len(names) <= 2: + joined = ", ".join(f"'{n}'" for n in names) + parts.append(f"{verb} playlist{'' if len(names) == 1 else 's'} {joined}") + else: + parts.append(f"{verb} {len(names)} playlists") + + for cat, verb, sing, plur in ( + ("hotcue-set", "set", "hotcue", "hotcues"), + ("hotcue-type", "changed", "hotcue type", "hotcue types"), + ("hotcue-delete", "deleted", "hotcue", "hotcues"), + ): + n = counts.get(cat, 0) + if n: + parts.append(f"{verb} {n} {sing if n == 1 else plur}") + if counts.get("grid-edit"): + parts.append("edited beatgrid") + if counts.get("grid-delete"): + parts.append("deleted beatgrid") + if counts.get("lock-toggle"): + parts.append("toggled lock") + for detail in details.get("remap", []): + parts.append(f"remapped {detail} file paths") + + if not parts: + return "Saved changes" + summary = "; ".join(parts) + return summary[0].upper() + summary[1:] def _sync_file_tags(self) -> list["FileTagResult"]: from . import file_tags @@ -658,17 +730,3 @@ class PlaylistStore: s = restore_traktor_float_format(s, self._nml) s = format_traktor_layout(s) return s.encode("utf-8") - - def _backup(self) -> Path: - # Backups live in a `backups/` folder next to the collection, not beside - # the file itself (keeps the collection's directory clean). - stamp = time.strftime("%Y%m%d-%H%M%S", time.localtime()) - backup_dir = self.nml_path.parent / "backups" - backup_dir.mkdir(exist_ok=True) - backup = backup_dir / f"{self.nml_path.name}.{stamp}.bak" - n = 1 - while backup.exists(): - backup = backup_dir / f"{self.nml_path.name}.{stamp}-{n}.bak" - n += 1 - shutil.copy2(self.nml_path, backup) - return backup diff --git a/backend/konduktor/prefs.py b/backend/konduktor/prefs.py index 4c743a0..5981ec0 100644 --- a/backend/konduktor/prefs.py +++ b/backend/konduktor/prefs.py @@ -1,20 +1,35 @@ """Tiny persisted user-preferences store. -Kept as a self-contained JSON file that travels with the app (resolved relative -to this package, not a per-OS config dir) so it works the same on every platform -and when the app is moved. Best-effort: any I/O error degrades to "no prefs". +A self-contained JSON file in the app's per-OS user-writable data dir (see +``paths.app_data_dir``) so it survives a frozen/packaged build and works the same +on every platform. Best-effort: any I/O error degrades to "no prefs". """ from __future__ import annotations import json from pathlib import Path -# backend/userprefs.json — one level up from the package (konduktor/). -_PREFS_PATH = Path(__file__).resolve().parent.parent / "userprefs.json" +from . import paths + +# userprefs.json in the app-data dir. Older versions kept it package-relative +# (backend/userprefs.json); _migrate_legacy() copies that in once on first use. +_PREFS_PATH = paths.app_data_dir() / "userprefs.json" +_LEGACY_PREFS_PATH = Path(__file__).resolve().parent.parent / "userprefs.json" + + +def _migrate_legacy() -> None: + """One-time: if the new file is absent but a legacy package-relative one + exists, copy it into the app-data dir. Best-effort.""" + try: + if not _PREFS_PATH.exists() and _LEGACY_PREFS_PATH.exists(): + _PREFS_PATH.write_bytes(_LEGACY_PREFS_PATH.read_bytes()) + except OSError: + pass def load_prefs() -> dict: try: + _migrate_legacy() data = json.loads(_PREFS_PATH.read_text()) return data if isinstance(data, dict) else {} except (OSError, ValueError): diff --git a/backend/konduktor/schemas.py b/backend/konduktor/schemas.py index 2189ffb..067115f 100644 --- a/backend/konduktor/schemas.py +++ b/backend/konduktor/schemas.py @@ -114,11 +114,17 @@ class FileTagOutcome(BaseModel): class SaveResult(BaseModel): saved: bool - backup: str | None = None + commit: str | None = None # sha of the version-history commit (None if deduped) playlists: int file_tags: list[FileTagOutcome] = [] +class HistoryEntry(BaseModel): + id: str # commit sha + timestamp: str # ISO 8601, UTC + summary: str # human-readable edit summary + + class CuePoint(BaseModel): name: str | None = None type: int # Traktor: 0 cue, 1 fade-in, 2 fade-out, 3 load, 4 grid, 5 loop @@ -252,7 +258,7 @@ class RemapPreview(BaseModel): class RemapResult(BaseModel): rewritten: int # tracks whose LOCATION was rewritten - backup: str | None = None # path of the .bak written before the rewrite + commit: str | None = None # sha of the version-history commit for the rewrite class PrefixGroup(BaseModel): diff --git a/backend/requirements.txt b/backend/requirements.txt index ce709d3..5d63084 100644 --- a/backend/requirements.txt +++ b/backend/requirements.txt @@ -5,6 +5,11 @@ uvicorn[standard]>=0.34 pydantic>=2.11 mutagen>=1.47 # embedded audio-file tag read/write (ID3/MP4/FLAC/AIFF) python-multipart>=0.0.9 # multipart form parsing for cover-art upload +# Version-history backups: a self-contained git impl (no system git needed; +# ships prebuilt py3.14 wheels, no from-source build) + a per-OS user-writable +# app-data dir. Both bundle cleanly into the frozen sidecar. +dulwich>=0.22 +platformdirs>=4.0 # Auto Hotcues: structural segmentation (McFee/Ellis Laplacian). Pure-Python, # ~150MB; numba/llvmlite ship Python 3.14 wheels (verified). No torch/native build. librosa>=0.11 diff --git a/backend/run_tests.sh b/backend/run_tests.sh index 48c6e2c..b0b6d48 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_save_fidelity.py test_phase3.py; do +for t in test_save_fidelity.py test_phase3.py test_history.py; do echo "──────────────────────────────────────────" echo "▶ $t" echo "──────────────────────────────────────────" diff --git a/backend/test_history.py b/backend/test_history.py new file mode 100644 index 0000000..9517360 --- /dev/null +++ b/backend/test_history.py @@ -0,0 +1,113 @@ +"""Version-history tests (git-backed backups replacing the old .bak scheme). + +Runs against a COPY of the collection (never the original), with an isolated +throwaway app-data dir. Verifies: + * opening a collection records a baseline commit + * a save adds a commit with a non-empty edit summary + * a byte-identical save is deduped (no new commit) + * list_history is newest-first + * restoring an earlier version round-trips the .nml bytes AND adds a + "Restored …" commit (a forward save, not a rewind) + * clear_history removes the repo + * no .bak files are left next to the collection + +Run: `python test_history.py` in the backend venv (see run_tests.sh). +""" +import os +import shutil +import sys +import tempfile +import warnings +from pathlib import Path + +warnings.filterwarnings("ignore") + +REAL = Path(__file__).resolve().parents[1] / "collection.nml" +work_dir = Path(tempfile.mkdtemp(prefix="konduktor-history-")) +WORK = work_dir / "collection.nml" +shutil.copy2(REAL, WORK) + +os.environ["KONDUKTOR_NML"] = str(WORK) +os.environ["KONDUKTOR_DATA_DIR"] = str(work_dir / "appdata") + +from fastapi.testclient import TestClient # noqa: E402 + +from konduktor import history, main # 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 + + +client = TestClient(main.app) + + +def first_playlist(nodes): + for n in nodes: + if n["type"] == "PLAYLIST": + return n + if n.get("children"): + found = first_playlist(n["children"]) + if found: + return found + return None + + +print("== baseline on open ==") +hist = client.get("/api/history").json() +check("baseline commit exists", len(hist) == 1) +check("baseline summary set", hist and "Baseline" in hist[0]["summary"]) + +original_bytes = WORK.read_bytes() + +print("== save records a commit ==") +pl = first_playlist(client.get("/api/playlists").json()) +new_name = pl["name"] + " ✎" +r = client.patch(f"/api/playlists/{pl['id']}", json={"name": new_name}) +check("rename ok", r.status_code == 200) +res = client.post("/api/save").json() +check("save reports a commit", bool(res["commit"])) +hist = client.get("/api/history").json() +check("history grew to 2", len(hist) == 2) +check("newest is the rename", hist and new_name in hist[0]["summary"]) +check("newest-first ordering", "Baseline" in hist[-1]["summary"]) + +print("== dedup: byte-identical save makes no commit ==") +# Force a save with no real change: rename back and forth nets a re-render of the +# same content is not guaranteed; instead call history.commit directly with HEAD. +head_bytes = WORK.read_bytes() +before = len(client.get("/api/history").json()) +dup = history.commit(WORK, head_bytes, "should be deduped", "test") +after = len(client.get("/api/history").json()) +check("dedup returns None", dup is None) +check("dedup adds no commit", after == before) + +print("== restore round-trips bytes + adds a forward commit ==") +hist = client.get("/api/history").json() +baseline_id = hist[-1]["id"] +count_before = len(hist) +rr = client.post(f"/api/history/{baseline_id}/restore") +check("restore ok", rr.status_code == 200) +check("restored bytes == original", WORK.read_bytes() == original_bytes) +hist = client.get("/api/history").json() +check("restore added a commit", len(hist) == count_before + 1) +check("restore commit labelled", hist and "Restored" in hist[0]["summary"]) + +print("== read_version returns the right blob ==") +check("baseline blob == original", history.read_version(WORK, baseline_id) == original_bytes) + +print("== no .bak litter ==") +check("no .bak files next to collection", not list(work_dir.glob("*.bak"))) +check("no backups/ dir next to collection", not (work_dir / "backups").exists()) + +print("== clear_history removes the repo ==") +cr = client.delete("/api/history") +check("clear ok", cr.status_code == 200) +check("history empty after clear", client.get("/api/history").json() == []) + +sys.exit(1 if failed else 0) diff --git a/backend/test_phase3.py b/backend/test_phase3.py index c0837cb..1af1255 100644 --- a/backend/test_phase3.py +++ b/backend/test_phase3.py @@ -2,7 +2,7 @@ Runs against a COPY of the collection (never the original). Verifies: * create / add-tracks / reorder / rename / delete all work - * save creates a backup and produces a Traktor-parseable file + * save records a version-history commit and produces a Traktor-parseable file * the COLLECTION section is byte-identical after save (truly surgical) * changes survive a reload """ @@ -26,6 +26,8 @@ shutil.copy2(REAL, WORK) REAL_STAT = (REAL.stat().st_size, REAL.stat().st_mtime) os.environ["KONDUKTOR_NML"] = str(WORK) +# Isolate version history + prefs to a throwaway dir (never the real app data). +os.environ["KONDUKTOR_DATA_DIR"] = str(work_dir / "appdata") from fastapi.testclient import TestClient # noqa: E402 from traktor_nml_utils import TraktorCollection # noqa: E402 @@ -79,9 +81,11 @@ check("state is dirty before save", st["dirty"] is True) print("== save ==") res = client.post("/api/save").json() check("saved", res["saved"] is True) -backup = Path(res["backup"]) -check("backup file exists", backup.exists()) -check("backup matches original size", backup.stat().st_size == REAL.stat().st_size) +check("commit recorded", bool(res["commit"])) +hist = client.get("/api/history").json() +check("history has baseline + this save", len(hist) >= 2) +check("newest history summary non-empty", bool(hist[0]["summary"])) +check("no .bak litter next to collection", not list(work_dir.glob("*.bak"))) st = client.get("/api/state").json() check("state clean after save", st["dirty"] is False) diff --git a/backend/test_save_fidelity.py b/backend/test_save_fidelity.py index 5a63e54..4e88c3f 100644 --- a/backend/test_save_fidelity.py +++ b/backend/test_save_fidelity.py @@ -15,6 +15,7 @@ two invariants against a COPY of the real collection: Run: `python test_save_fidelity.py` in the backend venv (see run_tests.sh). """ +import os import shutil import sys import tempfile @@ -23,6 +24,10 @@ from pathlib import Path warnings.filterwarnings("ignore") +# Isolate version-history commits (triggered by every save()) to a throwaway dir +# so the tests never touch the real app-data dir. Set before importing konduktor. +os.environ["KONDUKTOR_DATA_DIR"] = tempfile.mkdtemp(prefix="konduktor-fidelity-appdata-") + REAL = Path(__file__).resolve().parents[1] / "collection.nml" from konduktor.collection_service import CollectionService # noqa: E402 diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 66729f1..c0047aa 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -16,6 +16,7 @@ import { CollectionPicker } from './components/CollectionPicker' import { ContextMenu } from './components/ContextMenu' import { EditTagsDialog } from './components/EditTagsDialog' import { PathMappingDialog } from './components/PathMappingDialog' +import { HistoryPanel } from './components/HistoryPanel' import { PrepStrip } from './components/PrepStrip' function applyFilters(tracks: Track[], f: Filters): Track[] { @@ -49,6 +50,7 @@ export default function App() { const [menu, setMenu] = useState<{ track: Track; x: number; y: number } | null>(null) const [editing, setEditing] = useState(null) const [showPaths, setShowPaths] = useState(false) + const [showHistory, setShowHistory] = useState(false) const [prepTrack, setPrepTrack] = useState(null) const [playRequest, setPlayRequest] = useState(0) // bump → deck loads & auto-plays @@ -267,12 +269,24 @@ export default function App() { onError={onError} /> )} + {showHistory && ( + setShowHistory(false)} + onNotify={notify} + onError={onError} + /> + )} {/* Prep strip spans the top of the window; the library sits below it. */}
- + setShowHistory(true)} + />
{/* Search / filters / column settings — always visible. */} diff --git a/frontend/src/api.ts b/frontend/src/api.ts index 99282ac..0f65470 100644 --- a/frontend/src/api.ts +++ b/frontend/src/api.ts @@ -154,10 +154,16 @@ export interface FsListing { export interface SaveResult { saved: boolean - backup: string | null + commit: string | null playlists: number } +export interface HistoryEntry { + id: string + timestamp: string + summary: string +} + export interface PathMapping { from: string to: string @@ -178,7 +184,7 @@ export interface RemapPreview { export interface RemapResult { rewritten: number - backup: string | null + commit: string | null } export interface PrefixSuggestions { @@ -249,7 +255,7 @@ export const api = { getJSON( `/api/collection/path-mapping/preview?from=${encodeURIComponent(from)}&to=${encodeURIComponent(to)}`, ), - // Write-back: permanently rewrite matching LOCATIONs in the .nml (backup-first). + // Write-back: permanently rewrite matching LOCATIONs in the .nml (committed to history). remapPaths: (from: string, to: string) => send('POST', '/api/collection/remap-paths', { from, to }), @@ -283,6 +289,13 @@ export const api = { patchPrefs: (patch: Record) => send>('PATCH', '/api/prefs', patch), save: () => send('POST', '/api/save'), + + // ---- version history ---- + history: () => getJSON('/api/history'), + restoreVersion: (id: string) => + send('POST', `/api/history/${id}/restore`), + clearHistory: () => send<{ status: string }>('DELETE', '/api/history'), + editTrack: (trackId: string, fields: Record) => send<{ status: string }>('PATCH', '/api/tracks', { track_id: trackId, fields }), artUrl: (trackId: string) => diff --git a/frontend/src/components/HistoryPanel.tsx b/frontend/src/components/HistoryPanel.tsx new file mode 100644 index 0000000..85ad1f2 --- /dev/null +++ b/frontend/src/components/HistoryPanel.tsx @@ -0,0 +1,192 @@ +import { useState } from 'react' +import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' +import { api, type HistoryEntry } from '../api' +import type { ToastMsg } from './Toast' + +interface Props { + onClose: () => void + onNotify: (kind: ToastMsg['kind'], text: string) => void + onError: (msg: string) => void +} + +function formatWhen(iso: string): string { + const d = new Date(iso) + if (Number.isNaN(d.getTime())) return iso + return d.toLocaleString(undefined, { + year: 'numeric', + month: 'short', + day: 'numeric', + hour: '2-digit', + minute: '2-digit', + }) +} + +/** + * Version history browser for the current collection. Every save is a commit in + * a purely-local git repo (see backend history.py); this lists them newest-first + * and lets the user restore any past version (written back as a new forward save) + * or wipe the entire history. Restore overwrites the collection on disk, so the + * user must close Traktor first (it rewrites the .nml on exit). + */ +export function HistoryPanel({ onClose, onNotify, onError }: Props) { + const qc = useQueryClient() + const history = useQuery({ queryKey: ['history'], queryFn: api.history }) + const [confirmingId, setConfirmingId] = useState(null) + const [clearing, setClearing] = useState(false) + + const restore = useMutation({ + mutationFn: (id: string) => api.restoreVersion(id), + onSuccess: () => { + // A restore swaps the whole collection — refetch everything. + qc.invalidateQueries() + onNotify('success', 'Restored — the library now reflects that version.') + setConfirmingId(null) + onClose() + }, + onError: (e: Error) => { + onError(e.message) + setConfirmingId(null) + }, + }) + + const clear = useMutation({ + mutationFn: () => api.clearHistory(), + onSuccess: () => { + qc.invalidateQueries({ queryKey: ['history'] }) + onNotify('success', 'Version history deleted.') + setClearing(false) + }, + onError: (e: Error) => { + onError(e.message) + setClearing(false) + }, + }) + + const entries = history.data ?? [] + + return ( +
+
e.stopPropagation()} + > +
+
Version History
+
+ Every save is a restorable version of this collection. Close Traktor before + restoring — it overwrites the collection on exit. +
+
+ +
+ {history.isLoading ? ( +
Loading…
+ ) : entries.length === 0 ? ( +
+ No versions yet. Saving a change records the first one. +
+ ) : ( +
    + {entries.map((e: HistoryEntry, i: number) => { + const isCurrent = i === 0 + const isConfirming = confirmingId === e.id + return ( +
  • +
    +
    + {e.summary} + {isCurrent && ( + + current + + )} +
    +
    + {formatWhen(e.timestamp)} · {e.id.slice(0, 8)} +
    +
    + {isConfirming ? ( +
    + + +
    + ) : ( + + )} +
  • + ) + })} +
+ )} +
+ + {/* Destructive: wipe the whole history. */} +
+ {clearing ? ( +
+ + Permanently delete ALL {entries.length} version + {entries.length === 1 ? '' : 's'}? This can't be undone. + +
+ + +
+
+ ) : ( +
+ + +
+ )} +
+
+
+ ) +} diff --git a/frontend/src/components/PathMappingDialog.tsx b/frontend/src/components/PathMappingDialog.tsx index d46f1f9..3785031 100644 --- a/frontend/src/components/PathMappingDialog.tsx +++ b/frontend/src/components/PathMappingDialog.tsx @@ -87,7 +87,7 @@ export function PathMappingDialog({ onClose, onNotify, onError }: Props) { onNotify( 'success', `Rewrote ${res.rewritten} track path${res.rewritten === 1 ? '' : 's'}.` + - (res.backup ? ` Backup: ${res.backup.split('/').pop()}` : ''), + (res.commit ? ` Version: ${res.commit.slice(0, 8)}` : ''), ) onClose() } @@ -195,8 +195,8 @@ export function PathMappingDialog({ onClose, onNotify, onError }: Props) {
Make permanent

- Rewrites the matching file paths directly in the collection (a backup is - written first). Use this only when you've moved the library for good — it + Rewrites the matching file paths directly in the collection (saved to + version history). Use this only when you've moved the library for good — it bakes in this machine's paths and will break the collection on other machines/OSes.

diff --git a/frontend/src/components/SaveBar.tsx b/frontend/src/components/SaveBar.tsx index 1be5a09..95a2512 100644 --- a/frontend/src/components/SaveBar.tsx +++ b/frontend/src/components/SaveBar.tsx @@ -7,7 +7,7 @@ interface Props { } // Bottom-of-sidebar save control. Shows unsaved-changes state and writes to the -// NML (backup-first). On-disk saving is gated server-side by KONDUKTOR_ALLOW_WRITE. +// NML; every save is recorded in the collection's version history. export function SaveBar({ onError }: Props) { const qc = useQueryClient() const [justSaved, setJustSaved] = useState(null) @@ -17,9 +17,9 @@ export function SaveBar({ onError }: Props) { mutationFn: api.save, onSuccess: (res) => { qc.invalidateQueries({ queryKey: ['state'] }) - if (res.saved && res.backup) { - const name = res.backup.split('/').pop() - setJustSaved(`Saved · backup ${name}`) + qc.invalidateQueries({ queryKey: ['history'] }) + if (res.saved && res.commit) { + setJustSaved(`Saved · version ${res.commit.slice(0, 8)}`) setTimeout(() => setJustSaved(null), 6000) } }, diff --git a/frontend/src/components/Sidebar.tsx b/frontend/src/components/Sidebar.tsx index db2c806..a7d014c 100644 --- a/frontend/src/components/Sidebar.tsx +++ b/frontend/src/components/Sidebar.tsx @@ -9,6 +9,7 @@ interface Props { source: Source onSelect: (s: Source) => void onError: (msg: string) => void + onOpenHistory: () => void } const icons: Record = { @@ -157,7 +158,7 @@ function NodeRow({ ) } -export function Sidebar({ source, onSelect, onError }: Props) { +export function Sidebar({ source, onSelect, onError, onOpenHistory }: Props) { const qc = useQueryClient() const [creating, setCreating] = useState(false) const [newName, setNewName] = useState('') @@ -245,6 +246,14 @@ export function Sidebar({ source, onSelect, onError }: Props) { ))}
+ + ) From 41111c7c4c03d90453cccd26cc1a11c886811566 Mon Sep 17 00:00:00 2001 From: Benjamin Hardy Date: Thu, 9 Jul 2026 10:43:53 +0200 Subject: [PATCH 2/4] Improved collection version naming --- backend/konduktor/playlist_store.py | 117 +++++++++++++++++++--------- 1 file changed, 79 insertions(+), 38 deletions(-) diff --git a/backend/konduktor/playlist_store.py b/backend/konduktor/playlist_store.py index c7ca624..761607b 100644 --- a/backend/konduktor/playlist_store.py +++ b/backend/konduktor/playlist_store.py @@ -20,7 +20,6 @@ from __future__ import annotations import threading import uuid as uuidlib -from collections import Counter from dataclasses import dataclass from pathlib import Path @@ -92,13 +91,14 @@ class PlaylistStore: self._track_edits: dict[str, set[str]] = {} # track_id -> (image_bytes, mime) of staged replacement cover art self._track_art: dict[str, tuple[bytes, str]] = {} - # (category, detail) events accumulated this session -> commit summary - self._edit_events: list[tuple[str, str | None]] = [] + # (category, detail, track_id) events this session -> commit summary. + # track_id lets prep edits report how many distinct tracks were affected. + self._edit_events: list[tuple[str, str | None, str | None]] = [] self.dirty = False - def _note(self, category: str, detail: str | None = None) -> None: + def _note(self, category: str, detail: str | None = None, track_id: str | None = None) -> None: """Record a human-meaningful edit for the next commit's summary.""" - self._edit_events.append((category, detail)) + self._edit_events.append((category, detail, track_id)) def _root(self) -> Nodetype: node = self._nml.playlists.node if self._nml.playlists else None @@ -339,7 +339,9 @@ class PlaylistStore: grid=None, ) ) - self._note("hotcue-set") + # "add" only when it's a genuinely new hotcue; repositioning/retyping + # an existing slot is a "modify" (keeps the net add/remove count honest). + self._note("hotcue", "modify" if existing is not None else "add", track_id) self.dirty = True def place_hotcues( @@ -376,14 +378,16 @@ class PlaylistStore: if cue is None: raise PlaylistError(f"Hotcue {slot} is not set") cue.type = cue_type - self._note("hotcue-type") + self._note("hotcue", "modify", track_id) self.dirty = True def delete_hotcue(self, track_id: str, slot: int) -> None: with self._lock: entry = self._entry_or_raise(track_id) - entry.cue_v2 = [c for c in (entry.cue_v2 or []) if c.hotcue != slot] - self._note("hotcue-delete") + before = entry.cue_v2 or [] + entry.cue_v2 = [c for c in before if c.hotcue != slot] + if len(entry.cue_v2) != len(before): # only count an actual removal + self._note("hotcue", "delete", track_id) self.dirty = True # ---- beatgrid ----------------------------------------------------- @@ -433,7 +437,7 @@ class PlaylistStore: grid=GridType(bpm=grid_bpm), ) ) - self._note("grid-edit") + self._note("grid", "edit", track_id) self.dirty = True def delete_grid(self, track_id: str) -> None: @@ -442,14 +446,14 @@ class PlaylistStore: entry.cue_v2 = [ c for c in (entry.cue_v2 or []) if getattr(c, "grid", None) is None ] - self._note("grid-delete") + self._note("grid", "delete", track_id) self.dirty = True def set_lock(self, track_id: str, locked: bool) -> None: with self._lock: entry = self._entry_or_raise(track_id) entry.lock = 1 if locked else None - self._note("lock-toggle") + self._note("lock", "on" if locked else "off", track_id) self.dirty = True # ---- cover art ----------------------------------------------------- @@ -642,25 +646,34 @@ class PlaylistStore: def _edit_summary(self) -> str: """A one-line, human-readable summary of this session's edits, used as the version-history commit message (e.g. "Edited 3 tracks; renamed playlist - 'House'; set 2 hotcues").""" + 'House'; added 6 hotcues; edited beatgrid on 2 tracks"). + + Prep edits are collapsed to meaningful aggregates rather than raw op + counts: hotcues report their NET change (created − removed), and beatgrid/ + lock edits report how many distinct tracks were affected — so tweaking one + grid ten times reads as "1 track", not "10 edits".""" parts: list[str] = [] - counts = Counter(cat for cat, _ in self._edit_events) - details: dict[str, list[str]] = {} - for cat, detail in self._edit_events: - if detail: - details.setdefault(cat, []).append(detail) - n_tracks = len(self._track_edits.keys() | self._track_art.keys()) - if n_tracks: - parts.append(f"edited {n_tracks} track{'' if n_tracks == 1 else 's'}") + def tracks(n: int) -> str: + return f"{n} track{'' if n == 1 else 's'}" + # --- track metadata + cover art (already counted per-track) --- + n_meta = len(self._track_edits.keys() | self._track_art.keys()) + if n_meta: + parts.append(f"edited {tracks(n_meta)}") + + # --- playlists (name-bearing) --- + pl_names: dict[str, list[str]] = {} + for cat, detail, _tid in self._edit_events: + if cat.startswith("playlist-") and detail: + pl_names.setdefault(cat, []).append(detail) for cat, verb in ( ("playlist-create", "created"), ("playlist-rename", "renamed"), ("playlist-delete", "deleted"), ("playlist-entries", "reordered"), ): - names = details.get(cat, []) + names = pl_names.get(cat, []) if not names: continue if len(names) <= 2: @@ -669,22 +682,50 @@ class PlaylistStore: else: parts.append(f"{verb} {len(names)} playlists") - for cat, verb, sing, plur in ( - ("hotcue-set", "set", "hotcue", "hotcues"), - ("hotcue-type", "changed", "hotcue type", "hotcue types"), - ("hotcue-delete", "deleted", "hotcue", "hotcues"), - ): - n = counts.get(cat, 0) - if n: - parts.append(f"{verb} {n} {sing if n == 1 else plur}") - if counts.get("grid-edit"): - parts.append("edited beatgrid") - if counts.get("grid-delete"): - parts.append("deleted beatgrid") - if counts.get("lock-toggle"): - parts.append("toggled lock") - for detail in details.get("remap", []): - parts.append(f"remapped {detail} file paths") + # --- hotcues: net change in count, scoped by how many tracks were touched --- + hc_add = hc_del = 0 + hc_tracks: set[str] = set() + grid_edit: set[str] = set() + grid_del: set[str] = set() + lock_on: set[str] = set() + lock_off: set[str] = set() + for cat, detail, tid in self._edit_events: + if cat == "hotcue": + if tid: + hc_tracks.add(tid) + if detail == "add": + hc_add += 1 + elif detail == "delete": + hc_del += 1 + elif cat == "grid": + (grid_edit if detail == "edit" else grid_del).add(tid or "") + elif cat == "lock": + (lock_on if detail == "on" else lock_off).add(tid or "") + + if hc_tracks: + net = hc_add - hc_del + scope = f" across {tracks(len(hc_tracks))}" if len(hc_tracks) > 1 else "" + if net > 0: + parts.append(f"added {net} hotcue{'' if net == 1 else 's'}{scope}") + elif net < 0: + parts.append(f"removed {-net} hotcue{'' if -net == 1 else 's'}{scope}") + else: # net zero but there was activity (moves / retypes / add-then-delete) + parts.append(f"adjusted hotcues{scope}") + + # --- beatgrids & lock: per-track counts --- + if grid_edit: + parts.append(f"edited beatgrid on {tracks(len(grid_edit))}") + if grid_del: + parts.append(f"deleted beatgrid on {tracks(len(grid_del))}") + if lock_on: + parts.append(f"locked {tracks(len(lock_on))}") + if lock_off: + parts.append(f"unlocked {tracks(len(lock_off))}") + + # --- path remap --- + for cat, detail, _tid in self._edit_events: + if cat == "remap" and detail: + parts.append(f"remapped {detail} file paths") if not parts: return "Saved changes" From f19a662bd3ec63c76783da0a2399e54ee3ee715c Mon Sep 17 00:00:00 2001 From: Benjamin Hardy Date: Thu, 9 Jul 2026 13:19:16 +0200 Subject: [PATCH 3/4] Improved naming scheme for backup snapshot names --- frontend/src/components/HistoryPanel.tsx | 30 +++++++++++++++---- frontend/src/components/PathMappingDialog.tsx | 2 +- frontend/src/components/Sidebar.tsx | 5 ++-- 3 files changed, 27 insertions(+), 10 deletions(-) diff --git a/frontend/src/components/HistoryPanel.tsx b/frontend/src/components/HistoryPanel.tsx index 85ad1f2..f312c2b 100644 --- a/frontend/src/components/HistoryPanel.tsx +++ b/frontend/src/components/HistoryPanel.tsx @@ -21,6 +21,17 @@ function formatWhen(iso: string): string { }) } +// Backend joins the summary's parts with "; " (e.g. "Added 6 hotcues; edited +// beatgrid on 3 tracks"). Split them back out so each renders as its own chip +// that wraps — far more scannable than one truncated run-on line. +function summaryChips(summary: string): string[] { + return summary + .split('; ') + .map((p) => p.trim()) + .filter(Boolean) + .map((p) => p.charAt(0).toUpperCase() + p.slice(1)) +} + /** * Version history browser for the current collection. Every save is a commit in * a purely-local git repo (see backend history.py); this lists them newest-first @@ -96,18 +107,25 @@ export function HistoryPanel({ onClose, onNotify, onError }: Props) { return (
  • -
    - {e.summary} +
    {isCurrent && ( - + current )} + {summaryChips(e.summary).map((chip, ci) => ( + + {chip} + + ))}
    -
    +
    {formatWhen(e.timestamp)} · {e.id.slice(0, 8)}
    @@ -132,7 +150,7 @@ export function HistoryPanel({ onClose, onNotify, onError }: Props) { onClick={() => setConfirmingId(e.id)} disabled={isCurrent} title={isCurrent ? 'This is the current version' : 'Restore this version'} - className="shrink-0 rounded-md border border-line px-2.5 py-1 text-xs text-muted opacity-0 transition-opacity hover:bg-ink-800 hover:text-text group-hover:opacity-100 disabled:cursor-not-allowed disabled:opacity-0" + className="mt-0.5 shrink-0 rounded-md border border-line px-2.5 py-1 text-xs text-muted opacity-0 transition-opacity hover:bg-ink-800 hover:text-text group-hover:opacity-100 disabled:cursor-not-allowed disabled:opacity-0" > Restore diff --git a/frontend/src/components/PathMappingDialog.tsx b/frontend/src/components/PathMappingDialog.tsx index 3785031..1f2664f 100644 --- a/frontend/src/components/PathMappingDialog.tsx +++ b/frontend/src/components/PathMappingDialog.tsx @@ -281,7 +281,7 @@ function FolderBrowser({ {data?.path ?? '…'}
    -
    +
    {data?.dirs.length ? ( data.dirs.map((d) => ( From ed2b72c749b56f644f4943519e08717127467270 Mon Sep 17 00:00:00 2001 From: Benjamin Hardy Date: Thu, 9 Jul 2026 13:45:06 +0200 Subject: [PATCH 4/4] Implemented update checking --- CLAUDE.md | 13 +- frontend/package-lock.json | 15 +- frontend/package.json | 3 +- frontend/src-tauri/capabilities/default.json | 3 +- frontend/src/components/UpdateDialog.tsx | 211 +++++++++++++++++++ frontend/src/main.tsx | 3 + frontend/src/vite-env.d.ts | 4 + frontend/vite.config.ts | 8 + 8 files changed, 254 insertions(+), 6 deletions(-) create mode 100644 frontend/src/components/UpdateDialog.tsx create mode 100644 frontend/src/vite-env.d.ts diff --git a/CLAUDE.md b/CLAUDE.md index fa98879..743f934 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -64,7 +64,15 @@ Two independent apps that talk over HTTP: state every commit → infinite re-render loop. Keep that reference stable. `SelectionBar` (bulk add-to-playlist), `ContextMenu` + `EditTagsDialog` (right-click → multi-field metadata + album-art edit), `StatusBar`, - `RatingStars` (read-only, or click-to-set when given `onChange`), `Toast`. + `RatingStars` (read-only, or click-to-set when given `onChange`), `Toast`, + `UpdateDialog` (`UpdateCheck`, mounted in `main.tsx` beside `App` so it shows + even on the picker screen: on startup fetches the latest GitHub release and, + if its tag's **semver part** is newer than `__APP_VERSION__` — build-number + `-b` bumps don't count — shows an update dialog with the release's + "What's Changed" bullets; Download opens the release page in the system + browser via `@tauri-apps/plugin-shell` `open` — falls back to `window.open` + outside Tauri; "Skip this version" persists `skippedUpdateVersion` to + userprefs via `/api/prefs`; all failures are silent). - **Prep strip** (DJ deck across the top of the window): `PrepStrip` owns it — transport (play/pause, CUE), two waveforms (`MainWaveform` scrolling+zoomable — its zoom is owned by `PrepStrip` so it survives track switches and persists, @@ -171,6 +179,9 @@ that number and nothing else — everything derives from it: the PyInstaller root via `sys._MEIPASS`, added in `konduktor-sidecar.spec`). `main.py` uses this for the FastAPI `version`. Falls back to `"0.0.0"` if not found (cosmetic, must never crash startup). +- **Frontend / update check** — `vite.config.ts` bakes it in at build time as + the `__APP_VERSION__` global (declared in `src/vite-env.d.ts`); `UpdateCheck` + compares it against the latest GitHub release tag on startup. - **CI release** — `.github/workflows/build.yml` reads it with `jq .version frontend/package.json` and tags each push `v-b` (release name `Konduktor v-b`). diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 34f1ba3..0ea190b 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -1,12 +1,12 @@ { "name": "frontend", - "version": "0.0.0", + "version": "0.1.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "frontend", - "version": "0.0.0", + "version": "0.1.1", "dependencies": { "@dnd-kit/core": "^6.3.1", "@dnd-kit/modifiers": "^9.0.0", @@ -15,6 +15,7 @@ "@tanstack/react-query": "^5.101.2", "@tanstack/react-table": "^8.21.3", "@tanstack/react-virtual": "^3.14.5", + "@tauri-apps/plugin-shell": "^2.3.5", "react": "^19.2.7", "react-dom": "^19.2.7" }, @@ -1229,7 +1230,6 @@ "version": "2.11.1", "resolved": "https://registry.npmjs.org/@tauri-apps/api/-/api-2.11.1.tgz", "integrity": "sha512-M2FPuYND2m+wh5hfW9ZpSdxMPdEJovPBWwoHJmwUpysTYNHaOkVFN419m/K0LIgjb/7KU2vBgsUepJWugQCvAA==", - "dev": true, "license": "Apache-2.0 OR MIT", "funding": { "type": "opencollective", @@ -1468,6 +1468,15 @@ "node": ">= 10" } }, + "node_modules/@tauri-apps/plugin-shell": { + "version": "2.3.5", + "resolved": "https://registry.npmjs.org/@tauri-apps/plugin-shell/-/plugin-shell-2.3.5.tgz", + "integrity": "sha512-jewtULhiQ7lI7+owCKAjc8tYLJr92U16bPOeAa472LHJdgaibLP83NcfAF2e+wkEcA53FxKQAZ7byDzs2eeizg==", + "license": "MIT OR Apache-2.0", + "dependencies": { + "@tauri-apps/api": "^2.10.1" + } + }, "node_modules/@tybys/wasm-util": { "version": "0.10.3", "resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.3.tgz", diff --git a/frontend/package.json b/frontend/package.json index 6a56ba6..4163b5c 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,7 +1,7 @@ { "name": "frontend", "private": true, - "version": "0.1.1", + "version": "0.1.2", "type": "module", "scripts": { "dev": "vite", @@ -17,6 +17,7 @@ "@tanstack/react-query": "^5.101.2", "@tanstack/react-table": "^8.21.3", "@tanstack/react-virtual": "^3.14.5", + "@tauri-apps/plugin-shell": "^2.3.5", "react": "^19.2.7", "react-dom": "^19.2.7" }, diff --git a/frontend/src-tauri/capabilities/default.json b/frontend/src-tauri/capabilities/default.json index c135d7f..9f68e87 100644 --- a/frontend/src-tauri/capabilities/default.json +++ b/frontend/src-tauri/capabilities/default.json @@ -6,6 +6,7 @@ "main" ], "permissions": [ - "core:default" + "core:default", + "shell:allow-open" ] } diff --git a/frontend/src/components/UpdateDialog.tsx b/frontend/src/components/UpdateDialog.tsx new file mode 100644 index 0000000..97acf11 --- /dev/null +++ b/frontend/src/components/UpdateDialog.tsx @@ -0,0 +1,211 @@ +import { useState } from 'react' +import { useQuery, useQueryClient } from '@tanstack/react-query' +import { api } from '../api' + +/** + * Startup update check against GitHub Releases. + * + * Compares the running version (`__APP_VERSION__`, baked from package.json at + * build time) with the latest release's tag (`v-b` — only the + * semver part counts, so a new build of the same version is NOT an update). + * Failures are silent: an update check must never nag about itself. + * "Skip this version" persists `skippedUpdateVersion` to userprefs.json via + * the prefs API, keyed by the semver part, so a later version re-triggers. + */ + +const REPO = 'MrPatben8/konduktor' + +interface GithubRelease { + tag_name: string + html_url: string + body: string | null +} + +async function fetchLatestRelease(): Promise { + const res = await fetch(`https://api.github.com/repos/${REPO}/releases/latest`, { + headers: { Accept: 'application/vnd.github+json' }, + }) + if (!res.ok) throw new Error(`GitHub responded ${res.status}`) + return res.json() +} + +/** The semver triple at the start of a version/tag string ("v0.1.2-b7" → [0,1,2]). */ +function parseVersion(s: string): [number, number, number] | null { + const m = /^v?(\d+)\.(\d+)\.(\d+)/.exec(s.trim()) + return m ? [Number(m[1]), Number(m[2]), Number(m[3])] : null +} + +function isNewer(a: [number, number, number], b: [number, number, number]): boolean { + for (let i = 0; i < 3; i++) { + if (a[i] !== b[i]) return a[i] > b[i] + } + return false +} + +/** + * The "What's Changed" bullet lines from an auto-generated release body + * (section ends at the next heading or the Full Changelog link). If the + * section is missing (hand-written notes), fall back to the whole body. + * The auto-generated "by @user in " credit suffix is stripped. + */ +function whatsChanged(body: string | null): string[] { + if (!body) return [] + const lines = body.split(/\r?\n/) + const start = lines.findIndex((l) => /^#{2,4}\s+what'?s changed/i.test(l.trim())) + const out: string[] = [] + for (const raw of lines.slice(start + 1)) { + const line = raw.trim() + if (start !== -1 && (/^#{1,4}\s/.test(line) || line.startsWith('**Full Changelog**'))) break + if (line) { + out.push( + line.replace(/^[*-]\s+/, '').replace(/\s+by\s+@[\w-]+\s+in\s+https?:\/\/\S+$/i, ''), + ) + } + } + return out +} + +/** Open a URL in the system browser (Tauri shell-open in the desktop app). */ +async function openExternal(url: string) { + if ('__TAURI_INTERNALS__' in window) { + try { + const { open } = await import('@tauri-apps/plugin-shell') + await open(url) + return + } catch { + // fall through to window.open + } + } + window.open(url, '_blank', 'noopener') +} + +/** Render a changelog line, turning bare URLs into links (PR URLs as #N). */ +function ChangelogLine({ text }: { text: string }) { + const parts = text.split(/(https?:\/\/\S+)/g) + return ( + <> + {parts.map((part, i) => { + if (!/^https?:\/\//.test(part)) return {part} + const pr = /\/pull\/(\d+)/.exec(part) + return ( + { + e.preventDefault() + openExternal(part) + }} + className="text-accent hover:underline" + > + {pr ? `#${pr[1]}` : part} + + ) + })} + + ) +} + +export function UpdateCheck() { + const qc = useQueryClient() + const [dismissed, setDismissed] = useState(false) + const [skipVersion, setSkipVersion] = useState(false) + + const release = useQuery({ + queryKey: ['latestRelease'], + queryFn: fetchLatestRelease, + staleTime: Infinity, + retry: false, + }) + // Shares App's ['prefs'] cache entry. + const prefs = useQuery({ queryKey: ['prefs'], queryFn: api.getPrefs }) + + const latest = release.data + const latestVer = latest ? parseVersion(latest.tag_name) : null + const currentVer = parseVersion(__APP_VERSION__) + const latestSemver = latestVer?.join('.') + const updateAvailable = !!(latestVer && currentVer && isNewer(latestVer, currentVer)) + const skipped = !!latestSemver && prefs.data?.skippedUpdateVersion === latestSemver + + // Wait for prefs before showing so a skipped version never flashes the dialog. + if (dismissed || !updateAvailable || !latest || !prefs.isSuccess || skipped) return null + + const close = () => { + if (skipVersion && latestSemver) { + api + .patchPrefs({ skippedUpdateVersion: latestSemver }) + .then((p) => qc.setQueryData(['prefs'], p)) + .catch(() => {}) + } + setDismissed(true) + } + + const download = () => { + openExternal(latest.html_url) + setDismissed(true) + } + + const changes = whatsChanged(latest.body) + + return ( +
    +
    e.stopPropagation()} + > +
    +
    Update available
    +
    + Konduktor {latest.tag_name} is out — you have v + {__APP_VERSION__}. +
    +
    + +
    +
    What's changed
    + {changes.length ? ( +
      + {changes.map((line, i) => ( +
    • + • + + + +
    • + ))} +
    + ) : ( +
    No release notes.
    + )} +
    + +
    + +
    + + +
    +
    +
    + ) +} diff --git a/frontend/src/main.tsx b/frontend/src/main.tsx index ee87744..9b01eb6 100644 --- a/frontend/src/main.tsx +++ b/frontend/src/main.tsx @@ -3,6 +3,7 @@ import { createRoot } from 'react-dom/client' import { QueryClient, QueryClientProvider } from '@tanstack/react-query' import './index.css' import App from './App.tsx' +import { UpdateCheck } from './components/UpdateDialog.tsx' const queryClient = new QueryClient({ defaultOptions: { @@ -17,6 +18,8 @@ createRoot(document.getElementById('root')!).render( + {/* Mounted beside App so the update dialog shows even on the picker screen. */} + , ) diff --git a/frontend/src/vite-env.d.ts b/frontend/src/vite-env.d.ts new file mode 100644 index 0000000..953927d --- /dev/null +++ b/frontend/src/vite-env.d.ts @@ -0,0 +1,4 @@ +/// + +/** The app version from package.json, injected by vite.config.ts `define`. */ +declare const __APP_VERSION__: string diff --git a/frontend/vite.config.ts b/frontend/vite.config.ts index 45e215c..c274c75 100644 --- a/frontend/vite.config.ts +++ b/frontend/vite.config.ts @@ -1,9 +1,17 @@ +import { readFileSync } from 'node:fs' import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' +// The app's own version, from the single source of truth (package.json), baked +// in at build time as __APP_VERSION__ (used by the startup update check). +const pkg = JSON.parse(readFileSync(new URL('./package.json', import.meta.url), 'utf8')) + // Proxy /api to the FastAPI backend so the frontend can use same-origin fetches. export default defineConfig({ plugins: [react()], + define: { + __APP_VERSION__: JSON.stringify(pkg.version), + }, server: { port: 5173, proxy: {