Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
keep full music track render history with cards + remix modal
[._.]/ Adam Eivye19a5a86a7f4
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 9d317f9014..cbd96b3075 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -31,6 +31,7 @@## Fixed+- **AudioLDM2 music generation no longer crashes on current transformers.** Rendering with the AudioLDM2 engine failed mid-generation with `AttributeError: 'GPT2Model' object has no attribute '_update_model_kwargs_for_generation'`. AudioLDM2's internal language model is a bare `GPT2Model` (the pipeline reads its hidden states), and diffusers' `generate_language_model` drives it by hand using generation helpers that used to live on every `PreTrainedModel` — but transformers ≥4.50 decoupled `GenerationMixin`, so non-generative base models like `GPT2Model` no longer carry them, leaving diffusers calling a method that no longer exists. The AudioLDM2 sidecar now re-binds the missing helpers (`_update_model_kwargs_for_generation`, `_get_initial_cache_position`) from `GenerationMixin` onto the language model after loading the pipeline — keeping the runtime on a current transformers instead of pinning an EOL release, and a no-op on older transformers where the methods are already present. (`scripts/generate_audioldm2.py`)- **Client test suite no longer floods CI with React "not wrapped in act(...)" warnings.** Across eight component/page suites, state updates were being driven outside `act()` — hand-fired mock-EventSource frames (`emit`/`fail`), raw DOM `.blur()` calls, manually-invoked tracker callbacks, and resolved in-flight gates whose follow-up `setState` landed after the test body returned (plus a few synchronous tests whose mount-time fetches resolved late). These surfaced only under CI's verbose reporter (the default reporter hides console output), so they were invisible locally. Each driving call is now wrapped in `act()` (or switched to `fireEvent`, which wraps internally), and synchronous tests that mount components with async effects now flush inside `act()`. The full client suite (2497 tests) runs clean with zero act warnings. (`PipelineManuscriptEditor`, `Layout`, `WidgetSuggestions`, `ApiAccessTab`, `PitchTuner`, `SongTraining`, `AudioStage`, `LocalLlmPlayground` test suites)- **Deleting a generated image or video now asks for confirmation.** The trash button on image/video preview cards (the Image Gen page's recent-renders strip and the Media History grid) deleted the asset immediately on a single click, with no undo. It now arms an inline confirm row ("Delete this image?" / "Delete this video?" with Delete + Cancel) so an accidental click can't wipe a render. Fixed once in the shared `MediaCard` component, so both surfaces are covered. (`client/src/components/media/MediaCard.jsx`)- **Codex TUI CoS agents no longer get stuck in the sandbox.** The shipped Codex TUI provider pinned `--ask-for-approval never`, which silences approval prompts but leaves Codex's *sandbox* at its default (`workspace-write`) — so headless agents couldn't reach the network (`gh`/`npm`/`git fetch` failed) and could still hit surprise escalation prompts mid-run. Because an explicit `--ask-for-approval` flag also suppressed the auto-injected full-bypass, the shipped default actively defeated the headless posture the CLI codex path already uses. The default now ships `--dangerously-bypass-approvals-and-sandbox` (approvals off + sandbox off + network on), and migration 121 rewrites existing installs whose args still match the old default — custom Codex flags are left untouched.@@ -68,6 +69,7 @@- **On-device music generation in the Track editor.** Generate a track's audio locally from its prompt (+ lyrics) — no API key, no network at inference. Three OSS engines behind one picker: **MusicGen** (MLX) and **AudioLDM2** (diffusers) for instrumental/ambient beds, and **ACE-Step** (`INSTALL_ACESTEP=1 bash scripts/setup-image-video.sh`) for full songs *with vocals*, which uses the track's lyrics as conditioning. Engines whose opt-in venv isn't installed show their install hint and gate the Generate button (same posture as the FLUX.2 image venv). The generated WAV lands in the shared music library and attaches to the track with its engine/model/duration metadata.- **Install additional audio models from HuggingFace.** The Track editor's generator panel can pull extra checkpoints (e.g. a larger MusicGen, an AudioLDM2 variant) straight from HuggingFace into the local cache — same streamed-download path as the image/video model installer — and they become selectable for generation immediately. User-installed models persist in `data/audio-models.json` and can be removed from the same panel.+- **Every track render is now kept and shown as a card (not just the latest).** A track used to store a single audio pointer, so re-generating (or uploading a new file) silently overwrote the previous take with no way back. Tracks now keep a full **render history** (`track.renders[]`): each generated or uploaded take is a card in the editor showing its prompt, engine, model, and duration, with an inline player. Click **Details** to open a modal with the complete prompt + conditioning lyrics, **Use** to make any past take the active one (re-points playback + the album/track audio), **Remix** to seed the generator with that take's settings for a new render, plus per-card download and delete (deleting a take leaves its bytes in the shared library — they may be shared). Existing tracks are backfilled automatically on first read: the current audio becomes the first card, no migration needed. The history federates to sync peers (every render's audio rides the asset manifest, version-gated as `tracks` schema v2 so an older peer can't silently strip it).- **"Audio & Music" category in the Local LLM model installer (Settings → Local LLM).** The Hugging Face model search gained an audio/music output category that surfaces generation models (MusicGen, AudioLDM2, ACE-Step, Stable Audio, Magenta…) — the GGUF filter is relaxed for this category since audio models aren't GGUF. Installing an audio model downloads it into the HF cache and registers it in the **same** shared audio-model registry the Music studio reads (`data/audio-models.json`), so there's one DRY place to manage audio models: install it once from the installer and it's immediately selectable in the Music studio. Models no on-device engine can run yet — and ACE-Step, which uses a fixed checkpoint — are discovery-only with a "Visit" link. Curated suggestions lead the list: **ACE-Step v1.5**, **`google/magenta-realtime-2`**, and **`stabilityai/stable-audio-3-medium`** (the last gated behind a Hugging Face data-sharing agreement).- **Autopilot now heals episode-level arc contradictions instead of pausing on them.** The arc-verify convergence loop re-verifies and auto-resolves the arc each round, but auto-resolve could previously only rewrite the arc + volume/season synopses — it was explicitly forbidden from touching episodes. So a contradiction that *originated* inside one episode's planning synopsis (e.g. an episode stages an event a later volume reserves as its own "first" occurrence) could never be fixed: every round re-flagged it because the episode text never changed, and the run always hard-paused with "arc verification did not converge." The auto-resolve pass can now return targeted episode-synopsis corrections (keyed by season + episode number), applied at the arc-verify gate **before** any beats/scripts are generated — so the cheap structural layer is made consistent before expensive script generation. Locked episodes are left untouched; already-expanded beats on a corrected episode are cleared so they regenerate from the fixed synopsis. (`pipeline-arc-resolve` prompt + migration 123.)diff --git a/client/src/components/music/MusicGenPanel.jsx b/client/src/components/music/MusicGenPanel.jsxindex c36c98ba07..27215b60a4 100644--- a/client/src/components/music/MusicGenPanel.jsx+++ b/client/src/components/music/MusicGenPanel.jsx@@ -20,7 +20,7 @@ import {} from '../../services/api';import RuntimeInstallModal from '../install/RuntimeInstallModal';-export default function MusicGenPanel({ track, prompt, lyrics, onGenerated }) {+export default function MusicGenPanel({ track, prompt, lyrics, onGenerated, remix }) {const [engines, setEngines] = useState([]);const [loading, setLoading] = useState(true);const [engineId, setEngineId] = useState('');@@ -54,6 +54,21 @@ export default function MusicGenPanel({ track, prompt, lyrics, onGenerated }) {const engine = useMemo(() => engines.find((e) => e.id === engineId) || null, [engines, engineId]);+ // Remix: seed the engine / model / duration from a past render. Keyed on+ // `remix.nonce` (bumped per Remix click) so re-clicking the SAME render+ // re-applies even when its values are unchanged. An uploaded render carries no+ // engineId — skip the engine swap then and just keep the user's current+ // selection (the parent still prefills the prompt/lyrics form fields). Setting+ // engineId + modelId together lets the engine-validity effect below keep the+ // seeded model (it's in the engine's list because the engine produced it).+ useEffect(() => {+ if (!remix) return;+ if (remix.engineId) setEngineId(remix.engineId);+ if (remix.modelId) setModelId(remix.modelId);+ if (remix.durationSec != null) setDurationSec(remix.durationSec);+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [remix?.nonce]);+// Keep the model selection valid for the current engine: reset to the engine// default ONLY when the selected model isn't in this engine's list. Keying on// engine.id (not the object) + this guard means a list refresh after installingdiff --git a/client/src/components/music/TrackRenderCard.jsx b/client/src/components/music/TrackRenderCard.jsxnew file mode 100644index 0000000000..1554e53dad--- /dev/null+++ b/client/src/components/music/TrackRenderCard.jsx@@ -0,0 +1,130 @@+/**+ * TrackRenderCard — one take in a track's render history.+ *+ * Mirrors the image/video gen MediaCard: an inline player, the prompt + the+ * generation metadata (engine / model / duration) as badges, and opt-in actions+ * (open the detail modal, make this render active, remix from its settings,+ * download, delete). The ACTIVE render — the one the top-level track pointer+ * plays — is highlighted and labelled. Action callbacks are opt-in: pass only+ * the ones the parent wants rendered.+ */++import { useState } from 'react';+import { Maximize2, Sparkles, Download, Trash2, CheckCircle2, Music2, Upload } from 'lucide-react';+import InlineConfirmRow from '../ui/InlineConfirmRow';+import { formatTimecode, timeAgo } from '../../utils/formatters';+import { trackAudioUrl } from '../../services/api';++export default function TrackRenderCard({+ render,+ active = false,+ onOpen,+ onSelect,+ onRemix,+ onDelete,+}) {+ const [confirmingDelete, setConfirmingDelete] = useState(false);+ const { prompt, engine, modelId, durationSec, audioFilename, createdAt } = render;+ // An uploaded take has no engine (the studio cleared the gen metadata on+ // attach) — label it so a generated vs. imported take reads at a glance.+ const isUpload = !engine;++ return (+ <div className={`bg-port-card border rounded-xl p-2.5 space-y-2 ${active ? 'border-port-accent' : 'border-port-border'}`}>+ <div className="flex items-center justify-between gap-2">+ <div className="flex items-center gap-1.5 min-w-0">+ {isUpload+ ? <Upload size={13} className="text-gray-500 shrink-0" aria-hidden="true" />+ : <Music2 size={13} className="text-port-accent shrink-0" aria-hidden="true" />}+ <span className="text-[11px] text-gray-500 truncate" title={audioFilename}>+ {createdAt ? timeAgo(createdAt) : audioFilename}+ </span>+ </div>+ {active ? (+ <span className="inline-flex items-center gap-1 text-[10px] text-port-success shrink-0">+ <CheckCircle2 size={11} aria-hidden="true" /> Active+ </span>+ ) : null}+ </div>++ <audio controls preload="none" src={trackAudioUrl(audioFilename)} className="w-full h-8">+ <track kind="captions" />+ </audio>++ {prompt ? (+ <p className="text-[11px] text-gray-300 line-clamp-2" title={prompt}>{prompt}</p>+ ) : (+ <p className="text-[11px] text-gray-600 italic">{isUpload ? 'Uploaded audio' : 'No prompt'}</p>+ )}++ <div className="flex flex-wrap gap-1 text-[9px]">+ {engine ? <span className="px-1.5 py-0.5 bg-port-accent/20 text-port-accent rounded">{engine}</span> : null}+ {modelId ? <span className="px-1.5 py-0.5 bg-port-border text-gray-400 rounded truncate max-w-[140px]" title={modelId}>{modelId}</span> : null}+ {durationSec ? <span className="px-1.5 py-0.5 bg-port-border text-gray-400 rounded">{formatTimecode(durationSec)}</span> : null}+ </div>++ {confirmingDelete && onDelete ? (+ <InlineConfirmRow+ question="Delete this render?"+ confirmText="Delete"+ confirmTitle="Remove from history (audio stays in the library)"+ onConfirm={() => { setConfirmingDelete(false); onDelete(render); }}+ onCancel={() => setConfirmingDelete(false)}+ />+ ) : (+ <div className="flex flex-wrap gap-1">+ {onOpen ? (+ <button+ type="button"+ onClick={() => onOpen(render)}+ className="flex-1 min-w-0 px-1.5 py-1 bg-port-border hover:bg-port-border/70 text-white text-[10px] rounded flex items-center justify-center gap-1"+ title="View details"+ >+ <Maximize2 className="w-3 h-3 shrink-0" /> <span className="truncate">Details</span>+ </button>+ ) : null}+ {onSelect && !active ? (+ <button+ type="button"+ onClick={() => onSelect(render)}+ className="shrink-0 px-1.5 py-1 bg-port-success/20 hover:bg-port-success/40 text-port-success text-[10px] rounded flex items-center justify-center gap-1"+ title="Make this the active take"+ >+ <CheckCircle2 className="w-3 h-3" /> Use+ </button>+ ) : null}+ {onRemix ? (+ <button+ type="button"+ onClick={() => onRemix(render)}+ className="shrink-0 px-1.5 py-1 bg-port-accent/20 hover:bg-port-accent/40 text-port-accent text-[10px] rounded flex items-center justify-center gap-1"+ title="Reuse these settings for a new render"+ >+ <Sparkles className="w-3 h-3" /> Remix+ </button>+ ) : null}+ <a+ href={trackAudioUrl(audioFilename)}+ download+ className="shrink-0 px-1.5 py-1 bg-port-border hover:bg-port-border/70 text-white text-[10px] rounded flex items-center justify-center"+ title="Download"+ aria-label="Download"+ >+ <Download className="w-3 h-3" />+ </a>+ {onDelete ? (+ <button+ type="button"+ onClick={() => setConfirmingDelete(true)}+ className="shrink-0 px-1.5 py-1 bg-port-error/20 hover:bg-port-error/40 text-port-error text-[10px] rounded flex items-center justify-center"+ title="Delete render"+ aria-label="Delete render"+ >+ <Trash2 className="w-3 h-3" />+ </button>+ ) : null}+ </div>+ )}+ </div>+ );+}diff --git a/client/src/components/music/TrackRenderModal.jsx b/client/src/components/music/TrackRenderModal.jsxnew file mode 100644index 0000000000..aba01a4799--- /dev/null+++ b/client/src/components/music/TrackRenderModal.jsx@@ -0,0 +1,119 @@+/**+ * TrackRenderModal — the full detail view for a single render take.+ *+ * Opened from a TrackRenderCard's "Details" action. Shows the complete prompt,+ * the lyrics that conditioned the take (lyric-aware engines), every piece of+ * generation metadata, and a full-width player. The "Remix" action seeds the+ * generation panel with this take's settings so the user can iterate; "Use this+ * take" makes it the active render. Mirrors the image/video MediaLightbox role.+ */++import { Sparkles, CheckCircle2, Download, Trash2, X } from 'lucide-react';+import Modal from '../ui/Modal';+import { formatTimecode, timeAgo } from '../../utils/formatters';+import { trackAudioUrl } from '../../services/api';++function MetaRow({ label, children }) {+ return (+ <div className="flex gap-3 text-xs">+ <span className="w-20 shrink-0 text-gray-500 uppercase tracking-wider text-[10px] pt-0.5">{label}</span>+ <span className="flex-1 min-w-0 text-gray-300 break-words">{children}</span>+ </div>+ );+}++export default function TrackRenderModal({ render, active = false, onClose, onSelect, onRemix, onDelete }) {+ if (!render) return null;+ const { prompt, lyrics, engine, modelId, durationSec, audioFilename, createdAt } = render;+ const isUpload = !engine;++ return (+ <Modal+ open={!!render}+ onClose={onClose}+ size="lg"+ align="top"+ ariaLabelledBy="track-render-title"+ panelClassName="bg-port-card rounded-xl border border-port-border shadow-2xl overflow-hidden flex flex-col max-h-[85vh]"+ >+ <div className="flex items-center justify-between px-5 py-3 border-b border-port-border">+ <h2 id="track-render-title" className="text-sm font-semibold text-white flex items-center gap-2">+ {isUpload ? 'Uploaded take' : 'Render details'}+ {active ? (+ <span className="inline-flex items-center gap-1 text-[10px] text-port-success">+ <CheckCircle2 size={11} aria-hidden="true" /> Active+ </span>+ ) : null}+ </h2>+ <button onClick={onClose} className="text-gray-400 hover:text-white p-1" aria-label="Close">+ <X size={18} />+ </button>+ </div>++ <div className="flex-1 overflow-auto px-5 py-4 space-y-4">+ <audio controls preload="metadata" src={trackAudioUrl(audioFilename)} className="w-full">+ <track kind="captions" />+ </audio>++ <div className="space-y-1.5">+ {engine ? <MetaRow label="Engine">{engine}</MetaRow> : null}+ {modelId ? <MetaRow label="Model">{modelId}</MetaRow> : null}+ {durationSec ? <MetaRow label="Duration">{formatTimecode(durationSec)} ({durationSec}s)</MetaRow> : null}+ {createdAt ? <MetaRow label="Created">{timeAgo(createdAt)}</MetaRow> : null}+ <MetaRow label="File">{audioFilename}</MetaRow>+ </div>++ {prompt ? (+ <div>+ <div className="text-[10px] uppercase tracking-wider text-gray-500 mb-1">Prompt</div>+ <p className="text-xs text-gray-300 whitespace-pre-wrap break-words bg-port-bg border border-port-border rounded p-2.5">{prompt}</p>+ </div>+ ) : null}++ {lyrics ? (+ <div>+ <div className="text-[10px] uppercase tracking-wider text-gray-500 mb-1">Lyrics (conditioning)</div>+ <pre className="text-xs text-gray-300 whitespace-pre-wrap break-words bg-port-bg border border-port-border rounded p-2.5 font-mono max-h-48 overflow-auto">{lyrics}</pre>+ </div>+ ) : null}+ </div>++ <div className="px-5 py-3 border-t border-port-border flex items-center justify-end gap-2 flex-wrap">+ {onDelete ? (+ <button+ type="button"+ onClick={() => onDelete(render)}+ className="mr-auto inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-port-error hover:bg-port-error/10 text-xs"+ >+ <Trash2 size={13} /> Delete+ </button>+ ) : null}+ <a+ href={trackAudioUrl(audioFilename)}+ download+ className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-port-border hover:bg-port-border/70 text-white text-xs"+ >+ <Download size={13} /> Download+ </a>+ {onSelect && !active ? (+ <button+ type="button"+ onClick={() => onSelect(render)}+ className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-port-success/20 hover:bg-port-success/40 text-port-success text-xs font-medium"+ >+ <CheckCircle2 size={13} /> Use this take+ </button>+ ) : null}+ {onRemix ? (+ <button+ type="button"+ onClick={() => onRemix(render)}+ className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-port-accent hover:bg-port-accent/90 text-white text-xs font-medium"+ >+ <Sparkles size={13} /> Remix+ </button>+ ) : null}+ </div>+ </Modal>+ );+}diff --git a/client/src/components/music/TracksManager.jsx b/client/src/components/music/TracksManager.jsxindex daff1794df..b1847a66fc 100644--- a/client/src/components/music/TracksManager.jsx+++ b/client/src/components/music/TracksManager.jsx@@ -13,20 +13,22 @@*/import { useEffect, useMemo, useRef, useState } from 'react';-import { Plus, Loader2, Trash2, Save, Upload, Music2, X, Library } from 'lucide-react';+import { Plus, Loader2, Trash2, Save, Upload, Music2, Library } from 'lucide-react';import toast from '../ui/Toast';import { formatTimecode } from '../../utils/formatters';import ArtistPicker from './ArtistPicker';import MusicGenPanel from './MusicGenPanel';+import TrackRenderCard from './TrackRenderCard';+import TrackRenderModal from './TrackRenderModal';import {listTracks, createTrack, updateTrack, deleteTrack,- uploadTrackAudio, attachTrackAudio, clearTrackAudio, listMusicLibrary, listAlbums,+ uploadTrackAudio, attachTrackAudio, listMusicLibrary, listAlbums,+ selectTrackRender, deleteTrackRender,TRACK_TITLE_MAX, TRACK_LYRICS_MAX, TRACK_PROMPT_MAX,} from '../../services/api';// Cap audio uploads to match the server's MUSIC_UPLOAD_MAX_BYTES (50MB).const AUDIO_MAX_BYTES = 50 * 1024 * 1024;-const AUDIO_SRC = (filename) => `/data/music/${encodeURIComponent(filename)}`;const emptyForm = () => ({title: '', albumId: '', artistId: '', artist: '', lyrics: '', prompt: '', audioFilename: '',@@ -63,6 +65,12 @@ export default function TracksManager() {const [libraryOpen, setLibraryOpen] = useState(false);const [library, setLibrary] = useState([]);const [albums, setAlbums] = useState([]);+ // The render shown in the detail/remix modal, and the seed passed to the gen+ // panel when remixing (nonce bumps per click so re-remixing the same take+ // re-applies). See remixRender below.+ const [modalRender, setModalRender] = useState(null);+ const [remix, setRemix] = useState(null);+ const remixNonceRef = useRef(0);const fileInputRef = useRef(null);// Mirrors `selectedId` so async audio handlers can detect a selection change// that happened while their server round-trip was in flight (the server write@@ -202,14 +210,52 @@ export default function TracksManager() {}};- const removeAudio = async () => {- if (!persisted) { setForm((f) => ({ ...f, audioFilename: '' })); return; }- const targetId = persisted.id;- const res = await clearTrackAudio(targetId, { silent: true }).catch((err) => { toast.error(err.message || 'Failed to clear audio'); return null; });- if (res?.track) {- upsertLocal(res.track);- if (selectedIdRef.current === targetId) setForm((f) => ({ ...f, audioFilename: '' }));- }+ // Render history — newest first. The active take (the top-level audioFilename+ // pointer) is highlighted in the grid.+ const renders = useMemo(() => {+ const list = Array.isArray(persisted?.renders) ? [...persisted.renders] : [];+ return list.sort((a, b) => (b.createdAt || '').localeCompare(a.createdAt || ''));+ }, [persisted]);+ const activeFilename = persisted?.audioFilename || '';++ // After a server-confirmed render mutation, sync the list + mirror the active+ // pointer into the open form (only when THIS track is still selected — the+ // user may have switched tracks during the round-trip).+ const applyRenderResult = (res, targetId) => {+ if (!res?.track) return;+ upsertLocal(res.track);+ if (selectedIdRef.current === targetId) setForm((f) => ({ ...f, audioFilename: res.track.audioFilename || '' }));+ };++ const selectRender = async (render) => {+ const targetId = persisted?.id;+ if (!targetId) return;+ const res = await selectTrackRender(targetId, render.id, { silent: true })+ .catch((err) => { toast.error(err.message || 'Failed to select render'); return null; });+ applyRenderResult(res, targetId);+ };++ const deleteRender = async (render) => {+ const targetId = persisted?.id;+ if (!targetId) return;+ setModalRender((m) => (m?.id === render.id ? null : m));+ const res = await deleteTrackRender(targetId, render.id, { silent: true })+ .catch((err) => { toast.error(err.message || 'Failed to delete render'); return null; });+ applyRenderResult(res, targetId);+ };++ // Remix: prefill the editable prompt/lyrics from the take (guard empties so an+ // uploaded take can't wipe the user's text), seed the gen panel's engine/+ // model/duration, and close the modal so the panel is in view.+ const remixRender = (render) => {+ setModalRender(null);+ setForm((f) => ({+ ...f,+ ...(render.prompt ? { prompt: render.prompt } : {}),+ ...(render.lyrics ? { lyrics: render.lyrics } : {}),+ }));+ remixNonceRef.current += 1;+ setRemix({ engineId: render.engine, modelId: render.modelId, durationSec: render.durationSec, nonce: remixNonceRef.current });};return (@@ -315,29 +361,22 @@ export default function TracksManager() {/></Field>- {/* Generation metadata (read-only) — populated when a track is generated. */}- {persisted && (persisted.engine || persisted.modelId || persisted.durationSec) ? (- <div className="flex flex-wrap items-center gap-2 text-[11px]">- {persisted.engine ? <span className="px-2 py-0.5 rounded-full bg-port-bg border border-port-border text-gray-400">engine: {persisted.engine}</span> : null}- {persisted.modelId ? <span className="px-2 py-0.5 rounded-full bg-port-bg border border-port-border text-gray-400">model: {persisted.modelId}</span> : null}- {persisted.durationSec ? <span className="px-2 py-0.5 rounded-full bg-port-bg border border-port-border text-gray-400">{formatTimecode(persisted.durationSec)}</span> : null}- </div>- ) : null}-{/* On-device generation — available once the track is saved (theserver attaches the audio + metadata to the persisted track).- Uses the CURRENT prompt/lyrics in the form. */}+ Uses the CURRENT prompt/lyrics in the form; `remix` seeds the+ engine/model/duration from a past take. */}{persisted ? (<MusicGenPaneltrack={persisted}prompt={form.prompt}lyrics={form.lyrics}+ remix={remix}onGenerated={(updated) => {upsertLocal(updated); // list update is id-keyed → always safe// Merge ONLY the server-set generation fields into the open- // form (audio + gen metadata mirror onto the form's read-only- // badges/player) so any UNSAVED edits the user made to title/- // artist/album/prompt/lyrics before clicking Generate survive.+ // form (the active audio pointer mirrors onto the form) so any+ // UNSAVED edits the user made to title/artist/album/prompt/+ // lyrics before clicking Generate survive.if (selectedIdRef.current === updated.id) {setForm((f) => ({ ...f, audioFilename: updated.audioFilename || '' }));}@@ -345,66 +384,81 @@ export default function TracksManager() {/>) : null}- <Field label="Audio" hint="Upload an audio file or attach one from the shared music library. Save the track first.">- {form.audioFilename ? (- <div className="space-y-2">- <audio controls src={AUDIO_SRC(form.audioFilename)} className="w-full">- <track kind="captions" />- </audio>- <div className="flex items-center gap-2">- <span className="text-[11px] text-gray-500 truncate flex-1">{form.audioFilename}</span>+ {/* Render history — every generated/uploaded take as a card. The+ active take is highlighted; each card opens a detail/remix modal,+ can be made active, remixed, downloaded, or deleted. */}+ {persisted ? (+ <div className="space-y-2">+ <div className="flex items-center justify-between gap-2 flex-wrap">+ <span className="block text-xs uppercase tracking-wider text-gray-500">+ Renders{renders.length ? ` (${renders.length})` : ''}+ </span>+ <div className="flex items-center gap-2 flex-wrap"><buttontype="button"- onClick={removeAudio}- className="inline-flex items-center gap-1 px-2 py-1 rounded text-gray-400 hover:text-port-error text-xs"+ onClick={() => (requireSaved() ? fileInputRef.current?.click() : null)}+ disabled={uploading}+ className="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg bg-port-bg border border-port-border text-white text-sm hover:border-port-accent disabled:opacity-50">- <X size={12} /> Remove+ {uploading ? <Loader2 size={14} className="animate-spin" /> : <Upload size={14} />} Upload</button>+ <button+ type="button"+ onClick={openLibrary}+ className="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg bg-port-bg border border-port-border text-white text-sm hover:border-port-accent"+ >+ <Library size={14} /> From library+ </button>+ <input ref={fileInputRef} type="file" accept="audio/*,.mp3,.wav,.m4a,.ogg,.flac" onChange={handleAudioFile} className="hidden" /></div></div>- ) : (- <div className="flex items-center gap-2 flex-wrap">- <button- type="button"- onClick={() => (requireSaved() ? fileInputRef.current?.click() : null)}- disabled={uploading}- className="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg bg-port-bg border border-port-border text-white text-sm hover:border-port-accent disabled:opacity-50"- >- {uploading ? <Loader2 size={14} className="animate-spin" /> : <Upload size={14} />} Upload- </button>- <button- type="button"- onClick={openLibrary}- className="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg bg-port-bg border border-port-border text-white text-sm hover:border-port-accent"- >- <Library size={14} /> From library- </button>- <input ref={fileInputRef} type="file" accept="audio/*,.mp3,.wav,.m4a,.ogg,.flac" onChange={handleAudioFile} className="hidden" />- </div>- )}- {libraryOpen ? (- <div className="mt-2 border border-port-border rounded-lg bg-port-bg max-h-48 overflow-y-auto">- {library.length === 0 ? (- <div className="text-xs text-gray-500 p-3">The music library is empty — upload a track first.</div>- ) : (- <ul className="divide-y divide-port-border">- {library.map((item) => (- <li key={item.filename}>- <button- type="button"- onClick={() => attachFromLibrary(item.filename)}- className="w-full text-left px-3 py-2 text-sm text-gray-300 hover:bg-port-card flex items-center gap-2"- >- <Music2 size={13} className="text-gray-500 shrink-0" />- <span className="flex-1 min-w-0 truncate">{item.label || item.filename}</span>- </button>- </li>- ))}- </ul>- )}- </div>- ) : null}- </Field>++ {renders.length === 0 ? (+ <div className="text-xs text-gray-500 border border-dashed border-port-border rounded-lg p-4 text-center">+ No renders yet. Generate above, upload a file, or attach one from your library.+ </div>+ ) : (+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-2">+ {renders.map((r) => (+ <TrackRenderCard+ key={r.id}+ render={r}+ active={r.audioFilename === activeFilename}+ onOpen={(rr) => setModalRender(rr)}+ onSelect={selectRender}+ onRemix={remixRender}+ onDelete={deleteRender}+ />+ ))}+ </div>+ )}++ {libraryOpen ? (+ <div className="mt-1 border border-port-border rounded-lg bg-port-bg max-h-48 overflow-y-auto">+ {library.length === 0 ? (+ <div className="text-xs text-gray-500 p-3">The music library is empty — upload a track first.</div>+ ) : (+ <ul className="divide-y divide-port-border">+ {library.map((item) => (+ <li key={item.filename}>+ <button+ type="button"+ onClick={() => attachFromLibrary(item.filename)}+ className="w-full text-left px-3 py-2 text-sm text-gray-300 hover:bg-port-card flex items-center gap-2"+ >+ <Music2 size={13} className="text-gray-500 shrink-0" />+ <span className="flex-1 min-w-0 truncate">{item.label || item.filename}</span>+ </button>+ </li>+ ))}+ </ul>+ )}+ </div>+ ) : null}+ </div>+ ) : (+ <p className="text-xs text-gray-500">Save the track first to generate, upload, or attach audio.</p>+ )}<div className="flex items-center gap-2 pt-1 flex-wrap"><button@@ -434,6 +488,17 @@ export default function TracksManager() {)}</div></div>++ {modalRender ? (+ <TrackRenderModal+ render={modalRender}+ active={modalRender.audioFilename === activeFilename}+ onClose={() => setModalRender(null)}+ onSelect={selectRender}+ onRemix={remixRender}+ onDelete={deleteRender}+ />+ ) : null}</div>);}diff --git a/client/src/services/apiTracks.js b/client/src/services/apiTracks.jsindex dc409c024b..48cac03655 100644--- a/client/src/services/apiTracks.js+++ b/client/src/services/apiTracks.js@@ -1,5 +1,9 @@import { request } from './apiCore.js';+// Static-asset URL for a track's audio bytes in the shared music library+// (data/music/). Not an API call — a plain href for <audio>/download links.+export const trackAudioUrl = (filename) => `/data/music/${encodeURIComponent(filename)}`;+// ---- Music tracks ----// A track is a single song/recording — standalone or part of an album. It stores// a pointer (`audioFilename`) into the shared music library; the bytes are@@ -39,6 +43,23 @@ export const clearTrackAudio = (id, requestOptions = {}) => request(`/tracks/${e...requestOptions,});+// --- Render history ----+// A track keeps every generated/uploaded take in `track.renders[]`. The active+// take is mirrored onto the top-level `audioFilename`/`engine`/`modelId`/+// `durationSec`. Both endpoints return `{ track }` (the updated record).++// Make a past render the active one (re-points the player + gen-metadata badges).+export const selectTrackRender = (id, renderId, requestOptions = {}) => request(+ `/tracks/${encodeURIComponent(id)}/renders/${encodeURIComponent(renderId)}/select`,+ { method: 'POST', ...requestOptions },+);++// Remove a render from the history (the audio bytes stay in the shared library).+export const deleteTrackRender = (id, renderId, requestOptions = {}) => request(+ `/tracks/${encodeURIComponent(id)}/renders/${encodeURIComponent(renderId)}`,+ { method: 'DELETE', ...requestOptions },+);+// Upload an audio file (FormData with a `track` file field) into the library and// attach it to this track. The caller builds the FormData; we pass it through as// the request body so the multipart boundary header is set by the browser.diff --git a/server/lib/conflictJournal.js b/server/lib/conflictJournal.jsindex 4dd207cc0c..6c55725c8b 100644--- a/server/lib/conflictJournal.js+++ b/server/lib/conflictJournal.js@@ -306,7 +306,7 @@ export const RESTORABLE_FIELDS = Object.freeze({author: ['name', 'writingStyle', 'bio', 'physicalDescription', 'headshotStyle', 'headshotImageUrl'],artist: ['name', 'genre', 'bio', 'musicalStyle', 'physicalDescription', 'portraitStyle', 'portraitImageUrl'],album: ['title', 'artistId', 'artist', 'description', 'genre', 'releaseYear', 'coverImageUrl', 'trackIds'],- track: ['title', 'albumId', 'artistId', 'artist', 'lyrics', 'prompt', 'engine', 'modelId', 'durationSec', 'audioFilename'],+ track: ['title', 'albumId', 'artistId', 'artist', 'lyrics', 'prompt', 'engine', 'modelId', 'durationSec', 'audioFilename', 'renders'],// Issue: the user-authored content the merge can restore. `stages` carries// the bulk of the work (prose, comic pages, render metadata). Server-owned /// structural fields are excluded deliberately — `number` is renumber-managed,diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.jsindex 5db729a31f..c1d6df08fe 100644--- a/server/lib/schemaVersions.js+++ b/server/lib/schemaVersions.js@@ -159,7 +159,18 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({// music record type it cannot parse while unrelated categories keep flowing.artists: 1,albums: 1,- tracks: 1,+ // tracks v2 = `track.renders[]` render-history added (every generated/uploaded+ // take, so the studio shows each render as a card + can re-select an earlier+ // one). Additive + gracefully degrading, but version-gated for the same reason+ // as the universes relationshipLinks/attachments fields: a ≤v1 peer that+ // receives and re-sanitizes a track through its renders-unaware `sanitizeTrack`+ // would silently strip the history (keeping only the active pointer) and+ // last-writer-wins the loss back onto the newer peer. Bumping makes the older+ // peer reject the ahead-version track transfer instead. Per-category gate →+ // only track sync pauses with old peers; artists/albums keep flowing. The+ // backfill itself needs no migration — `sanitizeTrack` synthesizes a render+ // from the legacy active pointer on read (see services/tracks/logic.js).+ tracks: 2,// v1 = creative ingredients catalog (Postgres tables: catalog_scraps,// catalog_ingredients, catalog_ingredient_sources, catalog_ingredient_refs).// v2 = `catalog_ingredients.search_tsv` expanded to also index thediff --git a/server/routes/music.js b/server/routes/music.jsindex 3cd70a65af..3861601b4b 100644--- a/server/routes/music.js+++ b/server/routes/music.js@@ -296,12 +296,30 @@ router.post('/generate', asyncHandler(async (req, res) => {// including an intentional '' clear (the audio was generated without lyrics) —// but an ABSENT lyrics field leaves the track's lyrics untouched. A non-lyric// engine never writes lyrics (it can't erase a song's words by adding a bed).+ const durationSec = Math.round(result.durationSec);+ // The lyrics actually used for THIS render (snapshotted onto the render card):+ // what the caller sent for a lyric-aware engine, else the track's saved lyrics.+ const renderLyrics = engine.lyrics+ ? (body.lyrics ?? existing?.lyrics ?? '')+ : (existing?.lyrics ?? '');+ // Append to the existing history (sanitizeTrack de-dups + caps); a new track+ // seeds the array with this first render.+ const { renders } = tracks.buildRenderAppend(existing, {+ audioFilename: result.filename,+ prompt: body.prompt,+ lyrics: renderLyrics,+ engine: result.engine,+ modelId: result.modelId,+ durationSec,+ });+const meta = {audioFilename: result.filename,engine: result.engine,modelId: result.modelId,- durationSec: Math.round(result.durationSec),+ durationSec,prompt: body.prompt,+ renders,};if (engine.lyrics && body.lyrics !== undefined) meta.lyrics = body.lyrics;diff --git a/server/routes/music.test.js b/server/routes/music.test.jsindex e4da2dc33b..a7de48ba74 100644--- a/server/routes/music.test.js+++ b/server/routes/music.test.js@@ -29,6 +29,10 @@ vi.mock('../services/tracks/index.js', () => ({getTrack: vi.fn(),createTrack: vi.fn(async (input) => ({ id: 'track-new', ...input })),updateTrack: vi.fn(async (id, patch) => ({ id, ...patch })),+ buildRenderAppend: vi.fn((track, input) => {+ const render = { id: 'render-x', ...input };+ return { render, renders: [...(track?.renders || []), render] };+ }),}));const models = vi.hoisted(() => ({ list: vi.fn(), add: vi.fn(), remove: vi.fn() }));diff --git a/server/routes/tracks.js b/server/routes/tracks.jsindex 16b7b4085b..4367188db1 100644--- a/server/routes/tracks.js+++ b/server/routes/tracks.js@@ -107,6 +107,27 @@ async function requireTrack(id) {return track;}+// Make `filename` the active audio AND record it in the render history so an+// uploaded/attached take shows up as a card alongside generated ones. An+// uploaded render has no engine/model/duration, so the active gen-metadata is+// cleared (keeps the read-only badges honest). Re-attaching a file already in+// the history just re-selects it (no duplicate card).+async function attachAudioAsRender(track, filename) {+ const existing = (track.renders || []).find((r) => r.audioFilename === filename);+ if (existing) {+ const patch = tracks.selectRenderPatch(track, existing.id) || { audioFilename: filename };+ return tracks.updateTrack(track.id, patch);+ }+ const { renders } = tracks.buildRenderAppend(track, { audioFilename: filename });+ return tracks.updateTrack(track.id, {+ audioFilename: filename,+ engine: '',+ modelId: '',+ durationSec: null,+ renders,+ });+}+// Membership reconcile, track→album direction (the inverse of the album route's// reconcileAlbumMembership). When a track's `albumId` changes, append it to the// new album's ordered `trackIds` (if absent) and drop it from the previous@@ -171,27 +192,49 @@ router.delete('/:id', asyncHandler(async (req, res) => {// Upload an audio file into the shared library and attach it to this track.router.post('/:id/audio/upload', musicUpload, asyncHandler(async (req, res) => {- await requireTrack(req.params.id);+ const track = await requireTrack(req.params.id);if (!req.file) throw new ServerError('No audio file uploaded', { status: 400, code: 'TRACK_AUDIO_MISSING_FILE' });const { filename, sizeBytes } = await importUploadedTrack(req.file.path, req.file.originalname);- const updated = await tracks.updateTrack(req.params.id, { audioFilename: filename });+ const updated = await attachAudioAsRender(track, filename);res.json({ track: updated, filename, sizeBytes });}));// Attach an existing library track (by stored filename) to this track.router.post('/:id/audio/attach', asyncHandler(async (req, res) => {- await requireTrack(req.params.id);+ const track = await requireTrack(req.params.id);const { filename } = validateRequest(attachSchema, req.body ?? {});assertSafeMusicFilename(filename);const found = await statMusicTrack(filename);if (!found) throw new ServerError('Track not found in the music library', { status: 404, code: 'TRACK_AUDIO_NOT_IN_LIBRARY' });- res.json({ track: await tracks.updateTrack(req.params.id, { audioFilename: filename }) });+ res.json({ track: await attachAudioAsRender(track, filename) });}));// Clear the audio pointer (leaves the library file in place — it may be shared).+// Does NOT touch the render history — to drop a specific take, use the+// per-render delete below.router.delete('/:id/audio', asyncHandler(async (req, res) => {await requireTrack(req.params.id);res.json({ track: await tracks.updateTrack(req.params.id, { audioFilename: '' }) });}));+// Make a past render the active one (re-point the player + gen-metadata badges+// at it). The user-authored prompt/lyrics are left untouched — they drive the+// NEXT generation, independent of which take is selected for playback.+router.post('/:id/renders/:renderId/select', asyncHandler(async (req, res) => {+ const track = await requireTrack(req.params.id);+ const patch = tracks.selectRenderPatch(track, req.params.renderId);+ if (!patch) throw new ServerError('Render not found', { status: 404, code: 'TRACK_RENDER_NOT_FOUND' });+ res.json({ track: await tracks.updateTrack(req.params.id, patch) });+}));++// Remove a render from the history. When it was the active take, the active+// pointer re-points at the newest remaining render (or clears). The audio bytes+// stay in the shared library (they may be shared with another track).+router.delete('/:id/renders/:renderId', asyncHandler(async (req, res) => {+ const track = await requireTrack(req.params.id);+ const patch = tracks.deleteRenderPatch(track, req.params.renderId);+ if (!patch) throw new ServerError('Render not found', { status: 404, code: 'TRACK_RENDER_NOT_FOUND' });+ res.json({ track: await tracks.updateTrack(req.params.id, patch) });+}));+export default router;diff --git a/server/routes/tracks.test.js b/server/routes/tracks.test.jsindex dad755912e..7c382b1dce 100644--- a/server/routes/tracks.test.js+++ b/server/routes/tracks.test.js@@ -20,6 +20,19 @@ vi.mock('../services/tracks/index.js', () => ({createTrack: vi.fn(async (input) => ({ id: 'track-new', ...input })),updateTrack: vi.fn(async (id, patch) => ({ id, ...patch })),deleteTrack: vi.fn(async (id) => ({ id })),+ buildRenderAppend: vi.fn((track, input) => {+ const render = { id: 'render-x', ...input };+ return { render, renders: [...(track?.renders || []), render] };+ }),+ selectRenderPatch: vi.fn((track, renderId) => {+ const r = (track.renders || []).find((x) => x.id === renderId);+ return r ? { audioFilename: r.audioFilename, engine: r.engine, modelId: r.modelId, durationSec: r.durationSec } : null;+ }),+ deleteRenderPatch: vi.fn((track, renderId) => {+ const renders = track.renders || [];+ if (!renders.some((x) => x.id === renderId)) return null;+ return { renders: renders.filter((x) => x.id !== renderId) };+ }),}));const lib = vi.hoisted(() => ({@@ -141,12 +154,28 @@ describe('tracks routes', () => {expect(r.body.code).toBe('TRACK_AUDIO_NOT_IN_LIBRARY');});- it('POST /:id/audio/attach attaches an existing library track', async () => {+ it('POST /:id/audio/attach attaches an existing library track and records it as a render', async () => {tracks.getTrack.mockResolvedValue({ id: 'track-1', title: 'Intro' });lib.store.set('music-1.mp3', true);const r = await request(app).post('/api/tracks/track-1/audio/attach').send({ filename: 'music-1.mp3' });expect(r.status).toBe(200);- expect(tracks.updateTrack).toHaveBeenCalledWith('track-1', { audioFilename: 'music-1.mp3' });+ expect(tracks.updateTrack).toHaveBeenCalledWith('track-1', expect.objectContaining({+ audioFilename: 'music-1.mp3',+ engine: '',+ renders: expect.arrayContaining([expect.objectContaining({ audioFilename: 'music-1.mp3' })]),+ }));+ });++ it('POST /:id/audio/attach re-selects (no duplicate card) when the file is already in the history', async () => {+ tracks.getTrack.mockResolvedValue({+ id: 'track-1', title: 'Intro', audioFilename: 'other.mp3',+ renders: [{ id: 'render-1', audioFilename: 'music-1.mp3', engine: 'musicgen', modelId: 'm', durationSec: 5 }],+ });+ lib.store.set('music-1.mp3', true);+ const r = await request(app).post('/api/tracks/track-1/audio/attach').send({ filename: 'music-1.mp3' });+ expect(r.status).toBe(200);+ // Re-select path: no `renders` key in the patch (the take already exists).+ expect(tracks.updateTrack).toHaveBeenCalledWith('track-1', { audioFilename: 'music-1.mp3', engine: 'musicgen', modelId: 'm', durationSec: 5 });});it('DELETE /:id/audio clears the pointer', async () => {@@ -155,4 +184,38 @@ describe('tracks routes', () => {expect(r.status).toBe(200);expect(tracks.updateTrack).toHaveBeenCalledWith('track-1', { audioFilename: '' });});++ it('POST /:id/renders/:renderId/select makes a past render active', async () => {+ tracks.getTrack.mockResolvedValue({+ id: 'track-1', title: 'Intro', audioFilename: 'b.wav',+ renders: [{ id: 'render-a', audioFilename: 'a.wav', engine: 'musicgen', modelId: 'm1', durationSec: 10 }],+ });+ const r = await request(app).post('/api/tracks/track-1/renders/render-a/select');+ expect(r.status).toBe(200);+ expect(tracks.updateTrack).toHaveBeenCalledWith('track-1', { audioFilename: 'a.wav', engine: 'musicgen', modelId: 'm1', durationSec: 10 });+ });++ it('POST /:id/renders/:renderId/select 404s for an unknown render', async () => {+ tracks.getTrack.mockResolvedValue({ id: 'track-1', title: 'Intro', renders: [] });+ const r = await request(app).post('/api/tracks/track-1/renders/missing/select');+ expect(r.status).toBe(404);+ expect(r.body.code).toBe('TRACK_RENDER_NOT_FOUND');+ });++ it('DELETE /:id/renders/:renderId removes a render', async () => {+ tracks.getTrack.mockResolvedValue({+ id: 'track-1', title: 'Intro', audioFilename: 'a.wav',+ renders: [{ id: 'render-a', audioFilename: 'a.wav' }, { id: 'render-b', audioFilename: 'b.wav' }],+ });+ const r = await request(app).delete('/api/tracks/track-1/renders/render-a');+ expect(r.status).toBe(200);+ expect(tracks.updateTrack).toHaveBeenCalledWith('track-1', { renders: [{ id: 'render-b', audioFilename: 'b.wav' }] });+ });++ it('DELETE /:id/renders/:renderId 404s for an unknown render', async () => {+ tracks.getTrack.mockResolvedValue({ id: 'track-1', title: 'Intro', renders: [] });+ const r = await request(app).delete('/api/tracks/track-1/renders/missing');+ expect(r.status).toBe(404);+ expect(r.body.code).toBe('TRACK_RENDER_NOT_FOUND');+ });});diff --git a/server/services/sharing/peerSync.js b/server/services/sharing/peerSync.jsindex 7e9f2a118a..1456de9403 100644--- a/server/services/sharing/peerSync.js+++ b/server/services/sharing/peerSync.js@@ -1515,10 +1515,21 @@ async function buildAlbumAssetManifest(album) {}async function buildTrackAssetManifest(track) {- const filename = trackAudioFilename(track?.audioFilename);- if (!filename) return [];- const entry = await hashSimpleAsset(filename, 'music', PATHS.music);- return entry ? [entry] : [];+ // A track now carries a render history — every render's audio must ride the+ // manifest, not just the active pointer, so a peer can play any received card.+ // Union the active filename with each render's; de-dup (the active render's+ // bytes are also in renders[]).+ const filenames = new Set();+ const active = trackAudioFilename(track?.audioFilename);+ if (active) filenames.add(active);+ for (const r of Array.isArray(track?.renders) ? track.renders : []) {+ const f = trackAudioFilename(r?.audioFilename);+ if (f) filenames.add(f);+ }+ const entries = await Promise.all(+ [...filenames].map((filename) => hashSimpleAsset(filename, 'music', PATHS.music)),+ );+ return entries.filter(Boolean);}/**diff --git a/server/services/tracks/db.js b/server/services/tracks/db.jsindex 3354d6f473..ecaa177d00 100644--- a/server/services/tracks/db.js+++ b/server/services/tracks/db.js@@ -11,13 +11,19 @@ import { randomUUID } from 'crypto';import { query, withTransaction } from '../../lib/db.js';import { ServerError } from '../../lib/errorHandler.js';import { mirrorTimestamp } from '../../lib/pgTimestamp.js';-import { buildTrackRecord, applyTrackPatch, mergeTrackRecord } from './logic.js';+import { sanitizeTrack, buildTrackRecord, applyTrackPatch, mergeTrackRecord } from './logic.js';import {maybeJournalBeforeOverwrite, setSyncBaseHash, contentHashForRecord, flushBaseHashes, deleteSyncBaseHash,} from '../../lib/conflictJournal.js';+// Re-sanitize the stored JSONB on read (mirrors the file backend's loadAll →+// sanitizeTrack). The record was already sanitized on write, so for an in-shape+// row this is a no-op; the reason to do it is forward-compat BACKFILL — an+// additive field like `renders[]` is synthesized for legacy rows the next time+// they're read (and persisted whole on the next write), without a DB data+// migration (the scripts/migrations runner executes before the pool is up).function rowToTrack(row) {- return row ? row.data : null;+ return row ? sanitizeTrack(row.data) : null;}async function persist(exec, track) {diff --git a/server/services/tracks/file.test.js b/server/services/tracks/file.test.jsindex b940ba5de6..836f9b3324 100644--- a/server/services/tracks/file.test.js+++ b/server/services/tracks/file.test.js@@ -30,9 +30,12 @@ function reset() {const journalEntries = () => cj.conflictJournalStore().loadAll();+// `renders: []` matches the sanitized shape (no audio → empty history), so the+// raw fixture hashes identically to the stored sanitized record in the+// base-hash assertions below — `contentHashForRecord` now includes `renders`.const track = (id, extra = {}) => ({id, title: id, albumId: '', artistId: '', artist: '', lyrics: '', prompt: '',- engine: '', modelId: '', durationSec: null, audioFilename: '',+ engine: '', modelId: '', durationSec: null, audioFilename: '', renders: [],createdAt: '2026-01-01T00:00:00.000Z', updatedAt: '2026-01-01T00:00:00.000Z',deleted: false, deletedAt: null, ...extra,});diff --git a/server/services/tracks/index.js b/server/services/tracks/index.jsindex 431ef7bdc5..c3904e3856 100644--- a/server/services/tracks/index.js+++ b/server/services/tracks/index.js@@ -10,8 +10,10 @@* federate when peers enable the Tracks sync category.*/+import { randomUUID } from 'crypto';import { checkHealth, ensureSchema } from '../../lib/db.js';import { emitRecordUpdated, emitRecordDeleted, autoSubscribeRecordToAllPeers } from '../sharing/recordEvents.js';+import { makeRender as makeRenderLogic } from './logic.js';export {TITLE_MAX,@@ -25,8 +27,13 @@ export {AUDIO_FILENAME_MAX,DURATION_MIN_SEC,DURATION_MAX_SEC,+ RENDER_ID_MAX,+ RENDERS_MAX,TRACK_ID_RE,trackAudioFilename,+ makeRender,+ selectRenderPatch,+ deleteRenderPatch,} from './logic.js';let backend = null;@@ -49,6 +56,17 @@ async function selectBackend() {return backend;}+/**+ * Mint a new render (unique id + timestamp) and return the appended history ++ * the render itself. Centralizes the id/now generation + append so every+ * render-creation path (generate, upload, attach) stays identical — callers+ * layer their own active-pointer fields onto the returned `renders` patch.+ */+export function buildRenderAppend(track, renderInput) {+ const render = makeRenderLogic(renderInput, { id: `render-${randomUUID()}`, now: new Date().toISOString() });+ return { render, renders: [...(track?.renders || []), render] };+}+/** Name of the active backend, or null before first call (for diagnostics/tests). */export function getTracksBackendName() {return backendName;diff --git a/server/services/tracks/logic.js b/server/services/tracks/logic.jsindex 5aea3b77ef..d826ce453a 100644--- a/server/services/tracks/logic.js+++ b/server/services/tracks/logic.js@@ -19,7 +19,14 @@* - modelId — model within that engine, or ''* - durationSec — clip length in seconds, or null* - audioFilename — the music-library filename under data/music/ (the bytes),- * or '' when no audio is attached yet+ * or '' when no audio is attached yet — the ACTIVE render's+ * pointer; `engine`/`modelId`/`durationSec` mirror its metadata+ * - renders — the full render history (every generated/uploaded take), so+ * the studio can show each render as a card and re-select an+ * earlier one. Each entry is `{ id, audioFilename, prompt,+ * lyrics, engine, modelId, durationSec, createdAt }`. The+ * top-level `audioFilename`/`engine`/`modelId`/`durationSec`+ * point at whichever render is currently ACTIVE (selected).** Tracks are `db-primary` (PostgreSQL `tracks` table). The audio bytes live in* the shared music library (services/pipeline/musicLibrary.js, `data/music/`);@@ -42,11 +49,18 @@ export const PROMPT_MAX = 8000;export const ENGINE_MAX = 60;export const MODEL_ID_MAX = 120;export const AUDIO_FILENAME_MAX = 256;+export const RENDER_ID_MAX = 80;+// Cap the render history per track so a runaway generate loop can't grow the+// record unboundedly. Oldest renders fall off first (slice(-RENDERS_MAX)); the+// audio bytes stay in the shared library (they may be referenced elsewhere).+export const RENDERS_MAX = 100;// A track clip's usable duration band — wide enough for a long-form generation,// bounded so a garbage value can't poison the record.export const DURATION_MIN_SEC = 1;export const DURATION_MAX_SEC = 3600;+const RENDER_ID_RE = /^[A-Za-z0-9_-]{1,80}$/;+const isStr = (v) => typeof v === 'string';const trimTo = (v, max) => (isStr(v) ? v.trim().slice(0, max) : '');@@ -57,6 +71,52 @@ function sanitizeDuration(v) {return s;}+// Deterministic id for a render synthesized from a legacy single-pointer track+// (audio attached before the render-history field existed). The DB read path+// re-sanitizes on every read, so a fresh `randomUUID` here would mint a new id+// each read — derive a STABLE id from the audio filename instead (already unique+// per render: `music-gen-<uuid>.wav` for generated, the upload basename else).+function legacyRenderId(audioFilename) {+ const slug = String(audioFilename).replace(/[^A-Za-z0-9_-]/g, '-').slice(0, 72);+ return `r-${slug}`.slice(0, RENDER_ID_MAX);+}++/**+ * Normalize one render-history entry. Returns null for a non-object or an entry+ * without usable audio bytes (a render with no audioFilename is meaningless and+ * dropped — same drop-on-floor contract as sanitizeTrack). The id falls back to+ * a deterministic filename-derived id so re-sanitizing on read stays stable.+ */+export function sanitizeRender(raw) {+ if (!raw || typeof raw !== 'object') return null;+ const audioFilename = trackAudioFilename(raw.audioFilename);+ if (!audioFilename) return null;+ const id = isStr(raw.id) && RENDER_ID_RE.test(raw.id) ? raw.id : legacyRenderId(audioFilename);+ return {+ id,+ audioFilename,+ prompt: trimTo(raw.prompt, PROMPT_MAX),+ lyrics: trimTo(raw.lyrics, LYRICS_MAX),+ engine: trimTo(raw.engine, ENGINE_MAX),+ modelId: trimTo(raw.modelId, MODEL_ID_MAX),+ durationSec: sanitizeDuration(raw.durationSec),+ createdAt: isStr(raw.createdAt) && raw.createdAt ? raw.createdAt : new Date().toISOString(),+ };+}++// De-dup a render list by id (first wins) so a hand-edited record or a sync+// merge can't accumulate duplicate cards.+function dedupRenders(renders) {+ const seen = new Set();+ const out = [];+ for (const r of renders) {+ if (seen.has(r.id)) continue;+ seen.add(r.id);+ out.push(r);+ }+ return out;+}+/*** Normalize a raw track record into the canonical stored shape. Returns null for* a non-object or a record without a usable id/title (drop-on-floor contract).@@ -69,19 +129,48 @@ export function sanitizeTrack(raw) {const createdAt = isStr(raw.createdAt) ? raw.createdAt : new Date().toISOString();const updatedAt = isStr(raw.updatedAt) ? raw.updatedAt : createdAt;const deleted = raw.deleted === true;+ const lyrics = trimTo(raw.lyrics, LYRICS_MAX);+ const prompt = trimTo(raw.prompt, PROMPT_MAX);+ const engine = trimTo(raw.engine, ENGINE_MAX);+ const modelId = trimTo(raw.modelId, MODEL_ID_MAX);+ const durationSec = sanitizeDuration(raw.durationSec);+ // Empty string = no audio attached yet; never null so the shape is stable.+ const audioFilename = trimTo(raw.audioFilename, AUDIO_FILENAME_MAX);++ // Render history. Sanitize + de-dup + cap (newest kept). A legacy single-+ // pointer track (audio but no render array) is BACKFILLED with one synthesized+ // render from its top-level gen metadata — deterministic id + the track's own+ // createdAt, so re-sanitizing on every DB read stays stable (no drift, no new+ // id each read). New writes persist the backfilled array, healing the record.+ let renders = Array.isArray(raw.renders)+ ? dedupRenders(raw.renders.map(sanitizeRender).filter(Boolean)).slice(-RENDERS_MAX)+ : [];+ if (renders.length === 0 && audioFilename) {+ renders = [{+ id: legacyRenderId(audioFilename),+ audioFilename,+ prompt,+ lyrics,+ engine,+ modelId,+ durationSec,+ createdAt,+ }];+ }+return {id: raw.id,title,albumId: trimTo(raw.albumId, ALBUM_ID_MAX),artistId: trimTo(raw.artistId, ARTIST_ID_MAX),artist: trimTo(raw.artist, ARTIST_NAME_MAX),- lyrics: trimTo(raw.lyrics, LYRICS_MAX),- prompt: trimTo(raw.prompt, PROMPT_MAX),- engine: trimTo(raw.engine, ENGINE_MAX),- modelId: trimTo(raw.modelId, MODEL_ID_MAX),- durationSec: sanitizeDuration(raw.durationSec),- // Empty string = no audio attached yet; never null so the shape is stable.- audioFilename: trimTo(raw.audioFilename, AUDIO_FILENAME_MAX),+ lyrics,+ prompt,+ engine,+ modelId,+ durationSec,+ audioFilename,+ renders,createdAt,updatedAt,deleted,@@ -116,6 +205,7 @@ export function buildTrackRecord(input, { id, now }) {modelId: input.modelId || '',durationSec: input.durationSec ?? null,audioFilename: input.audioFilename || '',+ renders: Array.isArray(input.renders) ? input.renders : [],createdAt: now,updatedAt: now,deleted: false,@@ -123,10 +213,61 @@ export function buildTrackRecord(input, { id, now }) {});}+/**+ * Build a render-history entry from generation/upload metadata. The caller+ * supplies a unique `id` and `now` timestamp so this stays pure (no crypto/clock+ * I/O in logic.js). Returns null when there's no audio filename (sanitizeRender+ * contract).+ */+export function makeRender(input, { id, now } = {}) {+ return sanitizeRender({ ...input, id, createdAt: now });+}++/**+ * Compute the patch that makes `renderId` the ACTIVE render — copy its audio+ * pointer + gen metadata to the top level. Returns null if the render isn't in+ * the history. Deliberately does NOT touch the user-authored `prompt`/`lyrics`+ * (those are the editable source of the next generation, independent of which+ * past render is selected for playback).+ */+export function selectRenderPatch(current, renderId) {+ const r = (current?.renders || []).find((x) => x.id === renderId);+ if (!r) return null;+ return { audioFilename: r.audioFilename, engine: r.engine, modelId: r.modelId, durationSec: r.durationSec };+}++/**+ * Compute the patch that removes `renderId` from the history. When the removed+ * render was the active one, re-point the active fields at the newest remaining+ * render (or clear them when none remain). Returns null if the render isn't in+ * the history. The audio bytes are left in the shared library (may be shared).+ */+export function deleteRenderPatch(current, renderId) {+ const renders = current?.renders || [];+ const removed = renders.find((x) => x.id === renderId);+ if (!removed) return null;+ const next = renders.filter((x) => x.id !== renderId);+ const patch = { renders: next };+ if (removed.audioFilename === current.audioFilename) {+ // Re-point the active fields at the newest remaining take (reusing the same+ // mirror that selectRenderPatch applies), or clear them when none remain.+ const newest = next.length ? next[next.length - 1] : null;+ Object.assign(+ patch,+ newest+ ? selectRenderPatch({ renders: next }, newest.id)+ : { audioFilename: '', engine: '', modelId: '', durationSec: null },+ );+ }+ return patch;+}+// The user-authored fields a partial patch may overwrite. `id`, the LWW/-// tombstone trio, and `createdAt` are server-owned / structural.+// tombstone trio, and `createdAt` are server-owned / structural. `renders` is+// server-managed (generate/upload/select/delete-render routes set it); the+// generic create/patch route schemas omit it so a client can't inject history.const PATCHABLE = [- 'title', 'albumId', 'artistId', 'artist', 'lyrics', 'prompt', 'engine', 'modelId', 'durationSec', 'audioFilename',+ 'title', 'albumId', 'artistId', 'artist', 'lyrics', 'prompt', 'engine', 'modelId', 'durationSec', 'audioFilename', 'renders',];/**diff --git a/server/services/tracks/logic.test.js b/server/services/tracks/logic.test.jsindex 6015e12770..18770acc33 100644--- a/server/services/tracks/logic.test.js+++ b/server/services/tracks/logic.test.js@@ -1,7 +1,8 @@import { describe, it, expect } from 'vitest';import {sanitizeTrack, buildTrackRecord, applyTrackPatch, mergeTrackRecord, trackAudioFilename,- TITLE_MAX, LYRICS_MAX, DURATION_MIN_SEC, DURATION_MAX_SEC,+ sanitizeRender, makeRender, selectRenderPatch, deleteRenderPatch,+ TITLE_MAX, LYRICS_MAX, DURATION_MIN_SEC, DURATION_MAX_SEC, RENDERS_MAX,} from './logic.js';describe('tracks logic', () => {@@ -64,6 +65,107 @@ describe('tracks logic', () => {});});+ describe('render history', () => {+ it('backfills a legacy single-pointer track with one render (stable id, track createdAt)', () => {+ const t = sanitizeTrack({+ id: 'track-1', title: 'X', audioFilename: 'music-abc.wav',+ engine: 'musicgen', modelId: 'musicgen-medium', durationSec: 12, prompt: 'warm folk',+ createdAt: '2026-01-02T00:00:00.000Z',+ });+ expect(t.renders).toHaveLength(1);+ expect(t.renders[0]).toMatchObject({+ audioFilename: 'music-abc.wav', engine: 'musicgen', modelId: 'musicgen-medium', durationSec: 12, prompt: 'warm folk',+ createdAt: '2026-01-02T00:00:00.000Z',+ });+ // Deterministic id derived from the filename — re-sanitizing (the DB read+ // path) yields the SAME id, no drift.+ expect(sanitizeTrack(t).renders[0].id).toBe(t.renders[0].id);+ });++ it('no audio → empty render history (no synthesized entry)', () => {+ expect(sanitizeTrack({ id: 'track-1', title: 'X' }).renders).toEqual([]);+ });++ it('sanitizes, de-dups by id, and caps the render list to RENDERS_MAX (newest kept)', () => {+ const renders = [];+ for (let i = 0; i < RENDERS_MAX + 5; i += 1) {+ renders.push({ id: `render-${i}`, audioFilename: `music-${i}.wav`, createdAt: `2026-01-01T00:00:0${i % 10}.000Z` });+ }+ renders.push({ id: 'render-0', audioFilename: 'music-dupe.wav' }); // duplicate id dropped+ renders.push({ id: 'render-x', audioFilename: '' }); // no audio dropped+ const t = sanitizeTrack({ id: 'track-1', title: 'X', renders });+ expect(t.renders).toHaveLength(RENDERS_MAX);+ // Oldest fell off the front; the newest pushed entry survived.+ expect(t.renders.some((r) => r.id === 'render-x')).toBe(false);+ expect(t.renders[t.renders.length - 1].id).toBe(`render-${RENDERS_MAX + 4}`);+ });++ it('sanitizeRender drops entries without usable audio bytes', () => {+ expect(sanitizeRender({ id: 'r1' })).toBeNull();+ expect(sanitizeRender({ id: 'r1', audioFilename: '../x.wav' })).toBeNull();+ expect(sanitizeRender({ audioFilename: 'a.wav' }).id).toMatch(/^r-/); // deterministic fallback id+ });++ it('makeRender stamps the caller-supplied id + now', () => {+ const r = makeRender({ audioFilename: 'a.wav', engine: 'musicgen' }, { id: 'render-7', now: '2026-03-03T00:00:00.000Z' });+ expect(r).toMatchObject({ id: 'render-7', audioFilename: 'a.wav', engine: 'musicgen', createdAt: '2026-03-03T00:00:00.000Z' });+ });++ it('selectRenderPatch points the active fields at the chosen render, not prompt/lyrics', () => {+ const track = sanitizeTrack({+ id: 'track-1', title: 'X', audioFilename: 'b.wav', lyrics: 'keep me',+ renders: [+ { id: 'r-a', audioFilename: 'a.wav', engine: 'musicgen', modelId: 'm1', durationSec: 10 },+ { id: 'r-b', audioFilename: 'b.wav', engine: 'audioldm2', modelId: 'm2', durationSec: 20 },+ ],+ });+ const patch = selectRenderPatch(track, 'r-a');+ expect(patch).toEqual({ audioFilename: 'a.wav', engine: 'musicgen', modelId: 'm1', durationSec: 10 });+ expect(patch).not.toHaveProperty('lyrics');+ expect(selectRenderPatch(track, 'missing')).toBeNull();+ });++ it('deleteRenderPatch re-points active to newest remaining when the active take is removed', () => {+ const track = sanitizeTrack({+ id: 'track-1', title: 'X', audioFilename: 'b.wav', engine: 'audioldm2', modelId: 'm2', durationSec: 20,+ renders: [+ { id: 'r-a', audioFilename: 'a.wav', engine: 'musicgen', modelId: 'm1', durationSec: 10 },+ { id: 'r-b', audioFilename: 'b.wav', engine: 'audioldm2', modelId: 'm2', durationSec: 20 },+ ],+ });+ const patch = deleteRenderPatch(track, 'r-b'); // remove the active render+ expect(patch.renders.map((r) => r.id)).toEqual(['r-a']);+ expect(patch).toMatchObject({ audioFilename: 'a.wav', engine: 'musicgen', modelId: 'm1', durationSec: 10 });+ });++ it('deleteRenderPatch leaves the active pointer alone when a non-active take is removed', () => {+ const track = sanitizeTrack({+ id: 'track-1', title: 'X', audioFilename: 'b.wav',+ renders: [+ { id: 'r-a', audioFilename: 'a.wav' },+ { id: 'r-b', audioFilename: 'b.wav' },+ ],+ });+ const patch = deleteRenderPatch(track, 'r-a');+ expect(patch).toEqual({ renders: [expect.objectContaining({ id: 'r-b' })] });+ expect(deleteRenderPatch(track, 'missing')).toBeNull();+ });++ it('deleting the last render clears the active pointer', () => {+ const track = sanitizeTrack({ id: 'track-1', title: 'X', audioFilename: 'a.wav', engine: 'musicgen', renders: [{ id: 'r-a', audioFilename: 'a.wav', engine: 'musicgen' }] });+ const patch = deleteRenderPatch(track, 'r-a');+ expect(patch).toMatchObject({ renders: [], audioFilename: '', engine: '', modelId: '', durationSec: null });+ });++ it('renders is patchable so the route can append history', () => {+ const base = buildTrackRecord({ title: 'X' }, { id: 'track-1', now: '2026-01-01T00:00:00.000Z' });+ const r = makeRender({ audioFilename: 'a.wav', engine: 'musicgen' }, { id: 'render-1', now: '2026-01-01T00:00:00.000Z' });+ const next = applyTrackPatch(base, { renders: [r], audioFilename: 'a.wav' });+ expect(next.renders).toHaveLength(1);+ expect(next.renders[0].id).toBe('render-1');+ });+ });+describe('trackAudioFilename', () => {it('returns a bare filename, null for blank or path-ish input', () => {expect(trackAudioFilename('music-abc.mp3')).toBe('music-abc.mp3');