Skip to content

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

fix: distinguish same-title tracks in Music Video selectors (#9764)

Adam Eivyb1bc6a533699
diff --git a/client/src/components/musicVideo/AudioTimingPanel.jsx b/client/src/components/musicVideo/AudioTimingPanel.jsx
index b9fc2d6e08..d57457877c 100644
--- a/client/src/components/musicVideo/AudioTimingPanel.jsx
+++ b/client/src/components/musicVideo/AudioTimingPanel.jsx
@@ -1,6 +1,7 @@
import { useRef, useState } from 'react';
import { previewMusicVideoAudioTiming, applyMusicVideoAudioTiming } from '../../services/apiMusicVideo.js';
import { formatCount } from '../../utils/formatters.js';
+import { trackOptionLabels } from '../../utils/trackOptionLabels.js';
const seconds = (value) => value == null ? '—' : `${Number(value).toFixed(2)}s`;
@@ -12,6 +13,7 @@ export default function AudioTimingPanel({ project, tracks, onApplied, disabled
const [preview, setPreview] = useState(null);
const [busy, setBusy] = useState(false);
const [error, setError] = useState('');
+ const optionLabels = trackOptionLabels(tracks || []);
const generation = useRef(0);
const change = (fn) => { generation.current++; setPreview(null); setError(''); fn(); };
const cancel = () => change(() => { setOpen(false); });
@@ -39,7 +41,7 @@ export default function AudioTimingPanel({ project, tracks, onApplied, disabled
<label htmlFor="audio-timing-track" className="block text-sm">Edited track</label>
<select id="audio-timing-track" value={targetTrackId} onChange={(event) => change(() => setTargetTrackId(event.target.value))} className="w-full rounded border border-port-border bg-port-bg p-2">
<option value="">Choose a library track</option>
- {(tracks || []).filter((track) => track.audioFilename && track.id !== project.trackId).map((track) => <option key={track.id} value={track.id}>{track.title || track.id}</option>)}
+ {(tracks || []).filter((track) => track.audioFilename && track.id !== project.trackId).map((track) => <option key={track.id} value={track.id}>{optionLabels.get(track.id)}</option>)}
</select>
{intervals.map((row, index) => (
<div key={index} className="flex flex-wrap items-end gap-2">
diff --git a/client/src/components/musicVideo/CreateProjectDrawer.jsx b/client/src/components/musicVideo/CreateProjectDrawer.jsx
index 6b751537ec..6bb9d8041f 100644
--- a/client/src/components/musicVideo/CreateProjectDrawer.jsx
+++ b/client/src/components/musicVideo/CreateProjectDrawer.jsx
@@ -6,6 +6,7 @@ import AutomationBriefFields from './AutomationBriefFields.jsx';
import MoodBoardReferenceStrip from '../moodBoard/MoodBoardReferenceStrip.jsx';
import { trackSourceLabel } from '../../lib/trackProvenance.js';
import { formatDurationSec } from '../../utils/formatters.js';
+import { trackOptionLabels } from '../../utils/trackOptionLabels.js';
const inputClass = 'w-full min-w-0 bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm';
const MODES = [
@@ -21,6 +22,7 @@ const MODES = [
*/
export default function CreateProjectDrawer({ open, onClose, form, onFormChange, tracks, universes, trackName, youtube, onSubmit, submitting }) {
const autopilot = form.mode === 'autonomous';
+ const optionLabels = trackOptionLabels(tracks || []);
const selectedTrack = (tracks || []).find((t) => t.id === form.trackId) || null;
const sourceLabel = trackSourceLabel(selectedTrack);
@@ -65,7 +67,7 @@ export default function CreateProjectDrawer({ open, onClose, form, onFormChange,
<option value="">— choose from music library —</option>
{(tracks || []).map((t) => (
<option key={t.id} value={t.id}>
- {t.title || t.id}{t.artist ? ` · ${t.artist}` : ''}
+ {optionLabels.get(t.id)}
</option>
))}
</select>
diff --git a/client/src/components/musicVideo/SoundBedControl.jsx b/client/src/components/musicVideo/SoundBedControl.jsx
index 8d06a2eeff..3476d03656 100644
--- a/client/src/components/musicVideo/SoundBedControl.jsx
+++ b/client/src/components/musicVideo/SoundBedControl.jsx
@@ -2,6 +2,7 @@ import { useState } from 'react';
import { Waves } from 'lucide-react';
import toast from '../ui/Toast';
import { updateMusicVideoProject } from '../../services/apiMusicVideo.js';
+import { trackOptionLabels } from '../../utils/trackOptionLabels.js';
const DEFAULT_VOLUME = 0.3;
@@ -19,6 +20,7 @@ export default function SoundBedControl({ project, tracks, disabled, onUpdated }
const selectId = `mv-sound-bed-${project.id}`;
const volumeId = `mv-sound-bed-volume-${project.id}`;
const candidates = tracks.filter((t) => t.id !== project.trackId);
+ const optionLabels = trackOptionLabels(tracks);
const save = (soundBed) => {
setBusy(true);
@@ -44,7 +46,7 @@ export default function SoundBedControl({ project, tracks, disabled, onUpdated }
onChange={(e) => save(e.target.value ? { trackId: e.target.value, volume } : null)}
className="bg-port-bg border border-port-border rounded px-1.5 py-1 disabled:opacity-50 max-w-[16rem] min-h-[44px] sm:min-h-0">
<option value="">None — the song is the only audio</option>
- {candidates.map((t) => <option key={t.id} value={t.id}>{t.title || t.id}</option>)}
+ {candidates.map((t) => <option key={t.id} value={t.id}>{optionLabels.get(t.id)}</option>)}
</select>
</div>
{bed && (
diff --git a/client/src/components/musicVideo/TrackPanel.jsx b/client/src/components/musicVideo/TrackPanel.jsx
index 621902ecc2..20a8f35a68 100644
--- a/client/src/components/musicVideo/TrackPanel.jsx
+++ b/client/src/components/musicVideo/TrackPanel.jsx
@@ -6,6 +6,7 @@ import YoutubeImportControls from './YoutubeImportControls.jsx';
import VocalStemControl from './VocalStemControl.jsx';
import SoundBedControl from './SoundBedControl.jsx';
import { trackSourceLabel } from '../../lib/trackProvenance.js';
+import { trackOptionLabels } from '../../utils/trackOptionLabels.js';
/**
* The project's audio: pick an existing library track or import fresh audio from
@@ -29,6 +30,7 @@ export default function TrackPanel({
// Where the linked track's audio came from (e.g. a Suno export, #8967).
const sourceLabel = trackSourceLabel(tracks.find((t) => t.id === project.trackId));
const midiFile = project.midiTranscription?.filename;
+ const optionLabels = trackOptionLabels(tracks);
return (
<>
<div className="mt-2 flex flex-wrap items-center gap-2 text-xs">
@@ -44,7 +46,7 @@ export default function TrackPanel({
title={blockedMessage || undefined}
className="bg-port-bg border border-port-border rounded px-1.5 py-1 disabled:opacity-50 min-h-[44px] sm:min-h-0">
<option value="">Change track…</option>
- {tracks.map((t) => <option key={t.id} value={t.id}>{t.title || t.id}</option>)}
+ {tracks.map((t) => <option key={t.id} value={t.id}>{optionLabels.get(t.id)}</option>)}
</select>
<YoutubeImportControls
url={youtube.editUrl} onUrlChange={(e) => youtube.setEditUrl(e.target.value)}
diff --git a/client/src/components/musicVideo/TrackSelectors.test.jsx b/client/src/components/musicVideo/TrackSelectors.test.jsx
new file mode 100644
index 0000000000..bc8dff8833
--- /dev/null
+++ b/client/src/components/musicVideo/TrackSelectors.test.jsx
@@ -0,0 +1,106 @@
+import { useState } from 'react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { fireEvent, render, screen, within, waitFor } from '@testing-library/react';
+import CreateProjectDrawer from './CreateProjectDrawer.jsx';
+import TrackPanel from './TrackPanel.jsx';
+import AudioTimingPanel from './AudioTimingPanel.jsx';
+import SoundBedControl from './SoundBedControl.jsx';
+import * as api from '../../services/apiMusicVideo.js';
+
+vi.mock('../../services/apiMusicVideo.js', () => ({
+ previewMusicVideoAudioTiming: vi.fn(),
+ applyMusicVideoAudioTiming: vi.fn(),
+ updateMusicVideoProject: vi.fn(),
+}));
+vi.mock('../moodBoard/MoodBoardReferenceStrip.jsx', () => ({ default: () => null }));
+vi.mock('./VocalStemControl.jsx', () => ({ default: () => null }));
+vi.mock('../ui/Toast', () => ({ default: { success: vi.fn(), error: vi.fn() } }));
+
+const common = { title: 'Example Song', artist: 'Example Artist', durationSec: 75, createdAt: '2026-01-02T12:00:00Z' };
+const tracks = [
+ { ...common, id: 'example-a-123456', audioFilename: 'example-a.wav', lyrics: 'One line', renders: [{ audioFilename: 'example-a.wav', source: 'suno' }] },
+ { ...common, id: 'example-b-123456', audioFilename: 'example-b.wav', lyrics: 'First line\nSecond line', renders: [{ audioFilename: 'example-b.wav', source: 'youtube' }] },
+ { ...common, id: 'example-long', durationSec: 90, createdAt: '2025-01-02T12:00:00Z', audioFilename: 'example-long.wav' },
+ { id: 'example-missing', title: ' ', durationSec: null, createdAt: 'invalid' },
+];
+const project = { id: 'example-project', trackId: tracks[0].id, audioAnalysis: { durationSec: 75 } };
+const youtube = {
+ createJob: { active: false }, editJob: { active: false }, createUrl: '', editUrl: '',
+ setCreateUrl: vi.fn(), setEditUrl: vi.fn(), startCreate: vi.fn(), startEdit: vi.fn(),
+};
+const trackName = (id) => tracks.find((track) => track.id === id)?.title || id;
+
+beforeEach(() => vi.clearAllMocks());
+
+// Uniquely catches inaccessible duplicate choices, wrong-record selection,
+// and eligibility drift at the rendered selectors rather than helper internals.
+describe('Music Video track choices', () => {
+ it('distinguishes colliding records and shows metadata for the chosen ID without submitting or importing', () => {
+ const onSubmit = vi.fn();
+ function NewProject() {
+ const [form, setForm] = useState({ mode: 'director', mediaMode: 'code-images-video', name: '', trackId: '', universeId: '' });
+ return <CreateProjectDrawer open form={form} onFormChange={(patch) => setForm((current) => ({ ...current, ...patch }))}
+ tracks={tracks} universes={[]} trackName={trackName} youtube={youtube} onSubmit={onSubmit} onClose={vi.fn()} />;
+ }
+ render(<NewProject />);
+ const select = screen.getByRole('combobox', { name: /Track \(music audio source\)/ });
+ const first = within(select).getByRole('option', { name: /Example Song · Example Artist · 1:15 · Created .*2026 \[a-123456\]/ });
+ const second = within(select).getByRole('option', { name: /Example Song · Example Artist · 1:15 · Created .*2026 \[b-123456\]/ });
+ expect(first.value).toBe(tracks[0].id);
+ expect(second.value).toBe(tracks[1].id);
+ expect(within(select).getByRole('option', { name: /1:30 · Created .*2025$/ })).toHaveValue('example-long');
+ expect(within(select).getByRole('option', { name: 'Untitled track · Duration unknown · Created unknown · No audio' })).toHaveValue('example-missing');
+ select.focus();
+ fireEvent.change(select, { target: { value: second.value } });
+ expect(select).toHaveFocus();
+ expect(select).toHaveValue(tracks[1].id);
+ expect(screen.getByText('YouTube')).toBeInTheDocument();
+ expect(screen.getByText('2 lyric lines loaded')).toBeInTheDocument();
+ expect(screen.queryByText('Suno')).not.toBeInTheDocument();
+ expect(onSubmit).not.toHaveBeenCalled();
+ expect(youtube.startCreate).not.toHaveBeenCalled();
+ });
+
+ it('uses the same stable labels after reordering and relinks the exact ID while preserving render locks', () => {
+ const onChangeTrack = vi.fn();
+ const props = { project, tracks, trackName, youtube, onChangeTrack, onProjectUpdated: vi.fn() };
+ const { rerender } = render(<TrackPanel {...props} />);
+ const select = screen.getByRole('combobox', { name: 'Change track' });
+ const labels = Array.from(select.options, (option) => [option.value, option.textContent]);
+ expect(within(select).getByRole('option', { name: /\[b-123456\]$/ })).toHaveValue(tracks[1].id);
+ expect(within(select).getByRole('option', { name: /No audio$/ })).toHaveValue('example-missing');
+ fireEvent.change(select, { target: { value: tracks[1].id } });
+ expect(onChangeTrack).toHaveBeenCalledWith(tracks[1].id);
+ expect(api.updateMusicVideoProject).not.toHaveBeenCalled();
+ expect(youtube.startEdit).not.toHaveBeenCalled();
+ rerender(<TrackPanel {...props} tracks={[...tracks].reverse()} renderBound />);
+ expect(select).toBeDisabled();
+ for (const [id, label] of labels) expect(Array.from(select.options).find((option) => option.value === id)?.textContent).toBe(label);
+ });
+
+ it('keeps timing revisions audio-only, excludes the current track, and waits for explicit preview', () => {
+ render(<AudioTimingPanel project={project} tracks={tracks} onApplied={vi.fn()} />);
+ fireEvent.click(screen.getByRole('button', { name: 'Preview audio timing revision' }));
+ const select = screen.getByRole('combobox', { name: 'Edited track' });
+ expect(Array.from(select.options, (option) => option.value)).toEqual(['', tracks[1].id, 'example-long']);
+ const second = within(select).getByRole('option', { name: /\[b-123456\]$/ });
+ fireEvent.change(select, { target: { value: second.value } });
+ expect(select).toHaveValue(tracks[1].id);
+ expect(api.previewMusicVideoAudioTiming).not.toHaveBeenCalled();
+ expect(api.applyMusicVideoAudioTiming).not.toHaveBeenCalled();
+ });
+
+ it('keeps sound-bed eligibility and saves the intended duplicate ID without media processing', async () => {
+ const onUpdated = vi.fn();
+ const updated = { ...project, soundBed: { trackId: tracks[1].id, volume: 0.3 } };
+ api.updateMusicVideoProject.mockResolvedValue(updated);
+ render(<SoundBedControl project={project} tracks={tracks} onUpdated={onUpdated} />);
+ const select = screen.getByRole('combobox', { name: 'Sound-design bed' });
+ expect(Array.from(select.options, (option) => option.value)).toEqual(['', tracks[1].id, 'example-long', 'example-missing']);
+ fireEvent.change(select, { target: { value: within(select).getByRole('option', { name: /\[b-123456\]$/ }).value } });
+ await waitFor(() => expect(onUpdated).toHaveBeenCalledWith(updated));
+ expect(api.updateMusicVideoProject).toHaveBeenCalledWith(project.id, { soundBed: { trackId: tracks[1].id, volume: 0.3 } }, { silent: true });
+ expect(api.previewMusicVideoAudioTiming).not.toHaveBeenCalled();
+ expect(api.applyMusicVideoAudioTiming).not.toHaveBeenCalled();
+ });
+});
diff --git a/client/src/utils/README.md b/client/src/utils/README.md
index 7e87114e66..3a60f80e96 100644
--- a/client/src/utils/README.md
+++ b/client/src/utils/README.md
@@ -22,6 +22,7 @@ grep -i "what you want to do" client/src/utils/README.md
| Module | Purpose |
|---|---|
+| `trackOptionLabels` | `trackOptionLabels(tracks)` — ID-keyed library option labels with title, artist, duration, creation date, missing-audio status, and stable collision-resolving ID suffixes. Build before filtering selector eligibility. |
| `formatters` | Date/time/duration/byte formatters (`clamp`, `formatBytes`, `formatDownloadGb` (decimal-GB model download size, "~29 GB"), `formatCompactCount`, `formatCompactCountOrDash` (same, but an ABSENT count renders "—" rather than "0"), `formatCount` (thousands-separated EXACT count, "2,762" — for a total the user is meant to read as a number, where "2.8K" would throw away the precision that is the point of showing it), `timeAgo`, `formatAgeDays` (age in whole DAYS — "412 days ago" — where `timeAgo` would collapse to "1y ago"; model-download lists), `localDateKey` (browser-local `YYYY-MM-DD`), `shiftISODate` (DST-safe calendar-day shifts), `formatTimecode`, `formatDurationMs`, `formatDateShort`, `formatContextTokens` (suffix-less context length, "4K"), `throughputLabel` (a measured model's speed as one label — tok/s where the runtime reported token counts, `~` prefixed when frame-counted, else chars/s; never both), `parseTimeoutMs`, `formatCooldown`, `recommendedRamGb`, `nameFromImageFilename`, `formatUsd` — one USD renderer (`signed` puts the minus outside the `$`; `trimWhole` drops `.00` on a typed round price; thousands are grouped, "$4,610.09") — `formatWeight` / `formatPercent` — round unit-converted floats (`170.35000000000002` → `170.4 lbs`) so raw binary precision never reaches a tile — `middleTruncate` — clip a long string from the MIDDLE so its distinguishing tail survives, where CSS `line-clamp`/`text-overflow` always eats the end — …) plus timeout-input bounds and `getAppName`. Do not re-define formatters inside components. **Never write `new Date(x).toLocaleDateString()` inline** — pick the helper for the shape you want: `formatDateNumeric` ("3/5/2026", compact cells), `formatDateShort` ("Mar 5, 2026"), `formatDate` ("March 5, 2026"), `formatDateFull` ("Saturday, March 5, 2026"), `formatWeekdayDate` ("Monday, Mar 5", `{ weekday, year }`), `formatMonthDay` ("Mar 5"), `formatMonthYear` ("March 2026"), `formatWeekdayShort` ("Mon"), `formatWeekdayTime` ("Mon, 7:00 AM"), `formatTimeOfDay` ("1:30 PM"), `formatTimeOfDaySeconds` ("1:30:45 PM", log/queue rows), `formatClockTime` ("02:30:45 PM"; `{ seconds, hour12, timeZone }`), `formatDateTime`. `formatHourOfDay` renders a bare hour-of-day number (0-23) as a 12-hour label in one of four styles (`long` "3 PM", `compact` "3PM", `tiny` "3p", `lower` "3pm") — the canonical home for what five components each hand-rolled, so the same 3pm no longer renders four ways across screens. Date display helpers anchor a bare `YYYY-MM-DD` at LOCAL midnight (a naive `new Date('2026-03-05')` is UTC midnight and renders as the previous day west of Greenwich) and take a fallback instead of rendering the literal "Invalid Date". |
| `cronHelpers` | Cron preset list, friendly cron parsing/building, anchored recurrence parsing/building/description, `isCronExpression` detection, `describeCron` human-readable rendering, `cronFromIntervalMs` numeric-interval → expression conversion (mirrors the server helper), `summarizeAppSchedules` rendering of the per-app cron cadences a task's global row cannot express, and `JOB_INTERVAL_OPTIONS` / `ON_DEMAND_INTERVAL` — the interval-mode cadences for autonomous jobs, derived from the server's `INTERVAL_OPTIONS` (`on-demand` = stays enabled and manually runnable, but arms no timer). Import it rather than re-declaring the list in a scheduling component. |
| `markdownText` | `markdownToPlainText(md)` — flatten markdown source to one plain-text string for a clamped preview: strips heading/list/blockquote/fence markers, unwraps emphasis, inline code and links, images → `[alt]`, collapses blank-line runs. Use whenever a card previews arbitrary agent-authored markdown — `line-clamp-N` does not clamp a subtree of block elements, and foreign `##` headings would otherwise join the page's heading outline. Underscore emphasis is word-boundary gated and `__…__` needs interior whitespace, so stack frames and user-agent strings (`10_15_7`, `__init__`) are never silently rewritten. `dropsMarkupWhenFlattened(md)` — did the flatten lose actual markup, as opposed to only normalizing whitespace? Gates a "Show more" disclosure so a short-but-lossy body stays reachable without putting a toggle on every body that merely lost a trailing newline. |
diff --git a/client/src/utils/index.js b/client/src/utils/index.js
index d65e9a65e6..f852c0ce26 100644
--- a/client/src/utils/index.js
+++ b/client/src/utils/index.js
@@ -11,6 +11,7 @@
// === Formatting & time ===
export * from './formatters.js';
+export * from './trackOptionLabels.js';
export * from './cronHelpers.js';
export * from './markdownText.js';
export * from './timeWindow.js';
diff --git a/client/src/utils/trackOptionLabels.js b/client/src/utils/trackOptionLabels.js
new file mode 100644
index 0000000000..4c571889b4
--- /dev/null
+++ b/client/src/utils/trackOptionLabels.js
@@ -0,0 +1,33 @@
+import { formatDateShort, formatDurationSec } from './formatters.js';
+
+/**
+ * Shared library-track option text, keyed by record ID. Build against the full
+ * library before filtering eligibility so labels agree across selectors.
+ */
+export function trackOptionLabels(tracks = []) {
+ const groups = new Map();
+ for (const track of tracks) {
+ const duration = formatDurationSec(track.durationSec);
+ const created = formatDateShort(track.createdAt);
+ const label = [
+ track.title?.trim() || 'Untitled track',
+ track.artist?.trim(),
+ duration === '—' ? 'Duration unknown' : duration,
+ created === '—' ? 'Created unknown' : `Created ${created}`,
+ !track.audioFilename && 'No audio',
+ ].filter(Boolean).join(' · ');
+ if (!groups.has(label)) groups.set(label, []);
+ groups.get(label).push(track.id);
+ }
+
+ const labels = new Map();
+ for (const [label, ids] of groups) {
+ // Extend the shared suffix length until every colliding ID is distinct.
+ // IDs, rather than list positions, keep the result stable after reordering.
+ let length = 6;
+ const maxLength = Math.max(...ids.map((id) => id.length));
+ while (length < maxLength && new Set(ids.map((id) => id.slice(-length))).size < ids.length) length++;
+ for (const id of ids) labels.set(id, ids.length > 1 ? `${label} [${id.slice(-length)}]` : label);
+ }
+ return labels;
+}