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

feat: pick a music-library track as code animation soundtrack (#8465)

[._.]/ Adam Eivyabc4b0a906d5
diff --git a/client/src/components/music/AlbumTrackPicker.jsx b/client/src/components/music/AlbumTrackPicker.jsx
index 0f891acc26..755470cf00 100644
--- a/client/src/components/music/AlbumTrackPicker.jsx
+++ b/client/src/components/music/AlbumTrackPicker.jsx
@@ -3,10 +3,10 @@ import { Check, Music2, Plus, Search, X } from 'lucide-react';
import Modal from '../ui/Modal';
import { formatTimecode } from '../../utils/formatters';
-// Searchable, batch-oriented picker for adding existing library tracks to an
-// album. The parent owns persistence and ordering; this component only returns
-// the selected records in their current library order.
-export default function AlbumTrackPicker({ open, tracks = [], onClose, onAdd }) {
+// Searchable picker for adding existing library tracks to an album or
+// picking a soundtrack for code animation. The parent owns persistence; this
+// component returns the selected record(s).
+export default function AlbumTrackPicker({ open, tracks = [], onClose, onAdd, title = 'Add tracks', single = false }) {
const [query, setQuery] = useState('');
const [selectedIds, setSelectedIds] = useState(() => new Set());
@@ -27,6 +27,9 @@ export default function AlbumTrackPicker({ open, tracks = [], onClose, onAdd })
const toggleTrack = (trackId) => {
setSelectedIds((previous) => {
+ if (single) {
+ return previous.has(trackId) ? new Set() : new Set([trackId]);
+ }
const next = new Set(previous);
if (next.has(trackId)) next.delete(trackId);
else next.add(trackId);
@@ -52,7 +55,7 @@ export default function AlbumTrackPicker({ open, tracks = [], onClose, onAdd })
<div className="flex items-center justify-between p-4 border-b border-port-border flex-shrink-0">
<div className="flex items-center gap-2">
<Music2 className="w-5 h-5 text-port-accent" aria-hidden="true" />
- <h2 id="album-track-picker-title" className="text-lg font-bold text-white">Add tracks</h2>
+ <h2 id="album-track-picker-title" className="text-lg font-bold text-white">{title}</h2>
</div>
<button type="button" onClick={onClose} aria-label="Close track picker" className="p-2 text-gray-500 hover:text-white rounded min-h-[44px] min-w-[44px] flex items-center justify-center">
<X size={18} aria-hidden="true" />
@@ -86,7 +89,8 @@ export default function AlbumTrackPicker({ open, tracks = [], onClose, onAdd })
<li key={track.id}>
<label className={`flex items-center gap-3 w-full p-3 rounded border bg-port-bg/40 cursor-pointer transition-colors ${checked ? 'border-port-accent' : 'border-port-border hover:border-gray-500'}`}>
<input
- type="checkbox"
+ type={single ? 'radio' : 'checkbox'}
+ name={single ? 'album-track-picker-radio' : undefined}
checked={checked}
onChange={() => toggleTrack(track.id)}
className="accent-port-accent"
@@ -111,7 +115,7 @@ export default function AlbumTrackPicker({ open, tracks = [], onClose, onAdd })
<div className="flex items-center gap-2">
<button type="button" onClick={onClose} className="px-3 py-2 rounded text-sm text-gray-400 hover:text-white">Cancel</button>
<button type="button" onClick={handleAdd} disabled={selectedIds.size === 0} className="inline-flex items-center gap-2 px-3 py-2 rounded bg-port-accent hover:bg-port-accent/90 disabled:opacity-50 disabled:cursor-not-allowed text-white text-sm font-medium">
- <Plus size={14} aria-hidden="true" /> Add selected
+ <Plus size={14} aria-hidden="true" /> {single ? 'Select track' : 'Add selected'}
</button>
</div>
</div>
diff --git a/client/src/components/music/AlbumTrackPicker.test.jsx b/client/src/components/music/AlbumTrackPicker.test.jsx
index dfa780a47f..dbe679998e 100644
--- a/client/src/components/music/AlbumTrackPicker.test.jsx
+++ b/client/src/components/music/AlbumTrackPicker.test.jsx
@@ -31,4 +31,24 @@ describe('AlbumTrackPicker', () => {
render(<AlbumTrackPicker open tracks={tracks} onAdd={() => {}} onClose={() => {}} />);
expect(screen.getByRole('button', { name: /add selected/i })).toBeDisabled();
});
+
+ it('supports single-selection mode and custom title', () => {
+ const onAdd = vi.fn();
+ const onClose = vi.fn();
+ render(<AlbumTrackPicker open tracks={tracks} onAdd={onAdd} onClose={onClose} single title="Pick soundtrack track" />);
+
+ expect(screen.getByRole('heading', { name: 'Pick soundtrack track' })).toBeTruthy();
+ const selectBtn = screen.getByRole('button', { name: /select track/i });
+ expect(selectBtn).toBeDisabled();
+
+ fireEvent.click(screen.getByLabelText('Select Daybreak'));
+ expect(selectBtn).not.toBeDisabled();
+
+ // Selecting another replaces the selection in single mode
+ fireEvent.click(screen.getByLabelText('Select Northern Lights'));
+ fireEvent.click(selectBtn);
+
+ expect(onAdd).toHaveBeenCalledWith([tracks[0]]);
+ expect(onClose).toHaveBeenCalled();
+ });
});
diff --git a/client/src/pages/CodeAnimation.jsx b/client/src/pages/CodeAnimation.jsx
index d01e002cc6..9d4bad3a05 100644
--- a/client/src/pages/CodeAnimation.jsx
+++ b/client/src/pages/CodeAnimation.jsx
@@ -3,6 +3,7 @@ import { AlertTriangle, CheckCircle2, Clock3, Copy, FileCode2, Globe, ImagePlus,
import { Link, useNavigate, useParams, useSearchParams } from 'react-router';
import PageHeader from '../components/PageHeader';
import ProviderModelSelector from '../components/ProviderModelSelector';
+import AlbumTrackPicker from '../components/music/AlbumTrackPicker';
import CodeAnimationPreview from '../components/codeAnimation/CodeAnimationPreview';
import useProviderModels from '../hooks/useProviderModels';
import { useAutoRefetch } from '../hooks/useAutoRefetch';
@@ -14,6 +15,7 @@ import {
getCodeAnimationOptions,
listCodeAnimationJobs,
listMoodBoardNames,
+ listTracks,
listUniverseNames,
listUniverseStyles,
startCodeAnimationGeneration,
@@ -69,17 +71,28 @@ const loadDraft = () => {
url: `/api/uploads/${encodeURIComponent(image.filename)}`,
}))
: [];
- const audio = isRecord(stored.audio)
- && typeof stored.audio.filename === 'string'
- && stored.audio.filename.trim()
- ? {
- filename: stored.audio.filename,
- label: typeof stored.audio.label === 'string' ? stored.audio.label : stored.audio.filename,
- durationSeconds: Number.isFinite(stored.audio.durationSeconds) ? stored.audio.durationSeconds : null,
- notes: typeof stored.audio.notes === 'string' ? stored.audio.notes : '',
- url: `/api/uploads/${encodeURIComponent(stored.audio.filename)}`,
+ let audio = null;
+ if (isRecord(stored.audio)) {
+ if (stored.audio.source === 'track' && typeof stored.audio.trackId === 'string' && stored.audio.trackId.trim()) {
+ audio = {
+ source: 'track',
+ trackId: stored.audio.trackId.trim(),
+ label: typeof stored.audio.label === 'string' ? stored.audio.label : 'Music track',
+ durationSeconds: Number.isFinite(stored.audio.durationSeconds) ? stored.audio.durationSeconds : null,
+ notes: typeof stored.audio.notes === 'string' ? stored.audio.notes : '',
+ url: typeof stored.audio.url === 'string' ? stored.audio.url : '',
+ };
+ } else if (typeof stored.audio.filename === 'string' && stored.audio.filename.trim()) {
+ audio = {
+ source: 'upload',
+ filename: stored.audio.filename.trim(),
+ label: typeof stored.audio.label === 'string' ? stored.audio.label : stored.audio.filename,
+ durationSeconds: Number.isFinite(stored.audio.durationSeconds) ? stored.audio.durationSeconds : null,
+ notes: typeof stored.audio.notes === 'string' ? stored.audio.notes : '',
+ url: `/api/uploads/${encodeURIComponent(stored.audio.filename)}`,
+ };
}
- : null;
+ }
const stringField = (key) => typeof stored[key] === 'string' ? stored[key] : DEFAULT_DRAFT[key];
return {
...DEFAULT_DRAFT,
@@ -130,7 +143,20 @@ function toBrief(draft) {
includeMoodBoardImages: draft.includeMoodBoardImages,
referenceImages: draft.referenceImages.map(({ filename, label, note }) => ({ filename, label, note })),
audio: draft.audio
- ? { filename: draft.audio.filename, label: draft.audio.label, durationSeconds: draft.audio.durationSeconds ?? null, notes: draft.audio.notes }
+ ? draft.audio.source === 'track'
+ ? {
+ source: 'track',
+ trackId: draft.audio.trackId,
+ ...(draft.audio.label ? { label: draft.audio.label } : {}),
+ ...(draft.audio.durationSeconds != null ? { durationSeconds: draft.audio.durationSeconds } : {}),
+ notes: draft.audio.notes || '',
+ }
+ : {
+ filename: draft.audio.filename,
+ label: draft.audio.label,
+ durationSeconds: draft.audio.durationSeconds ?? null,
+ notes: draft.audio.notes,
+ }
: null,
...moodBoardSelection(draft),
};
@@ -178,7 +204,20 @@ function draftFromJob(job) {
url: `/api/uploads/${encodeURIComponent(image.filename)}`,
})),
audio: input.audio
- ? { ...input.audio, url: `/api/uploads/${encodeURIComponent(input.audio.filename)}` }
+ ? input.audio.source === 'track'
+ ? {
+ source: 'track',
+ trackId: input.audio.trackId,
+ label: input.audio.label || 'Music track',
+ durationSeconds: input.audio.durationSeconds ?? null,
+ notes: input.audio.notes || '',
+ url: job.audioUrl || '',
+ }
+ : {
+ source: 'upload',
+ ...input.audio,
+ url: `/api/uploads/${encodeURIComponent(input.audio.filename)}`,
+ }
: null,
soundtrack: input.soundtrack || 'none',
format: { ...DEFAULT_DRAFT.format, ...(input.format || {}) },
@@ -240,6 +279,8 @@ export default function CodeAnimation() {
const [universes, setUniverses] = useState([]);
const [universeStyles, setUniverseStyles] = useState({});
const [boards, setBoards] = useState([]);
+ const [libraryTracks, setLibraryTracks] = useState([]);
+ const [trackPickerOpen, setTrackPickerOpen] = useState(false);
const [draft, setDraft] = useState(loadDraft);
const [uploading, setUploading] = useState(false);
const [building, setBuilding] = useState(false);
@@ -306,6 +347,9 @@ export default function CodeAnimation() {
.then((rows) => setUniverseStyles(Object.fromEntries((Array.isArray(rows) ? rows : []).map((row) => [row.id, row]))))
.catch(() => {});
listMoodBoardNames({ silent: true }).then((rows) => setBoards(Array.isArray(rows) ? rows : [])).catch(() => {});
+ listTracks({ silent: true })
+ .then((rows) => setLibraryTracks(Array.isArray(rows) ? rows : rows?.tracks || []))
+ .catch(() => {});
}, []);
const brief = useMemo(() => toBrief(draft), [draft]);
@@ -398,6 +442,22 @@ export default function CodeAnimation() {
referenceImages: prev.referenceImages.map((ref) => (ref.filename === filename ? { ...ref, ...patch } : ref)),
}));
+ const playableTracks = useMemo(() => libraryTracks.filter((t) => Boolean(t.audioFilename)), [libraryTracks]);
+
+ const handlePickTrack = (track) => {
+ if (!track) return;
+ update({
+ audio: {
+ source: 'track',
+ trackId: track.id,
+ label: track.title || 'Untitled track',
+ durationSeconds: track.durationSec ?? null,
+ notes: '',
+ url: track.audioFilename ? `/data/music/${encodeURIComponent(track.audioFilename)}` : '',
+ },
+ });
+ };
+
const handleAudio = async (event) => {
const file = event.target.files?.[0];
event.target.value = '';
@@ -405,7 +465,7 @@ export default function CodeAnimation() {
setUploading(true);
const [durationSeconds, saved] = await Promise.all([readAudioDuration(file), uploadOrToast(file)]);
setUploading(false);
- if (saved) update({ audio: { filename: saved.filename, label: file.name, durationSeconds, notes: '', url: saved.path } });
+ if (saved) update({ audio: { source: 'upload', filename: saved.filename, label: file.name, durationSeconds, notes: '', url: saved.path } });
};
// Ask a model to write the brief from the universe's bible and canon cast,
@@ -706,13 +766,25 @@ export default function CodeAnimation() {
<div className="flex items-center gap-2 text-sm text-gray-200">
<span className="min-w-0 truncate">{draft.audio.label}</span>
{draft.audio.durationSeconds ? <span className="text-xs text-gray-500">{draft.audio.durationSeconds.toFixed(1)}s</span> : null}
+ <span className="rounded bg-port-card-hover px-1.5 py-0.5 text-[10px] uppercase tracking-wider text-gray-400">
+ {draft.audio.source === 'track' ? 'Library track' : 'Upload'}
+ </span>
<button type="button" aria-label="Remove audio track" onClick={() => update({ audio: null })} className="ml-auto text-gray-500 hover:text-port-error"><X className="h-4 w-4" /></button>
</div>
<textarea aria-label="Audio notes" rows={2} value={draft.audio.notes} maxLength={limits?.audioNotesMax} onChange={(event) => update({ audio: { ...draft.audio, notes: event.target.value } })} placeholder="120 BPM; soft intro, drop at 0:16, fade at 0:40" className={`${inputClass} resize-y`} />
</div>
) : (
<div className="space-y-2">
- <input id="ca-audio" type="file" accept={audioAccept} onChange={handleAudio} disabled={uploading} className={fileInputClass} />
+ <div className="flex flex-wrap items-center gap-2">
+ <input id="ca-audio" type="file" accept={audioAccept} onChange={handleAudio} disabled={uploading} className={`${fileInputClass} flex-1 min-w-[200px]`} />
+ <button
+ type="button"
+ onClick={() => setTrackPickerOpen(true)}
+ className={buttonSecondary}
+ >
+ <Music2 className="h-3.5 w-3.5" /> Pick from music library
+ </button>
+ </div>
<label className="flex items-center gap-2 text-xs text-gray-300">
<input type="checkbox" checked={draft.soundtrack === 'procedural'} onChange={(event) => update({ soundtrack: event.target.checked ? 'procedural' : 'none' })} />
No track? Have the code compose a procedural soundtrack
@@ -808,6 +880,16 @@ export default function CodeAnimation() {
</section>
</div>
</div>
+ <AlbumTrackPicker
+ open={trackPickerOpen}
+ tracks={playableTracks}
+ onClose={() => setTrackPickerOpen(false)}
+ onAdd={([selected]) => {
+ if (selected) handlePickTrack(selected);
+ }}
+ single
+ title="Pick soundtrack track"
+ />
</div>
);
}
diff --git a/client/src/pages/CodeAnimation.test.jsx b/client/src/pages/CodeAnimation.test.jsx
index 5b531c4824..1492961e35 100644
--- a/client/src/pages/CodeAnimation.test.jsx
+++ b/client/src/pages/CodeAnimation.test.jsx
@@ -12,6 +12,7 @@ vi.mock('../services/api', () => ({
getCodeAnimationOptions: vi.fn(),
listCodeAnimationJobs: vi.fn().mockResolvedValue([]),
listMoodBoardNames: vi.fn(),
+ listTracks: vi.fn().mockResolvedValue([]),
listUniverseNames: vi.fn(),
listUniverseStyles: vi.fn(),
startCodeAnimationGeneration: vi.fn(),
@@ -43,6 +44,7 @@ import {
getCodeAnimationJob,
getCodeAnimationOptions,
listMoodBoardNames,
+ listTracks,
listUniverseNames,
listUniverseStyles,
startCodeAnimationGeneration,
@@ -80,6 +82,7 @@ describe('Code Animation page', () => {
listUniverseNames.mockResolvedValue([{ id: 'u1', name: 'Example Universe' }]);
listUniverseStyles.mockResolvedValue([{ id: 'u1', name: 'Example Universe', influences: { embrace: ['ink wash'], avoid: ['photorealism'] } }]);
listMoodBoardNames.mockResolvedValue([{ id: 'b1', name: 'Dusk' }]);
+ listTracks.mockResolvedValue([]);
buildCodeAnimationPrompt.mockResolvedValue({
prompt: 'You are an award-winning creative coder…',
attachments: [{ label: 'Night markets', origin: 'universe', url: '/data/image-refs/style-ref.png' }],
@@ -234,4 +237,56 @@ describe('Code Animation page', () => {
await waitFor(() => expect(buildCodeAnimationPrompt).toHaveBeenCalled());
expect(buildCodeAnimationPrompt.mock.calls[0][0].moodBoardId).toBe('');
});
+
+ it('picks a track from the music library, shows library badge, and sends track audio in brief', async () => {
+ const user = userEvent.setup();
+ listTracks.mockResolvedValue([
+ { id: 'track-1', title: 'Neon Rain', audioFilename: 'neon-rain.mp3', durationSec: 42.5 },
+ ]);
+ await renderPage();
+
+ expect(screen.getByRole('button', { name: /pick from music library/i })).toBeInTheDocument();
+ await user.click(screen.getByRole('button', { name: /pick from music library/i }));
+
+ expect(screen.getByText('Pick soundtrack track')).toBeInTheDocument();
+ expect(screen.getByText('Neon Rain')).toBeInTheDocument();
+
+ await user.click(screen.getByRole('radio', { name: /select neon rain/i }));
+ await user.click(screen.getByRole('button', { name: /select track/i }));
+
+ expect(screen.getByText('Neon Rain')).toBeInTheDocument();
+ expect(screen.getByText('42.5s')).toBeInTheDocument();
+ expect(screen.getByText('Library track')).toBeInTheDocument();
+
+ await user.type(screen.getByLabelText(/what happens/i), 'Robots dancing');
+ await user.click(screen.getByRole('button', { name: /build prompt/i }));
+ await waitFor(() => expect(buildCodeAnimationPrompt).toHaveBeenCalled());
+ expect(buildCodeAnimationPrompt.mock.calls[0][0].audio).toEqual({
+ source: 'track',
+ trackId: 'track-1',
+ label: 'Neon Rain',
+ durationSeconds: 42.5,
+ notes: '',
+ });
+
+ await user.click(screen.getByRole('button', { name: /remove audio track/i }));
+ expect(screen.getByRole('button', { name: /pick from music library/i })).toBeInTheDocument();
+ });
+
+ it('restores draft with library track audio from localStorage', async () => {
+ localStorage.setItem('portos.codeAnimation.draft', JSON.stringify({
+ audio: {
+ source: 'track',
+ trackId: 'track-stored',
+ label: 'Ambient Drone',
+ durationSeconds: 60,
+ },
+ }));
+
+ await renderPage();
+
+ expect(screen.getByText('Ambient Drone')).toBeInTheDocument();
+ expect(screen.getByText('60.0s')).toBeInTheDocument();
+ expect(screen.getByText('Library track')).toBeInTheDocument();
+ });
});
diff --git a/server/routes/codeAnimation.js b/server/routes/codeAnimation.js
index 65bfc71f8e..c1c43723a5 100644
--- a/server/routes/codeAnimation.js
+++ b/server/routes/codeAnimation.js
@@ -46,6 +46,24 @@ const formatSchema = z.object({
fps: z.number().int().refine((fps) => L.fpsOptions.includes(fps), 'Unsupported frame rate').default(30),
});
+const uploadAudioSchema = z.object({
+ source: z.literal('upload').optional().default('upload'),
+ filename: uploadFilenameSchema,
+ label: z.string().trim().max(200).default(''),
+ durationSeconds: z.number().positive().max(60 * 60).nullable().optional(),
+ notes: z.string().trim().max(L.audioNotesMax).default(''),
+});
+
+const trackAudioSchema = z.object({
+ source: z.literal('track'),
+ trackId: z.string().trim().min(1).max(128),
+ label: z.string().trim().max(200).optional(),
+ durationSeconds: z.number().positive().max(60 * 60).nullable().optional(),
+ notes: z.string().trim().max(L.audioNotesMax).default(''),
+});
+
+const audioSchema = z.union([trackAudioSchema, uploadAudioSchema]).nullable().optional();
+
const briefSchema = z.object({
title: z.string().trim().max(L.titleMax).default(''),
concept: z.string().trim().min(1, 'Describe what happens in the animation').max(L.conceptMax),
@@ -67,12 +85,7 @@ const briefSchema = z.object({
label: z.string().trim().max(200).default(''),
note: z.string().trim().max(L.referenceNoteMax).default(''),
})).max(L.referenceImagesMax).default([]),
- audio: z.object({
- filename: uploadFilenameSchema,
- label: z.string().trim().max(200).default(''),
- durationSeconds: z.number().positive().max(60 * 60).nullable().optional(),
- notes: z.string().trim().max(L.audioNotesMax).default(''),
- }).nullable().optional(),
+ audio: audioSchema,
}).strict();
const generateSchema = briefSchema.extend({
diff --git a/server/routes/codeAnimation.test.js b/server/routes/codeAnimation.test.js
index b33367c507..1fad6c3980 100644
--- a/server/routes/codeAnimation.test.js
+++ b/server/routes/codeAnimation.test.js
@@ -24,6 +24,7 @@ vi.mock('../services/codeAnimation/jobStore.js', () => ({
vi.mock('../services/universeBuilder/crud.js', () => ({ getUniverse: vi.fn() }));
vi.mock('../services/moodBoard/db.js', () => ({ getBoard: vi.fn() }));
vi.mock('../services/providers.js', () => ({ getProviderById: vi.fn() }));
+vi.mock('../services/tracks/index.js', () => ({ getTrack: vi.fn() }));
vi.mock('../services/promptRunner.js', () => ({
runPromptThroughProvider: vi.fn(),
resolveProviderAndModel: vi.fn(),
@@ -34,6 +35,7 @@ import { PATHS } from '../lib/paths.js';
import { getUniverse } from '../services/universeBuilder/crud.js';
import { getBoard } from '../services/moodBoard/db.js';
import { getProviderById } from '../services/providers.js';
+import { getTrack } from '../services/tracks/index.js';
import { assertProvider, resolveProviderAndModel, runPromptThroughProvider } from '../services/promptRunner.js';
import routes from './codeAnimation.js';
@@ -74,11 +76,14 @@ beforeAll(() => {
mkdirSync(PATHS.uploads, { recursive: true });
mkdirSync(PATHS.imageRefs, { recursive: true });
mkdirSync(PATHS.images, { recursive: true });
+ mkdirSync(PATHS.music, { recursive: true });
writeFileSync(join(PATHS.uploads, 'abc12345-hero.png'), 'png');
writeFileSync(join(PATHS.uploads, 'abc12345-theme.mp3'), 'mp3');
writeFileSync(join(PATHS.imageRefs, 'style-ref.png'), 'png');
writeFileSync(join(PATHS.images, 'pin.png'), 'png');
writeFileSync(join(PATHS.imageRefs, 'sheet.png'), 'png');
+ writeFileSync(join(PATHS.music, 'track-active.mp3'), 'mp3');
+ writeFileSync(join(PATHS.music, 'wavesketch-active.wav'), 'wav');
});
afterAll(cleanupTempDataRoots);
@@ -209,6 +214,79 @@ describe('POST /api/code-animation/prompt', () => {
getUniverse.mockRejectedValueOnce(Object.assign(new Error('Universe not found'), { code: 'NOT_FOUND' }));
expect((await request(app).post('/api/code-animation/prompt').send(brief)).status).toBe(404);
});
+
+ it('creates an animation with a music-library track and gets the resolved music URL and duration', async () => {
+ getTrack.mockResolvedValueOnce({
+ id: 'track-1',
+ title: 'Neon Drift',
+ audioFilename: 'track-active.mp3',
+ durationSec: 45,
+ waveSketch: null,
+ });
+ const res = await request(makeApp()).post('/api/code-animation/prompt').send({
+ ...brief,
+ audio: { source: 'track', trackId: 'track-1' },
+ });
+ expect(res.status).toBe(200);
+ expect(res.body.audioUrl).toBe('/data/music/track-active.mp3');
+ expect(res.body.prompt).toContain('"Neon Drift" (45.0s long)');
+ expect(res.body.prompt).not.toContain('Drawn waveform timing cues');
+ });
+
+ it('appends timing cues when the track has a waveSketch, but not for a plain diffusion track', async () => {
+ const sketch = {
+ version: 1,
+ title: 'Glass Tide',
+ durationSec: 2,
+ shapes: { glass: [0, 0.8, 1, 0.3, 0, -0.5, -1, -0.2] },
+ voices: [{ name: 'lead', shape: 'glass', notes: [{ t: 0, d: 1, pitch: 'A4' }, { t: 1, d: 1, pitch: 'E5' }] }],
+ contour: [0.1, 0.8, 0.4],
+ };
+ getTrack.mockResolvedValueOnce({
+ id: 'track-wave',
+ title: 'Glass Tide',
+ audioFilename: 'wavesketch-active.wav',
+ durationSec: 2,
+ waveSketch: sketch,
+ });
+ const res = await request(makeApp()).post('/api/code-animation/prompt').send({
+ ...brief,
+ audio: { source: 'track', trackId: 'track-wave' },
+ });
+ expect(res.status).toBe(200);
+ expect(res.body.audioUrl).toBe('/data/music/wavesketch-active.wav');
+ expect(res.body.prompt).toContain('Drawn waveform timing cues:');
+ expect(res.body.prompt).toContain('- Section/onset times:');
+ expect(res.body.prompt).toContain('- Strongest onsets:');
+ expect(res.body.prompt).toContain('- Loudness contour:');
+ });
+
+ it('returns 400 AUDIO_NOT_FOUND for unknown, deleted, or missing audio file track', async () => {
+ const app = makeApp();
+ getTrack.mockResolvedValueOnce(null);
+ const unknown = await request(app).post('/api/code-animation/prompt').send({
+ ...brief,
+ audio: { source: 'track', trackId: 'track-missing' },
+ });
+ expect(unknown.status).toBe(400);
+ expect(unknown.body.code).toBe('AUDIO_NOT_FOUND');
+
+ getTrack.mockResolvedValueOnce({ id: 'track-deleted', deletedAt: '2026-01-01T00:00:00Z', audioFilename: 'track-active.mp3' });
+ const deleted = await request(app).post('/api/code-animation/prompt').send({
+ ...brief,
+ audio: { source: 'track', trackId: 'track-deleted' },
+ });
+ expect(deleted.status).toBe(400);
+ expect(deleted.body.code).toBe('AUDIO_NOT_FOUND');
+
+ getTrack.mockResolvedValueOnce({ id: 'track-no-file', audioFilename: 'ghost-file.mp3' });
+ const missingFile = await request(app).post('/api/code-animation/prompt').send({
+ ...brief,
+ audio: { source: 'track', trackId: 'track-no-file' },
+ });
+ expect(missingFile.status).toBe(400);
+ expect(missingFile.body.code).toBe('AUDIO_NOT_FOUND');
+ });
});
describe('POST /api/code-animation/generate', () => {
diff --git a/server/services/codeAnimation/index.js b/server/services/codeAnimation/index.js
index 6f92419c31..2b75ee09d1 100644
--- a/server/services/codeAnimation/index.js
+++ b/server/services/codeAnimation/index.js
@@ -19,6 +19,8 @@ import { makePathResolver, resolveGalleryImage, resolveImageRef } from '../../li
import { universeVisualStyleTokens } from '../../lib/universeVisualStyle.js';
import { isNonBlankStr, trimTo } from '../../lib/textUtils.js';
import { UPLOAD_AUDIO_EXTENSIONS } from '../../lib/mimeTypes.js';
+import { normalizeWaveSketch } from '../../lib/waveSketch.js';
+import { SUPPORTED_AUDIO_EXTENSIONS } from '../pipeline/musicLibrary.js';
import {
getCodeAnimationJobRecord,
isCodeAnimationJobId,
@@ -42,6 +44,7 @@ import {
const IMAGE_EXTENSIONS = ['png', 'jpg', 'jpeg', 'webp', 'gif'];
const resolveUploadImage = makePathResolver(() => PATHS.uploads, { extensions: IMAGE_EXTENSIONS });
const resolveUploadAudio = makePathResolver(() => PATHS.uploads, { extensions: UPLOAD_AUDIO_EXTENSIONS });
+const resolveMusicAudio = makePathResolver(() => PATHS.music, { extensions: SUPPORTED_AUDIO_EXTENSIONS });
// This process-local set distinguishes live work from persisted jobs left
// running by a previous server process. Those are marked interrupted when the
@@ -168,12 +171,123 @@ function resolveUploadedImages(referenceImages) {
});
}
-function resolveAudio(audio) {
+/**
+ * Derive compact timing cues from a track's drawn waveform (waveSketch).
+ * Returns prompt-ready cue text covering section/onset times, strongest note
+ * or stroke onsets, and the loudness contour, or '' if no valid sketch.
+ */
+export function _deriveWaveSketchCues(rawSketch) {
+ const sketch = normalizeWaveSketch(rawSketch);
+ if (!sketch) return '';
+
+ const durationSec = sketch.durationSec;
+ const strokes = [];
+ for (const voice of sketch.voices || []) {
+ const gain = typeof voice.gain === 'number' ? voice.gain : 0.6;
+ for (const note of voice.notes || []) {
+ const v = typeof note.v === 'number' ? note.v : 0.8;
+ strokes.push({
+ voice: voice.name || 'voice',
+ t: note.t,
+ d: note.d,
+ hz: note.hz,
+ pitch: note.pitch,
+ v,
+ strength: v * gain,
+ });
+ }
+ }
+
+ if (strokes.length === 0) return '';
+
+ // 1. Section and onset times
+ const uniqueOnsets = [...new Set(strokes.map((s) => Math.round(s.t * 100) / 100))].sort((a, b) => a - b);
+ const formattedOnsets = uniqueOnsets.slice(0, 16).map((t) => `${t.toFixed(1)}s`).join(', ');
+ const onsetSummary = uniqueOnsets.length > 16 ? `${formattedOnsets} (+${uniqueOnsets.length - 16} more)` : formattedOnsets;
+
+ // 2. Strongest note or stroke onsets
+ const strongest = [...strokes]
+ .sort((a, b) => b.strength - a.strength)
+ .slice(0, 6)
+ .sort((a, b) => a.t - b.t);
+ const formattedStrongest = strongest.map((s) => {
+ const pitchStr = s.pitch || (s.hz ? `${Math.round(s.hz)}Hz` : '');
+ const voicePitch = pitchStr ? `${s.voice} ${pitchStr}` : s.voice;
+ return `${s.t.toFixed(1)}s: ${voicePitch} (vel ${s.v.toFixed(2)})`;
+ }).join('; ');
+
+ // 3. Loudness contour
+ let contourSummary = '';
+ if (Array.isArray(sketch.contour) && sketch.contour.length >= 2) {
+ const count = Math.min(6, sketch.contour.length);
+ const sampled = [];
+ for (let i = 0; i < count; i++) {
+ const idx = Math.round((i / (count - 1)) * (sketch.contour.length - 1));
+ const t = (i / (count - 1)) * durationSec;
+ sampled.push(`${t.toFixed(1)}s: ${Math.round(sketch.contour[idx] * 100)}%`);
+ }
+ contourSummary = sampled.join(' -> ');
+ } else {
+ const steps = 4;
+ const sampled = [];
+ for (let i = 0; i <= steps; i++) {
+ const t = (i / steps) * durationSec;
+ const active = strokes.filter((s) => (t >= s.t && t <= s.t + s.d) || Math.abs(s.t - t) < 0.25);
+ const energy = active.length > 0
+ ? Math.min(1, active.reduce((max, s) => Math.max(max, s.strength), 0))
+ : 0;
+ sampled.push(`${t.toFixed(1)}s: ${Math.round(energy * 100)}%`);
+ }
+ contourSummary = sampled.join(' -> ');
+ }
+
+ const lines = [
+ 'Drawn waveform timing cues:',
+ `- Section/onset times: ${onsetSummary}`,
+ `- Strongest onsets: ${formattedStrongest}`,
+ `- Loudness contour: ${contourSummary}`,
+ ];
+
+ return lines.join('\n');
+}
+
+async function resolveAudio(audio) {
if (!audio) return null;
+
+ if (audio.source === 'track' || audio.trackId) {
+ const { getTrack } = await import('../tracks/index.js');
+ const track = await getTrack(audio.trackId);
+ if (!track || track.deletedAt) {
+ throw new ServerError(`Track not found: ${audio.trackId}`, { status: 400, code: 'AUDIO_NOT_FOUND' });
+ }
+ if (!track.audioFilename || !resolveMusicAudio(track.audioFilename)) {
+ throw new ServerError(`Audio file not found: ${track.audioFilename || audio.trackId}`, { status: 400, code: 'AUDIO_NOT_FOUND' });
+ }
+ const name = trimTo(audio.label, 200) || trimTo(track.title, 200) || track.audioFilename;
+ const durationSeconds = audio.durationSeconds ?? track.durationSec ?? null;
+ let notes = isNonBlankStr(audio.notes) ? trimTo(audio.notes, CODE_ANIMATION_LIMITS.audioNotesMax) : '';
+ if (track.waveSketch) {
+ const cues = _deriveWaveSketchCues(track.waveSketch);
+ if (cues) {
+ notes = notes ? `${notes}\n\n${cues}` : cues;
+ notes = trimTo(notes, CODE_ANIMATION_LIMITS.audioNotesMax);
+ }
+ }
+ return {
+ source: 'track',
+ trackId: track.id,
+ name,
+ durationSeconds,
+ notes,
+ url: `/data/music/${encodeURIComponent(track.audioFilename)}`,
+ };
+ }
+
if (!resolveUploadAudio(audio.filename)) {
throw new ServerError(`Audio file not found: ${audio.filename}`, { status: 400, code: 'AUDIO_NOT_FOUND' });
}
return {
+ source: 'upload',
name: trimTo(audio.label, 200) || audio.filename,
durationSeconds: audio.durationSeconds ?? null,
notes: audio.notes,
@@ -188,7 +302,7 @@ function resolveAudio(audio) {
*/
export async function buildCodeAnimationRequest(input, { delivery = 'copy' } = {}) {
const uploads = resolveUploadedImages(input.referenceImages || []);
- const audio = resolveAudio(input.audio);
+ const audio = await resolveAudio(input.audio);
const universe = await resolveUniverse(input.universeId, {
imageSlots: Math.max(0, CODE_ANIMATION_LIMITS.referenceImagesMax - uploads.length),
});
diff --git a/server/services/codeAnimation/index.test.js b/server/services/codeAnimation/index.test.js
new file mode 100644
index 0000000000..cb68d308cd
--- /dev/null
+++ b/server/services/codeAnimation/index.test.js
@@ -0,0 +1,76 @@
+import { describe, expect, it } from 'vitest';
+import { _deriveWaveSketchCues } from './index.js';
+import { CODE_ANIMATION_LIMITS } from './prompt.js';
+
+describe('_deriveWaveSketchCues', () => {
+ it('returns empty string for null, invalid, or empty sketches', () => {
+ expect(_deriveWaveSketchCues(null)).toBe('');
+ expect(_deriveWaveSketchCues({})).toBe('');
+ expect(_deriveWaveSketchCues({ voices: [] })).toBe('');
+ expect(_deriveWaveSketchCues({ voices: [{ name: 'v', shape: 's', notes: [] }] })).toBe('');
+ });
+
+ it('derives section/onset times, strongest onsets, and sampled contour from a valid waveSketch', () => {
+ const sketch = {
+ version: 1,
+ title: 'Neon Drift',
+ durationSec: 8,
+ shapes: { synth: [0, 0.5, 1, 0, -1, -0.5] },
+ voices: [
+ {
+ name: 'bass',
+ shape: 'synth',
+ gain: 0.8,
+ notes: [
+ { t: 0, d: 2, pitch: 'C2', v: 0.9 },
+ { t: 4, d: 2, pitch: 'G2', v: 1.0 },
+ ],
+ },
+ {
+ name: 'lead',
+ shape: 'synth',
+ gain: 0.7,
+ notes: [
+ { t: 1, d: 1, pitch: 'E4', v: 0.7 },
+ { t: 2, d: 1, pitch: 'G4', v: 0.8 },
+ { t: 5, d: 1, pitch: 'B4', v: 0.95 },
+ ],
+ },
+ ],
+ contour: [0.2, 0.4, 0.7, 0.9, 0.6, 0.3],
+ };
+
+ const cues = _deriveWaveSketchCues(sketch);
+ expect(cues).toContain('Drawn waveform timing cues:');
+ expect(cues).toContain('- Section/onset times: 0.0s, 1.0s, 2.0s, 4.0s, 5.0s');
+ expect(cues).toContain('- Strongest onsets:');
+ expect(cues).toContain('bass C2');
+ expect(cues).toContain('lead B4');
+ expect(cues).toContain('- Loudness contour:');
+ expect(cues.length).toBeLessThanOrEqual(CODE_ANIMATION_LIMITS.audioNotesMax);
+ });
+
+ it('computes timeline energy checkpoints when contour array is absent', () => {
+ const sketch = {
+ version: 1,
+ durationSec: 4,
+ shapes: { bell: [0, 0.8, 1, 0.3, -0.3, -1, -0.8] },
+ voices: [
+ {
+ name: 'bell',
+ shape: 'bell',
+ gain: 0.9,
+ notes: [
+ { t: 0, d: 1, hz: 440, v: 0.8 },
+ { t: 2, d: 1, hz: 880, v: 0.6 },
+ ],
+ },
+ ],
+ };
+
+ const cues = _deriveWaveSketchCues(sketch);
+ expect(cues).toContain('- Loudness contour:');
+ expect(cues).toContain('0.0s:');
+ expect(cues).toContain('->');
+ });
+});