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

add Code Animation page that prompts an LLM to code a universe-styled animation film

[._.]/ Adam Eivy5459d4567d43
diff --git a/client/src/App.jsx b/client/src/App.jsx
index d9c981bb15..931fccaa6a 100644
--- a/client/src/App.jsx
+++ b/client/src/App.jsx
@@ -81,6 +81,7 @@ const Game = lazyWithReload(() => import('./pages/Game'));
const MusicVideo = lazyWithReload(() => import('./pages/MusicVideo'));
const Sprites = lazyWithReload(() => import('./pages/Sprites'));
const MoodBoards = lazyWithReload(() => import('./pages/MoodBoards'));
+const CodeAnimation = lazyWithReload(() => import('./pages/CodeAnimation'));
const MoodBoardDetail = lazyWithReload(() => import('./pages/MoodBoardDetail'));
const Decks = lazyWithReload(() => import('./pages/Decks'));
const DeckDetail = lazyWithReload(() => import('./pages/DeckDetail'));
@@ -592,6 +593,7 @@ export default function App() {
<Route path="catalog" element={<Catalog />} />
<Route path="catalog/ingest" element={<CatalogIngest />} />
<Route path="catalog/:type/:id" element={<CatalogIngredient />} />
+ <Route path="code-animation" element={<CodeAnimation />} />
<Route path="mood-boards" element={<MoodBoards />} />
<Route path="mood-boards/:id" element={<MoodBoardDetail />} />
<Route path="decks" element={<Decks />} />
diff --git a/client/src/components/codeAnimation/CodeAnimationPreview.jsx b/client/src/components/codeAnimation/CodeAnimationPreview.jsx
new file mode 100644
index 0000000000..77369fea2f
--- /dev/null
+++ b/client/src/components/codeAnimation/CodeAnimationPreview.jsx
@@ -0,0 +1,234 @@
+import { useEffect, useMemo, useRef, useState } from 'react';
+import { Circle, Download, FileCode2, LoaderCircle, Save } from 'lucide-react';
+import { Link } from 'react-router';
+import toast from '../ui/Toast';
+import { uploadGalleryVideo } from '../../services/api';
+import { readFileAsBase64 } from '../../utils/fileUpload';
+import { downloadBlob } from '../../lib/downloadBlob';
+
+// Seconds past the film's own duration before a silent recording is abandoned
+// (a page that never answers the handshake must not leave Record spinning).
+const RECORD_GRACE_SECONDS = 30;
+
+const BUTTON_PRIMARY = 'inline-flex items-center gap-2 rounded-lg bg-port-accent px-3 py-1.5 text-sm text-white hover:opacity-90 disabled:cursor-not-allowed disabled:opacity-40';
+const BUTTON_SECONDARY = 'inline-flex items-center gap-2 rounded-lg border border-port-border px-3 py-1.5 text-sm text-gray-200 hover:border-port-accent disabled:cursor-not-allowed disabled:opacity-40';
+
+const slug = (text) => (text || 'code-animation').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '') || 'code-animation';
+
+// Set the audio global BEFORE any page script runs: right after <head>, or at
+// the very top when the document has none. `<` is escaped so no value can
+// close the script element early.
+const scriptLiteral = (value) => JSON.stringify(value).replace(/</g, '\\u003c');
+export function injectAudioGlobal(html, globalName, audioDataUrl) {
+ if (!audioDataUrl) return html;
+ const tag = `<script>window[${scriptLiteral(globalName)}] = ${scriptLiteral(audioDataUrl)};</script>`;
+ const head = html.match(/<head[^>]*>/i);
+ if (!head) return `${tag}${html}`;
+ const at = head.index + head[0].length;
+ return `${html.slice(0, at)}${tag}${html.slice(at)}`;
+}
+
+const blobToDataUrl = (blob) => new Promise((resolve, reject) => {
+ const reader = new FileReader();
+ reader.onload = () => resolve(reader.result);
+ reader.onerror = () => reject(new Error('Failed to read the audio track'));
+ reader.readAsDataURL(blob);
+});
+
+/**
+ * Runs a generated code animation in a sandboxed iframe (scripts only — no
+ * same-origin, so the page cannot reach PortOS's API or storage) and drives
+ * the prompt's recording handshake: Record posts `messages.record`, the page
+ * answers with the WebM Blob, which can be downloaded or saved to the shared
+ * video gallery.
+ *
+ * The opaque-origin frame cannot fetch `/api/uploads/*` itself, so the audio
+ * track is read here and handed over as a data URL through the audio global.
+ */
+export default function CodeAnimationPreview({ html, audioUrl, messages, audioGlobal, frame, title }) {
+ const iframeRef = useRef(null);
+ // status: none | loading | ready | failed; dataUrl is set only when ready.
+ const [audio, setAudio] = useState({ status: audioUrl ? 'loading' : 'none', dataUrl: null });
+ const [meta, setMeta] = useState(null);
+ const [recording, setRecording] = useState(false);
+ const [recordProgress, setRecordProgress] = useState(0);
+ const [video, setVideo] = useState(null);
+ const [saving, setSaving] = useState(false);
+ const recordTimerRef = useRef(null);
+
+ useEffect(() => {
+ let active = true;
+ setAudio({ status: audioUrl ? 'loading' : 'none', dataUrl: null });
+ if (!audioUrl) return () => { active = false; };
+ fetch(audioUrl, { credentials: 'same-origin' })
+ .then((res) => {
+ if (!res.ok) throw new Error(`Audio track unavailable (${res.status})`);
+ return res.blob();
+ })
+ .then(blobToDataUrl)
+ .then((dataUrl) => {
+ if (active) setAudio({ status: 'ready', dataUrl });
+ })
+ .catch((error) => {
+ if (!active) return;
+ setAudio({ status: 'failed', dataUrl: null });
+ toast.error(error.message);
+ });
+ return () => { active = false; };
+ }, [audioUrl]);
+
+ // Hold the frame back until the audio is in hand so the page boots once,
+ // with its audio global already set.
+ const srcDoc = useMemo(() => {
+ if (!html || audio.status === 'loading') return null;
+ return injectAudioGlobal(html, audioGlobal, audio.dataUrl);
+ }, [html, audioGlobal, audio]);
+
+ useEffect(() => {
+ setMeta(null);
+ setRecording(false);
+ setVideo(null);
+ }, [srcDoc]);
+
+ // Keyed on the URL, not the object: marking a video saved replaces the
+ // object but keeps its URL alive.
+ const videoUrl = video?.url;
+ useEffect(() => () => {
+ if (videoUrl) URL.revokeObjectURL(videoUrl);
+ }, [videoUrl]);
+
+ useEffect(() => () => clearTimeout(recordTimerRef.current), []);
+
+ useEffect(() => {
+ if (!messages) return undefined;
+ const onMessage = (event) => {
+ if (!iframeRef.current || event.source !== iframeRef.current.contentWindow) return;
+ const data = event.data;
+ if (!data || typeof data !== 'object') return;
+ if (data.type === messages.ready) setMeta(data.meta && typeof data.meta === 'object' ? data.meta : {});
+ if (data.type === messages.progress && Number.isFinite(data.t)) setRecordProgress(data.t);
+ if (data.type === messages.recorded && data.blob instanceof Blob) {
+ clearTimeout(recordTimerRef.current);
+ setRecording(false);
+ setVideo({ blob: data.blob, url: URL.createObjectURL(data.blob), saved: false });
+ }
+ if (data.type === messages.error) {
+ clearTimeout(recordTimerRef.current);
+ setRecording(false);
+ toast.error(`Animation error: ${String(data.message || 'unknown error').slice(0, 300)}`);
+ }
+ };
+ window.addEventListener('message', onMessage);
+ return () => window.removeEventListener('message', onMessage);
+ }, [messages]);
+
+ const duration = Number(meta?.duration) || frame?.durationSeconds || 0;
+ const fileBase = slug(title);
+
+ const handleRecord = () => {
+ const target = iframeRef.current?.contentWindow;
+ if (!target || recording) return;
+ setRecording(true);
+ setRecordProgress(0);
+ target.postMessage({ type: messages.record }, '*');
+ clearTimeout(recordTimerRef.current);
+ recordTimerRef.current = setTimeout(() => {
+ setRecording(false);
+ toast.error('The animation never returned a recording — its code may not implement the record handshake.');
+ }, (duration + RECORD_GRACE_SECONDS) * 1_000);
+ };
+
+ const handleSave = async () => {
+ if (!video || video.saved || saving) return;
+ setSaving(true);
+ const base64 = await readFileAsBase64(video.blob).catch(() => null);
+ const saved = base64
+ ? await uploadGalleryVideo(base64, `${fileBase}.webm`, { silent: true }).catch((error) => {
+ toast.error(error.message || 'Failed to save the video');
+ return null;
+ })
+ : null;
+ setSaving(false);
+ if (saved?.id) {
+ setVideo((current) => (current?.blob === video.blob ? { ...current, saved: true } : current));
+ toast.success('Saved to Media History');
+ }
+ };
+
+ if (!html) return null;
+
+ const aspect = frame?.width && frame?.height ? `${frame.width} / ${frame.height}` : '16 / 9';
+
+ return (
+ <section className="space-y-3" aria-label="Animation preview">
+ <div className="overflow-hidden rounded-lg border border-port-border bg-black" style={{ aspectRatio: aspect, maxHeight: '70vh' }}>
+ {srcDoc ? (
+ <iframe
+ ref={iframeRef}
+ title="Code animation preview"
+ // No allow-same-origin: generated code runs in an opaque origin
+ // and cannot touch PortOS's API, cookies, or storage.
+ sandbox="allow-scripts allow-downloads"
+ allow="autoplay"
+ srcDoc={srcDoc}
+ className="h-full w-full border-0"
+ />
+ ) : (
+ <div className="flex h-full items-center justify-center gap-2 text-sm text-gray-400">
+ <LoaderCircle className="h-4 w-4 animate-spin" /> Loading audio track…
+ </div>
+ )}
+ </div>
+
+ <div className="flex flex-wrap items-center gap-2">
+ <button
+ type="button"
+ onClick={handleRecord}
+ disabled={!srcDoc || recording}
+ className="inline-flex items-center gap-2 rounded-lg bg-port-error/90 px-3 py-1.5 text-sm text-white hover:opacity-90 disabled:cursor-not-allowed disabled:opacity-40"
+ >
+ {recording ? <LoaderCircle className="h-4 w-4 animate-spin" /> : <Circle className="h-4 w-4 fill-current" />}
+ {recording ? `Recording ${Math.floor(recordProgress)}s / ${Math.round(duration)}s` : 'Record video'}
+ </button>
+ <button
+ type="button"
+ onClick={() => downloadBlob(html, `${fileBase}.html`, 'text/html')}
+ className={BUTTON_SECONDARY}
+ >
+ <FileCode2 className="h-4 w-4" /> Download HTML
+ </button>
+ <span className="text-xs text-gray-500">
+ {meta ? 'Animation ready' : 'Waiting for the animation to report ready…'}
+ {audio.status === 'failed' ? ' · audio track failed to load' : ''}
+ </span>
+ </div>
+
+ {video && (
+ <div className="space-y-2 rounded-lg border border-port-border bg-port-card p-3">
+ <video src={video.url} controls className="max-h-80 w-full rounded bg-black" aria-label="Recorded animation" />
+ <div className="flex flex-wrap items-center gap-2">
+ <button
+ type="button"
+ onClick={() => downloadBlob(video.blob, `${fileBase}.webm`)}
+ className={BUTTON_SECONDARY}
+ >
+ <Download className="h-4 w-4" /> Download WebM
+ </button>
+ <button
+ type="button"
+ onClick={handleSave}
+ disabled={saving || video.saved}
+ className={BUTTON_PRIMARY}
+ >
+ {saving ? <LoaderCircle className="h-4 w-4 animate-spin" /> : <Save className="h-4 w-4" />}
+ {video.saved ? 'Saved' : 'Save to Media History'}
+ </button>
+ {video.saved && (
+ <Link to="/media/history" className="text-xs text-port-accent hover:underline">Open Media History</Link>
+ )}
+ </div>
+ </div>
+ )}
+ </section>
+ );
+}
diff --git a/client/src/components/codeAnimation/CodeAnimationPreview.test.jsx b/client/src/components/codeAnimation/CodeAnimationPreview.test.jsx
new file mode 100644
index 0000000000..c5a15f7088
--- /dev/null
+++ b/client/src/components/codeAnimation/CodeAnimationPreview.test.jsx
@@ -0,0 +1,66 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { act, render, screen } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { MemoryRouter } from 'react-router';
+
+vi.mock('../../services/api', () => ({ uploadGalleryVideo: vi.fn() }));
+
+import CodeAnimationPreview, { injectAudioGlobal } from './CodeAnimationPreview';
+
+const MESSAGES = { ready: 'ca:ready', record: 'ca:record', recorded: 'ca:recorded', progress: 'ca:progress', error: 'ca:error' };
+const HTML = '<!DOCTYPE html><html><head><title>x</title></head><body><canvas></canvas></body></html>';
+
+const renderPreview = () => render(
+ <MemoryRouter>
+ <CodeAnimationPreview html={HTML} audioUrl={null} messages={MESSAGES} audioGlobal="ANIMATION_AUDIO_URL" frame={{ width: 1920, height: 1080, durationSeconds: 5 }} title="Lantern" />
+ </MemoryRouter>,
+);
+
+const postFromFrame = (source, data) => act(async () => {
+ window.dispatchEvent(new MessageEvent('message', { data, source }));
+});
+
+describe('injectAudioGlobal', () => {
+ it('sets the audio global before any page script, with or without a <head>', () => {
+ const withHead = injectAudioGlobal(HTML, 'ANIMATION_AUDIO_URL', 'data:audio/mpeg;base64,AA');
+ expect(withHead).toContain('<head><script>window["ANIMATION_AUDIO_URL"] = "data:audio/mpeg;base64,AA";</script><title>');
+ expect(injectAudioGlobal('<canvas></canvas>', 'G', 'data:x')).toBe('<script>window["G"] = "data:x";</script><canvas></canvas>');
+ expect(injectAudioGlobal(HTML, 'G', null)).toBe(HTML);
+ });
+
+ it('cannot break out of the script tag through the data URL', () => {
+ const out = injectAudioGlobal(HTML, 'G', 'data:x"</script><script>alert(1)//');
+ expect(out).not.toContain('</script><script>alert');
+ expect(out).toContain('"data:x\\"\\u003c/script>\\u003cscript>alert(1)//"');
+ });
+});
+
+describe('CodeAnimationPreview', () => {
+ beforeEach(() => {
+ globalThis.URL.createObjectURL = vi.fn(() => 'blob:recorded');
+ globalThis.URL.revokeObjectURL = vi.fn();
+ });
+
+ it('runs the page in a scripts-only sandbox and records through the postMessage handshake', async () => {
+ const user = userEvent.setup();
+ renderPreview();
+ const frame = screen.getByTitle('Code animation preview');
+ expect(frame.getAttribute('sandbox')).toBe('allow-scripts allow-downloads');
+ const target = frame.contentWindow;
+ const postMessage = vi.spyOn(target, 'postMessage');
+
+ await postFromFrame(target, { type: MESSAGES.ready, meta: { duration: 5 } });
+ expect(screen.getByText('Animation ready')).toBeInTheDocument();
+
+ await user.click(screen.getByRole('button', { name: /record video/i }));
+ expect(postMessage).toHaveBeenCalledWith({ type: MESSAGES.record }, '*');
+
+ // A message from any other window is ignored.
+ await postFromFrame(window, { type: MESSAGES.recorded, blob: new Blob(['x']), mimeType: 'video/webm' });
+ expect(screen.queryByLabelText('Recorded animation')).not.toBeInTheDocument();
+
+ await postFromFrame(target, { type: MESSAGES.recorded, blob: new Blob(['x'], { type: 'video/webm' }), mimeType: 'video/webm' });
+ expect(screen.getByLabelText('Recorded animation')).toHaveAttribute('src', 'blob:recorded');
+ expect(screen.getByRole('button', { name: /save to media history/i })).toBeEnabled();
+ });
+});
diff --git a/client/src/lib/navPresentation.js b/client/src/lib/navPresentation.js
index cff9dfd817..eaea98a8be 100644
--- a/client/src/lib/navPresentation.js
+++ b/client/src/lib/navPresentation.js
@@ -22,6 +22,7 @@ import {
CheckCircle,
Dna,
Download,
+ FileCode2,
Film,
MessageSquare,
Palette,
@@ -171,6 +172,7 @@ export const NAV_PRESENTATION = {
'/authors': { icon: FilePen },
'/catalog': { icon: Sparkles },
'/creative-commission': { icon: CalendarClock },
+ '/code-animation': { icon: FileCode2 },
'/creative-director': { icon: Clapperboard },
'/video': { icon: Clapperboard },
'/pipeline/editorial-checks': { icon: ListChecks },
diff --git a/client/src/pages/CodeAnimation.jsx b/client/src/pages/CodeAnimation.jsx
new file mode 100644
index 0000000000..ad0b4e03d9
--- /dev/null
+++ b/client/src/pages/CodeAnimation.jsx
@@ -0,0 +1,483 @@
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { Copy, FileCode2, Globe, ImagePlus, LoaderCircle, Music2, Sparkles, Wand2, X } from 'lucide-react';
+import { Link, useSearchParams } from 'react-router';
+import PageHeader from '../components/PageHeader';
+import ProviderModelSelector from '../components/ProviderModelSelector';
+import CodeAnimationPreview from '../components/codeAnimation/CodeAnimationPreview';
+import useProviderModels from '../hooks/useProviderModels';
+import { useAutoRefetch } from '../hooks/useAutoRefetch';
+import toast from '../components/ui/Toast';
+import {
+ buildCodeAnimationPrompt,
+ getCodeAnimationJob,
+ getCodeAnimationOptions,
+ listMoodBoardNames,
+ listUniverseNames,
+ listUniverseStyles,
+ startCodeAnimationGeneration,
+ uploadFile,
+} from '../services/api';
+import { copyToClipboard } from '../lib/clipboard';
+import { safeReadJsonStorage, safeWriteJsonStorage } from '../lib/safeStorage';
+import { readFileAsBase64, UPLOAD_IMAGE_ACCEPT, validateImageFile } from '../utils/fileUpload';
+
+const DRAFT_KEY = 'portos.codeAnimation.draft';
+const JOB_POLL_MS = 3_000;
+// Mood-board choice sentinels: follow the universe's linked board, or none.
+const BOARD_FOLLOW_UNIVERSE = 'universe';
+const BOARD_NONE = 'none';
+
+const DEFAULT_DRAFT = {
+ title: '',
+ concept: '',
+ onScreenText: '',
+ styleNotes: '',
+ universeId: '',
+ moodBoardChoice: BOARD_FOLLOW_UNIVERSE,
+ includeMoodBoardImages: true,
+ referenceImages: [],
+ audio: null,
+ soundtrack: 'none',
+ format: { durationSeconds: 20, aspectRatio: '16:9', resolution: '1080p', fps: 30 },
+ renderer: 'auto',
+ interactive: false,
+};
+
+const loadDraft = () => {
+ const stored = safeReadJsonStorage(DRAFT_KEY, null);
+ if (!stored || typeof stored !== 'object') return DEFAULT_DRAFT;
+ return { ...DEFAULT_DRAFT, ...stored, format: { ...DEFAULT_DRAFT.format, ...(stored.format || {}) } };
+};
+
+// The draft → the server's brief shape. An absent moodBoardId follows the
+// universe's linked board; '' means none.
+function toBrief(draft) {
+ const brief = {
+ title: draft.title,
+ concept: draft.concept,
+ onScreenText: draft.onScreenText,
+ styleNotes: draft.styleNotes,
+ format: draft.format,
+ renderer: draft.renderer,
+ interactive: draft.interactive,
+ soundtrack: draft.audio ? 'none' : draft.soundtrack,
+ universeId: draft.universeId || null,
+ 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 }
+ : null,
+ };
+ if (draft.moodBoardChoice === BOARD_NONE) brief.moodBoardId = '';
+ else if (draft.moodBoardChoice !== BOARD_FOLLOW_UNIVERSE) brief.moodBoardId = draft.moodBoardChoice;
+ return brief;
+}
+
+const readAudioDuration = (file) => new Promise((resolve) => {
+ const url = URL.createObjectURL(file);
+ const audio = new Audio();
+ const done = (value) => { URL.revokeObjectURL(url); resolve(value); };
+ audio.onloadedmetadata = () => done(Number.isFinite(audio.duration) ? audio.duration : null);
+ audio.onerror = () => done(null);
+ audio.src = url;
+});
+
+const inputClass = 'w-full rounded-lg border border-port-border bg-port-bg px-3 py-2 text-sm text-white placeholder:text-gray-600 focus:border-port-accent focus:outline-none';
+const labelClass = 'mb-1 block text-xs text-gray-400';
+const fileInputClass = 'block w-full text-xs text-gray-400 file:mr-3 file:rounded file:border-0 file:bg-port-border file:px-3 file:py-1.5 file:text-gray-200';
+const buttonPrimary = 'inline-flex items-center gap-2 rounded-lg bg-port-accent px-3 py-1.5 text-sm text-white hover:opacity-90 disabled:cursor-not-allowed disabled:opacity-40';
+const buttonSecondary = 'inline-flex items-center gap-2 rounded-lg border border-port-border px-3 py-1.5 text-sm text-gray-200 hover:border-port-accent disabled:cursor-not-allowed disabled:opacity-40';
+const providerFilter = (provider) => provider.enabled !== false;
+
+// Read + upload one file; toasts and resolves null on failure.
+async function uploadOrToast(file) {
+ const base64 = await readFileAsBase64(file).catch(() => null);
+ if (!base64) {
+ toast.error(`Failed to read ${file.name}`);
+ return null;
+ }
+ return uploadFile(base64, file.name, { silent: true }).catch((error) => {
+ toast.error(error.message || `Failed to upload ${file.name}`);
+ return null;
+ });
+}
+
+export default function CodeAnimation() {
+ const [searchParams, setSearchParams] = useSearchParams();
+ const jobId = searchParams.get('job') || '';
+ const [options, setOptions] = useState(null);
+ const [universes, setUniverses] = useState([]);
+ const [universeStyles, setUniverseStyles] = useState({});
+ const [boards, setBoards] = useState([]);
+ const [draft, setDraft] = useState(loadDraft);
+ const [uploading, setUploading] = useState(false);
+ const [building, setBuilding] = useState(false);
+ // The last built prompt, tagged with the brief it was built from.
+ const [built, setBuilt] = useState(null);
+ const [starting, setStarting] = useState(false);
+ const [job, setJob] = useState(null);
+ const [effort, setEffort] = useState('');
+ const [pastedHtml, setPastedHtml] = useState('');
+ const [preview, setPreview] = useState(null);
+ const jobIdRef = useRef(jobId);
+ const {
+ providers,
+ selectedProviderId,
+ selectedModel,
+ availableModels,
+ setSelectedProviderId,
+ setSelectedModel,
+ loading: providersLoading,
+ } = useProviderModels({ filter: providerFilter, silent: true, withEffort: true });
+
+ const update = (patch) => setDraft((prev) => ({ ...prev, ...patch }));
+ const updateFormat = (patch) => setDraft((prev) => ({ ...prev, format: { ...prev.format, ...patch } }));
+
+ useEffect(() => { safeWriteJsonStorage(DRAFT_KEY, draft); }, [draft]);
+
+ useEffect(() => {
+ getCodeAnimationOptions({ silent: true }).then(setOptions).catch(() => toast.error('Failed to load Code Animation options'));
+ listUniverseNames({ silent: true }).then((rows) => setUniverses(Array.isArray(rows) ? rows : [])).catch(() => {});
+ listUniverseStyles({ silent: true })
+ .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(() => {});
+ }, []);
+
+ const brief = useMemo(() => toBrief(draft), [draft]);
+ const briefKey = useMemo(() => JSON.stringify(brief), [brief]);
+ const promptStale = !!built && built.briefKey !== briefKey;
+ const activeStyle = draft.universeId ? universeStyles[draft.universeId] : null;
+ const limits = options?.limits;
+ const maxRefs = limits?.referenceImagesMax ?? 8;
+ const audioAccept = (options?.audioExtensions || ['mp3', 'wav', 'ogg', 'm4a']).map((ext) => `.${ext}`).join(',');
+ const generating = job?.id === jobId && job.status === 'running';
+ const canBuild = draft.concept.trim().length > 0 && !building && !uploading;
+
+ // Poll the generation job named in the URL until it settles. The ref drops a
+ // response for a job the user has since replaced.
+ useEffect(() => { jobIdRef.current = jobId; }, [jobId]);
+ const jobSettled = job?.id === jobId && job.status !== 'running';
+ const pollJob = useCallback(async () => {
+ const requested = jobId;
+ const next = await getCodeAnimationJob(requested, { silent: true })
+ .catch((error) => ({ id: requested, status: 'missing', error: error.message }));
+ if (jobIdRef.current !== requested) return;
+ setJob(next);
+ if (next.status === 'completed' && next.html) setPreview({ html: next.html, audioUrl: next.audioUrl, frame: next.frame });
+ }, [jobId]);
+ useAutoRefetch(pollJob, JOB_POLL_MS, { enabled: !!jobId && !jobSettled, pollOnly: true });
+
+ const handleImages = async (event) => {
+ const files = [...(event.target.files || [])];
+ event.target.value = '';
+ if (!files.length) return;
+ const room = Math.max(0, maxRefs - draft.referenceImages.length);
+ if (files.length > room) toast.error(`Only ${room} more reference image(s) fit`);
+ const valid = files.slice(0, room).filter((file) => {
+ const invalid = validateImageFile(file);
+ if (invalid) toast.error(invalid);
+ return !invalid;
+ });
+ setUploading(true);
+ const uploaded = await Promise.all(valid.map(async (file) => {
+ const saved = await uploadOrToast(file);
+ return saved ? { filename: saved.filename, label: file.name, note: '', url: saved.path } : null;
+ }));
+ const added = uploaded.filter(Boolean);
+ setUploading(false);
+ if (added.length) setDraft((prev) => ({ ...prev, referenceImages: [...prev.referenceImages, ...added] }));
+ };
+
+ const updateReference = (filename, patch) => setDraft((prev) => ({
+ ...prev,
+ referenceImages: prev.referenceImages.map((ref) => (ref.filename === filename ? { ...ref, ...patch } : ref)),
+ }));
+
+ const handleAudio = async (event) => {
+ const file = event.target.files?.[0];
+ event.target.value = '';
+ if (!file) return;
+ 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 } });
+ };
+
+ const handleBuild = async () => {
+ if (!canBuild) return;
+ setBuilding(true);
+ const result = await buildCodeAnimationPrompt(brief, { silent: true }).catch((error) => {
+ toast.error(error.message || 'Failed to build the prompt');
+ return null;
+ });
+ setBuilding(false);
+ if (result) setBuilt({ ...result, briefKey });
+ };
+
+ const handleGenerate = async () => {
+ if (!canBuild || !selectedProviderId || starting) return;
+ setStarting(true);
+ const started = await startCodeAnimationGeneration({
+ ...brief,
+ providerId: selectedProviderId,
+ model: selectedModel || undefined,
+ effort: effort || undefined,
+ }, { silent: true }).catch((error) => {
+ toast.error(error.message || 'Failed to start generation');
+ return null;
+ });
+ setStarting(false);
+ if (!started) return;
+ setBuilt({ prompt: started.prompt, attachments: started.attachments, frame: started.frame, audioUrl: started.audioUrl, briefKey });
+ setJob(started);
+ setPreview(null);
+ const next = new URLSearchParams(searchParams);
+ next.set('job', started.id);
+ setSearchParams(next);
+ };
+
+ const handlePreviewPasted = () => {
+ if (!pastedHtml.trim()) return;
+ setPreview({ html: pastedHtml, audioUrl: built?.audioUrl ?? draft.audio?.url ?? null, frame: built?.frame ?? null });
+ };
+
+ const boardName = (id) => boards.find((board) => board.id === id)?.name || 'linked board';
+
+ return (
+ <div className="mx-auto max-w-7xl space-y-4">
+ <PageHeader
+ icon={FileCode2}
+ title="Code Animation"
+ subtitle="Prompt an LLM to code an animated film, with no assets, in a universe's style, then preview it and record it to video."
+ className="rounded-xl border border-port-border bg-port-card"
+ />
+
+ <div className="grid gap-4 lg:grid-cols-[minmax(0,1fr)_minmax(0,1fr)]">
+ <div className="space-y-4">
+ <section className="space-y-3 rounded-xl border border-port-border bg-port-card p-4" aria-labelledby="ca-style-heading">
+ <h2 id="ca-style-heading" className="flex items-center gap-2 text-sm font-semibold text-white"><Globe className="h-4 w-4 text-port-accent" /> Style</h2>
+ <div className="grid gap-3 sm:grid-cols-2">
+ <div>
+ <label htmlFor="ca-universe" className={labelClass}>Universe (sets the art style)</label>
+ <select id="ca-universe" value={draft.universeId} onChange={(event) => update({ universeId: event.target.value })} className={inputClass}>
+ <option value="">No universe</option>
+ {universes.map((universe) => <option key={universe.id} value={universe.id}>{universe.name}</option>)}
+ </select>
+ </div>
+ <div>
+ <label htmlFor="ca-board" className={labelClass}>Mood board</label>
+ <select id="ca-board" value={draft.moodBoardChoice} onChange={(event) => update({ moodBoardChoice: event.target.value })} className={inputClass}>
+ <option value={BOARD_FOLLOW_UNIVERSE}>Universe&apos;s linked board</option>
+ <option value={BOARD_NONE}>No mood board</option>
+ {boards.map((board) => <option key={board.id} value={board.id}>{board.name}</option>)}
+ </select>
+ </div>
+ </div>
+ {activeStyle && (activeStyle.influences?.embrace?.length > 0 || activeStyle.influences?.avoid?.length > 0) && (
+ <div className="flex flex-wrap gap-1 text-[11px]">
+ {(activeStyle.influences.embrace || []).slice(0, 12).map((token) => (
+ <span key={`e-${token}`} className="rounded bg-port-accent/15 px-1.5 py-0.5 text-port-accent">{token}</span>
+ ))}
+ {(activeStyle.influences.avoid || []).slice(0, 6).map((token) => (
+ <span key={`a-${token}`} className="rounded bg-port-error/15 px-1.5 py-0.5 text-port-error line-through">{token}</span>
+ ))}
+ </div>
+ )}
+ {draft.universeId && !activeStyle && (
+ <p className="text-xs text-gray-500">
+ This universe has no style tokens yet, so only its notes and style references will be used. <Link to={`/universes/${encodeURIComponent(draft.universeId)}`} className="text-port-accent hover:underline">Edit its style guide</Link>
+ </p>
+ )}
+ <div>
+ <label htmlFor="ca-style-notes" className={labelClass}>Style refinements <span className="text-gray-600">(optional, applied on top of the universe style)</span></label>
+ <textarea id="ca-style-notes" rows={2} value={draft.styleNotes} maxLength={limits?.styleNotesMax} onChange={(event) => update({ styleNotes: event.target.value })} placeholder="Heavier film grain, slower camera, dusk palette" className={`${inputClass} resize-y`} />
+ </div>
+ <label className="flex items-center gap-2 text-xs text-gray-300">
+ <input type="checkbox" checked={draft.includeMoodBoardImages} onChange={(event) => update({ includeMoodBoardImages: event.target.checked })} />
+ Attach mood board images as references
+ </label>
+ </section>
+
+ <section className="space-y-3 rounded-xl border border-port-border bg-port-card p-4" aria-labelledby="ca-brief-heading">
+ <h2 id="ca-brief-heading" className="flex items-center gap-2 text-sm font-semibold text-white"><Sparkles className="h-4 w-4 text-port-accent" /> Brief</h2>
+ <div>
+ <label htmlFor="ca-title" className={labelClass}>Title <span className="text-gray-600">(optional)</span></label>
+ <input id="ca-title" value={draft.title} maxLength={200} onChange={(event) => update({ title: event.target.value })} placeholder="The Lantern Keeper" className={inputClass} />
+ </div>
+ <div>
+ <label htmlFor="ca-concept" className={labelClass}>What happens</label>
+ <textarea id="ca-concept" rows={4} value={draft.concept} maxLength={limits?.conceptMax} onChange={(event) => update({ concept: event.target.value })} placeholder="A paper lantern drifts over a sleeping harbor town, gathers fireflies, and bursts into a constellation at the climax." className={`${inputClass} resize-y`} />
+ </div>
+ <div>
+ <label htmlFor="ca-text" className={labelClass}>On-screen text / narration <span className="text-gray-600">(optional)</span></label>
+ <textarea id="ca-text" rows={2} value={draft.onScreenText} maxLength={limits?.textMax} onChange={(event) => update({ onScreenText: event.target.value })} placeholder={'0:02 "Every night, one light remains"\n0:15 Title card'} className={`${inputClass} resize-y`} />
+ </div>
+ </section>
+
+ <section className="space-y-3 rounded-xl border border-port-border bg-port-card p-4" aria-labelledby="ca-refs-heading">
+ <h2 id="ca-refs-heading" className="flex items-center gap-2 text-sm font-semibold text-white"><ImagePlus className="h-4 w-4 text-port-accent" /> References &amp; audio</h2>
+ <div>
+ <label htmlFor="ca-images" className={labelClass}>Reference images ({draft.referenceImages.length}/{maxRefs})</label>
+ <input id="ca-images" type="file" multiple accept={UPLOAD_IMAGE_ACCEPT} onChange={handleImages} disabled={uploading} className={fileInputClass} />
+ {draft.referenceImages.length > 0 && (
+ <ul className="mt-2 space-y-2">
+ {draft.referenceImages.map((ref) => (
+ <li key={ref.filename} className="flex items-center gap-2">
+ <img src={ref.url} alt={ref.label} className="h-12 w-12 shrink-0 rounded object-cover" />
+ <input aria-label={`Note for ${ref.label}`} value={ref.note} maxLength={limits?.referenceNoteMax} onChange={(event) => updateReference(ref.filename, { note: event.target.value })} placeholder="What to take from it (palette, silhouette…)" className={`${inputClass} min-w-0`} />
+ <button type="button" aria-label={`Remove ${ref.label}`} onClick={() => update({ referenceImages: draft.referenceImages.filter((item) => item.filename !== ref.filename) })} className="shrink-0 text-gray-500 hover:text-port-error"><X className="h-4 w-4" /></button>
+ </li>
+ ))}
+ </ul>
+ )}
+ </div>
+ <div>
+ <label htmlFor="ca-audio" className={`${labelClass} flex items-center gap-1`}><Music2 className="h-3 w-3" /> Audio track <span className="text-gray-600">(optional; the animation syncs to it)</span></label>
+ {draft.audio ? (
+ <div className="space-y-2">
+ <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}
+ <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} />
+ <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
+ </label>
+ </div>
+ )}
+ </div>
+ {uploading && <p className="flex items-center gap-2 text-xs text-gray-400"><LoaderCircle className="h-3 w-3 animate-spin" /> Uploading…</p>}
+ </section>
+
+ <section className="rounded-xl border border-port-border bg-port-card p-4" aria-labelledby="ca-format-heading">
+ <h2 id="ca-format-heading" className="mb-3 text-sm font-semibold text-white">Format</h2>
+ <div className="grid grid-cols-2 gap-3 sm:grid-cols-3">
+ <div>
+ <label htmlFor="ca-duration" className={labelClass}>Duration (s)</label>
+ <input id="ca-duration" type="number" min={limits?.durationMin ?? 3} max={limits?.durationMax ?? 180} value={draft.format.durationSeconds} onChange={(event) => updateFormat({ durationSeconds: Math.round(Number(event.target.value) || 0) })} className={inputClass} />
+ </div>
+ <div>
+ <label htmlFor="ca-aspect" className={labelClass}>Aspect</label>
+ <select id="ca-aspect" value={draft.format.aspectRatio} onChange={(event) => updateFormat({ aspectRatio: event.target.value })} className={inputClass}>
+ {(options?.aspectRatios || ['16:9']).map((ratio) => <option key={ratio} value={ratio}>{ratio}</option>)}
+ </select>
+ </div>
+ <div>
+ <label htmlFor="ca-resolution" className={labelClass}>Resolution</label>
+ <select id="ca-resolution" value={draft.format.resolution} onChange={(event) => updateFormat({ resolution: event.target.value })} className={inputClass}>
+ {(options?.resolutions || ['1080p']).map((res) => <option key={res} value={res}>{res}</option>)}
+ </select>
+ </div>
+ <div>
+ <label htmlFor="ca-fps" className={labelClass}>FPS</label>
+ <select id="ca-fps" value={draft.format.fps} onChange={(event) => updateFormat({ fps: Number(event.target.value) })} className={inputClass}>
+ {(limits?.fpsOptions || [30]).map((fps) => <option key={fps} value={fps}>{fps}</option>)}
+ </select>
+ </div>
+ <div>
+ <label htmlFor="ca-renderer" className={labelClass}>Renderer</label>
+ <select id="ca-renderer" value={draft.renderer} onChange={(event) => update({ renderer: event.target.value })} className={inputClass}>
+ {(options?.renderers || ['auto']).map((renderer) => <option key={renderer} value={renderer}>{renderer}</option>)}
+ </select>
+ </div>
+ <label className="flex items-end gap-2 pb-2 text-xs text-gray-300">
+ <input type="checkbox" checked={draft.interactive} onChange={(event) => update({ interactive: event.target.checked })} />
+ Interactive
+ </label>
+ </div>
+ </section>
+ </div>
+
+ <div className="space-y-4">
+ <section className="space-y-3 rounded-xl border border-port-border bg-port-card p-4" aria-labelledby="ca-prompt-heading">
+ <div className="flex flex-wrap items-center justify-between gap-2">
+ <h2 id="ca-prompt-heading" className="text-sm font-semibold text-white">Prompt</h2>
+ <div className="flex flex-wrap gap-2">
+ <button type="button" onClick={handleBuild} disabled={!canBuild} className={buttonPrimary}>
+ {building ? <LoaderCircle className="h-4 w-4 animate-spin" /> : <Wand2 className="h-4 w-4" />}
+ {built ? 'Rebuild prompt' : 'Build prompt'}
+ </button>
+ <button type="button" onClick={() => built && copyToClipboard(built.prompt, 'Prompt copied')} disabled={!built} className={buttonSecondary}>
+ <Copy className="h-4 w-4" /> Copy
+ </button>
+ </div>
+ </div>
+ {!draft.concept.trim() && <p className="text-xs text-gray-500">Describe what happens in the brief to build a prompt.</p>}
+ {built && (
+ <>
+ {promptStale && <p className="text-xs text-port-warning">The brief changed since this prompt was built. Rebuild to include your edits.</p>}
+ {built.moodBoardId && draft.moodBoardChoice === BOARD_FOLLOW_UNIVERSE && (
+ <p className="text-xs text-gray-500">Using the universe&apos;s mood board: {boardName(built.moodBoardId)}</p>
+ )}
+ <textarea readOnly aria-label="Generated prompt" value={built.prompt} rows={14} className={`${inputClass} font-mono text-xs`} />
+ {built.attachments?.length > 0 && (
+ <div>
+ <p className="mb-1 text-xs text-gray-400">Attach these images, in order, when you paste the prompt into another LLM:</p>
+ <div className="flex flex-wrap gap-2">
+ {built.attachments.map((attachment, index) => (
+ <a key={attachment.url} href={attachment.url} target="_blank" rel="noreferrer" title={`${index + 1}. ${attachment.label} (${attachment.origin})`} className="relative block h-14 w-14 overflow-hidden rounded border border-port-border">
+ <img src={attachment.url} alt={attachment.label} className="h-full w-full object-cover" />
+ <span className="port-media-overlay-strong absolute left-0 top-0 rounded-br px-1 text-[10px]">{index + 1}</span>
+ </a>
+ ))}
+ </div>
+ </div>
+ )}
+ </>
+ )}
+ </section>
+
+ <section className="space-y-3 rounded-xl border border-port-border bg-port-card p-4" aria-labelledby="ca-generate-heading">
+ <h2 id="ca-generate-heading" className="text-sm font-semibold text-white">Generate &amp; preview</h2>
+ <ProviderModelSelector
+ providers={providers}
+ selectedProviderId={selectedProviderId}
+ selectedModel={selectedModel}
+ availableModels={availableModels}
+ onProviderChange={(id) => { setSelectedProviderId(id); setEffort(''); }}
+ onModelChange={setSelectedModel}
+ effort={effort}
+ onEffortChange={setEffort}
+ disabled={providersLoading || starting}
+ alwaysShowModel
+ emptyModelOption="Provider default"
+ label="Generation provider"
+ />
+ <div className="flex flex-wrap items-center gap-3">
+ <button type="button" onClick={handleGenerate} disabled={!canBuild || !selectedProviderId || starting || generating} className={buttonPrimary}>
+ {starting || generating ? <LoaderCircle className="h-4 w-4 animate-spin" /> : <Sparkles className="h-4 w-4" />}
+ {generating ? 'Generating…' : 'Generate animation'}
+ </button>
+ {job?.status === 'failed' && <span className="text-xs text-port-error">Generation failed: {job.error}</span>}
+ {job?.status === 'missing' && <span className="text-xs text-gray-500">That generation is no longer available (it expired or the server restarted).</span>}
+ </div>
+ <details className="text-xs text-gray-400">
+ <summary className="cursor-pointer select-none">Preview HTML from another LLM</summary>
+ <div className="mt-2 space-y-2">
+ <textarea aria-label="Pasted animation HTML" rows={4} value={pastedHtml} onChange={(event) => setPastedHtml(event.target.value)} placeholder="Paste the <!DOCTYPE html> document the model returned" className={`${inputClass} font-mono text-xs`} />
+ <button type="button" onClick={handlePreviewPasted} disabled={!pastedHtml.trim()} className={buttonSecondary}>Preview pasted HTML</button>
+ </div>
+ </details>
+ {preview && options && (
+ <CodeAnimationPreview
+ html={preview.html}
+ audioUrl={preview.audioUrl}
+ frame={preview.frame}
+ messages={options.messages}
+ audioGlobal={options.audioGlobal}
+ title={draft.title || draft.concept.slice(0, 40)}
+ />
+ )}
+ </section>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/pages/CodeAnimation.test.jsx b/client/src/pages/CodeAnimation.test.jsx
new file mode 100644
index 0000000000..e17cce4cbf
--- /dev/null
+++ b/client/src/pages/CodeAnimation.test.jsx
@@ -0,0 +1,104 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { act, render, screen, waitFor } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { MemoryRouter } from 'react-router';
+
+vi.mock('../services/api', () => ({
+ buildCodeAnimationPrompt: vi.fn(),
+ getCodeAnimationJob: vi.fn(),
+ getCodeAnimationOptions: vi.fn(),
+ listMoodBoardNames: vi.fn(),
+ listUniverseNames: vi.fn(),
+ listUniverseStyles: vi.fn(),
+ startCodeAnimationGeneration: vi.fn(),
+ uploadFile: vi.fn(),
+ uploadGalleryVideo: vi.fn(),
+}));
+vi.mock('../hooks/useProviderModels', () => ({
+ default: () => ({
+ providers: [{ id: 'api-1', name: 'Example API', type: 'api', enabled: true }],
+ selectedProviderId: 'api-1',
+ selectedModel: '',
+ availableModels: [],
+ setSelectedProviderId: vi.fn(),
+ setSelectedModel: vi.fn(),
+ loading: false,
+ }),
+}));
+
+import CodeAnimation from './CodeAnimation';
+import {
+ buildCodeAnimationPrompt,
+ getCodeAnimationOptions,
+ listMoodBoardNames,
+ listUniverseNames,
+ listUniverseStyles,
+} from '../services/api';
+
+const OPTIONS = {
+ aspectRatios: ['16:9', '9:16'],
+ resolutions: ['720p', '1080p'],
+ renderers: ['auto', 'canvas2d'],
+ limits: { durationMin: 3, durationMax: 180, fpsOptions: [24, 30, 60], referenceImagesMax: 8 },
+ messages: { ready: 'r', record: 'rec', recorded: 'done', progress: 'p', error: 'e' },
+ audioGlobal: 'ANIMATION_AUDIO_URL',
+ audioExtensions: ['mp3', 'wav'],
+};
+
+const renderPage = async () => {
+ const result = render(<MemoryRouter initialEntries={['/code-animation']}><CodeAnimation /></MemoryRouter>);
+ await act(async () => {});
+ return result;
+};
+
+describe('Code Animation page', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ localStorage.clear();
+ getCodeAnimationOptions.mockResolvedValue(OPTIONS);
+ 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' }]);
+ buildCodeAnimationPrompt.mockResolvedValue({
+ prompt: 'You are an award-winning creative coder…',
+ attachments: [{ label: 'Night markets', origin: 'universe', url: '/data/image-refs/style-ref.png' }],
+ frame: { width: 1920, height: 1080, fps: 30, durationSeconds: 20 },
+ audioUrl: null,
+ moodBoardId: 'b1',
+ });
+ });
+
+ it('builds a universe-styled prompt that follows the universe mood board by default', async () => {
+ const user = userEvent.setup();
+ await renderPage();
+ const build = screen.getByRole('button', { name: /build prompt/i });
+ expect(build).toBeDisabled();
+
+ await user.selectOptions(screen.getByLabelText(/universe \(sets the art style\)/i), 'u1');
+ expect(screen.getByText('ink wash')).toBeInTheDocument();
+ await user.type(screen.getByLabelText(/what happens/i), 'A lantern drifts over a harbor');
+ await user.click(build);
+
+ await waitFor(() => expect(buildCodeAnimationPrompt).toHaveBeenCalledTimes(1));
+ const brief = buildCodeAnimationPrompt.mock.calls[0][0];
+ expect(brief).toMatchObject({ universeId: 'u1', concept: 'A lantern drifts over a harbor' });
+ expect('moodBoardId' in brief).toBe(false);
+ expect(await screen.findByLabelText('Generated prompt')).toHaveValue('You are an award-winning creative coder…');
+ expect(screen.getByText(/Using the universe's mood board: Dusk/)).toBeInTheDocument();
+ expect(screen.getByAltText('Night markets')).toHaveAttribute('src', '/data/image-refs/style-ref.png');
+
+ // Editing the brief marks the built prompt stale until it is rebuilt.
+ await user.type(screen.getByLabelText(/style refinements/i), 'more fog');
+ expect(screen.getByText(/brief changed since this prompt was built/i)).toBeInTheDocument();
+ });
+
+ it('sends an explicit empty board when the user opts out of a mood board', async () => {
+ const user = userEvent.setup();
+ await renderPage();
+ await user.type(screen.getByLabelText(/what happens/i), 'Fireflies');
+ await user.selectOptions(screen.getByLabelText('Mood board'), 'none');
+ await user.click(screen.getByRole('button', { name: /build prompt/i }));
+ await waitFor(() => expect(buildCodeAnimationPrompt).toHaveBeenCalled());
+ expect(buildCodeAnimationPrompt.mock.calls[0][0].moodBoardId).toBe('');
+ });
+});
diff --git a/client/src/services/README.md b/client/src/services/README.md
index 4c9f092cfe..658cdf10f8 100644
--- a/client/src/services/README.md
+++ b/client/src/services/README.md
@@ -83,7 +83,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire
| `apiHealth.js` | Apple Health. |
| `apiMeatspace.js` | MeatSpace health, genome, POST, memory-practice, and atomic POST training-run APIs. |
| `apiMortalLoom.js` | Mortality tracking. |
-| `apiMoodBoard.js` | Mood boards (inspiration canvas + items). |
+| `apiMoodBoard.js` | Mood boards (inspiration canvas + items), plus `listMoodBoardNames()` for pickers. |
| `apiTribe.js` | Tribe people (relationship rings + contacts), plus `getTribeDuplicateIdentifiers()` (`GET /tribe/duplicate-identifiers`): a non-blocking report of emails/phones shared by more than one person. |
| `apiTimeline.js` | Human-activity timeline: `/timeline/day`. |
| `apiCalendar.js` | Calendar events. |
@@ -114,6 +114,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire
| `apiContinuousVideo.js` | Continuous-video episode generation: client-side-callable lint preview of a scene draft, queue-episode submit, and the SSE progress-events URL. |
| `apiSprites.js` | Sprite Manager records, asset library, production-set import (#2895), reference workflow: create/generate/lock (#2896), directional walk and per-track generation/approval, animation-type definition CRUD (#3153), trim/postprocess, and per-run source-frame listing for the Loop Trimmer's re-derive (#2980), and animation render-provider readiness (#4876). |
| `apiShell.js` | Shell sessions over HTTP: hand a photo (plus a message) to the agent TUI running in a session. Keystrokes/output stay on the `shell:*` socket protocol. |
+| `apiCodeAnimation.js` | Code Animation: host-contract options, universe-styled LLM prompt building for a procedurally coded animation film, and provider generation jobs (start + poll for the HTML). |
| `apiThreejsModels.js` | Procedural Three.js model workspaces: gallery-image generation, refinement, source export, deletion, and the subject-family checklist options. |
| `apiImageTo3d.js` | Image-to-3D (`/3d`): selectable targets (TRELLIS.2) with host availability/install status, and per-image model records — create/list/get/generate/delete + GLB asset URL, the full-resolution OBJ download URL, and the AR Quick Look USDZ upload/download pair. |
| `apiPipeline.js` | Pipeline (issues + stages + canon; series names and index summaries). |
diff --git a/client/src/services/api.js b/client/src/services/api.js
index bcc4a0788a..770b5a35dd 100644
--- a/client/src/services/api.js
+++ b/client/src/services/api.js
@@ -87,6 +87,7 @@ export * from './apiShell.js';
export * from './apiMoodBoard.js';
export * from './apiDecks.js';
export * from './apiThreejsModels.js';
+export * from './apiCodeAnimation.js';
export * from './apiImporter.js';
export * from './apiStoryBuilder.js';
export * from './apiVoice.js';
diff --git a/client/src/services/apiCodeAnimation.js b/client/src/services/apiCodeAnimation.js
new file mode 100644
index 0000000000..791a6c4279
--- /dev/null
+++ b/client/src/services/apiCodeAnimation.js
@@ -0,0 +1,23 @@
+import { request } from './apiCore.js';
+
+// Code Animation — build an LLM prompt for a procedurally coded animation film
+// styled by a universe (plus mood board, references, audio), and optionally run
+// it on a provider to get the film's HTML. `options` is forwarded to the
+// request helper so callers owning their error UI can pass `{ silent: true }`.
+
+export const getCodeAnimationOptions = (options) => request('/code-animation/options', options);
+
+export const buildCodeAnimationPrompt = (brief, options) => request('/code-animation/prompt', {
+ method: 'POST',
+ body: JSON.stringify(brief),
+ ...options,
+});
+
+export const startCodeAnimationGeneration = (brief, options) => request('/code-animation/generate', {
+ method: 'POST',
+ body: JSON.stringify(brief),
+ ...options,
+});
+
+export const getCodeAnimationJob = (id, options) =>
+ request(`/code-animation/generate/${encodeURIComponent(id)}`, options);
diff --git a/client/src/services/apiMoodBoard.js b/client/src/services/apiMoodBoard.js
index e86828dc7b..1a6ce093cf 100644
--- a/client/src/services/apiMoodBoard.js
+++ b/client/src/services/apiMoodBoard.js
@@ -7,6 +7,9 @@ import { request } from './apiCore.js';
export const listMoodBoards = (options) => request('/mood-boards', options);
+// `{ id, name }` only — for pickers; skips every board's inline items.
+export const listMoodBoardNames = (options) => request('/mood-boards/names', options);
+
export const getMoodBoard = (id, options) =>
request(`/mood-boards/${encodeURIComponent(id)}`, options);
diff --git a/docs/API.md b/docs/API.md
index e06252ee78..fe90d3fff6 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -763,6 +763,7 @@ Every mounted API prefix (see `server/index.js` for the authoritative list). Dom
| `/api/games` | Game projects |
| `/api/sprites` | Sprite catalog / export |
| `/api/threejs-models` | Procedural Three.js models |
+| `/api/code-animation` | Code Animation: universe-styled prompt for an LLM-coded animation film, plus provider generation jobs (start + poll for the HTML) |
| `/api/image-to-3d` | Image-to-3D conversion |
| `/api/rigging` | Auto-skin rigging and animation retargeting for image-to-3D models |
| `/api/privacy` | PII vault / trusted-org / broker opt-out |
diff --git a/server/index.js b/server/index.js
index e5a795edeb..fb5bf492ee 100644
--- a/server/index.js
+++ b/server/index.js
@@ -141,6 +141,7 @@ import spriteRoutes from './routes/sprites.js';
import moodBoardRoutes from './routes/moodBoard.js';
import deckRoutes from './routes/decks.js';
import threejsModelsRoutes from './routes/threejsModels.js';
+import codeAnimationRoutes from './routes/codeAnimation.js';
import imageTo3dRoutes from './routes/imageTo3d.js';
import riggingRoutes from './routes/rigging.js';
import privacyRoutes from './routes/privacy.js';
@@ -413,6 +414,7 @@ app.use('/api/sprites', spriteRoutes);
app.use('/api/mood-boards', moodBoardRoutes);
app.use('/api/decks', deckRoutes);
app.use('/api/threejs-models', threejsModelsRoutes);
+app.use('/api/code-animation', codeAnimationRoutes);
app.use('/api/image-to-3d', imageTo3dRoutes);
app.use('/api/rigging', riggingRoutes);
app.use('/api/privacy', privacyRoutes);
diff --git a/server/lib/README.md b/server/lib/README.md
index 0600def844..4f744320c4 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -334,7 +334,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `homePath.js` | `scrubHomePath(value)` — replace the running user's home-directory prefix with `~` anywhere in a string, so `/Users/<name>/…` never embeds the OS username in anything a user pastes into a bug report. Non-strings pass through; a root-user container reporting `/` as home is left alone (substituting on it would rewrite every separator in every path). Zero-dependency by design: `agentRunEvents.js` re-exports it for the CoS ledger, and `scripts/doctor.js` imports it statically because it must load from a bare checkout with no `node_modules` (`scripts/pre-install-entrypoints.test.js` enforces that). |
| `jsonIo.js` | JSON/JSONL parsing and file IO, strict read sentinels, append/read/write helpers, and `createCachedStore` — a TTL-cached mutable JSON document with serialized `save`/`mutate`; its `load()` is strict (#4115) so a corrupt file rejects instead of being overwritten by the next `mutate`. |
| `settingsStore.js` | `createSettingsStore(filePath | () => filePath, defaults, { normalize? })` → `{ get, update, path }` — the one owner of a flat per-feature settings document with shipped defaults (`journal-settings.json`, `activity-digest-settings.json`, `goal-scorecard-settings.json`, …). `get()` reads strict (#4115: a corrupt file rejects rather than reading as the defaults, because `update` writes it back), merges the file over `defaults`, then runs `normalize`; `update(patch)` is a serialized `get → apply → atomicWrite` that skips `undefined` values and writes `null` as an explicit clear. Filter client-settable keys BEFORE calling `update`. Reach for `createCachedStore` for an in-place-edited document and `createCollectionStore` for per-record collections. |
-| `mimeTypes.js` | MIME tables and extension allowlists, image format detection, and filename sanitization. |
+| `mimeTypes.js` | MIME tables and extension allowlists (incl. `UPLOAD_AUDIO_EXTENSIONS`, the playable-audio subset of `/api/uploads`), image format detection, and filename sanitization. |
| `paths.js` | Canonical source/install `PATHS`, `dataPath`, and home-directory expansion. |
| `pathContainment.js` | Dependency-free leaf holding `isPathAtOrInsideDir(dir, path)` (containment where the root itself counts as inside — what a guard policing a whole tree wants, as opposed to `pathSafety.js`'s strict `isPathInsideDir`; case-folded on Windows/macOS) and `canonicalizePath(path)` (realpath of the deepest EXISTING ancestor plus the not-yet-created tail, so a target that does not exist yet still resolves through symlinked ancestors). Split out so `fileCore.js`'s #6176 guard can reach them without dragging `errorHandler.js`/`paths.js` into the closure of every server suite — see the budget in `importScoping.test.js`. Keep it free of non-builtin imports. |
| `pathSafety.js` | Filename/traversal validation, path containment, and approved image-asset resolvers. |
diff --git a/server/lib/creativeLatitude.js b/server/lib/creativeLatitude.js
index b8305a9454..1e13b13c3b 100644
--- a/server/lib/creativeLatitude.js
+++ b/server/lib/creativeLatitude.js
@@ -70,6 +70,7 @@ export function withCreativeLatitude(prompt) {
/** Prefixes whose stages/runs generate or edit creative work (story, art, canon). */
export const CREATIVE_PREFIXES = Object.freeze([
'cd-', // Creative Director: treatments, plans, scene evaluation
+ 'code-animation-', // procedurally coded animation films in a universe's style
'deck-', // Decks: sample-image style analysis, deck casting, card prompts
'fableloom-',
'importer-', // extracts canon/arcs out of existing (often licensed) source works
diff --git a/server/lib/mimeTypes.js b/server/lib/mimeTypes.js
index 1bf78c8eb8..b90939e26f 100644
--- a/server/lib/mimeTypes.js
+++ b/server/lib/mimeTypes.js
@@ -95,6 +95,12 @@ export const EXTENSION_MIME_MAP = {
* miscellaneous text/config types that are not meaningful attachment types.
* The attachments route validates against this set; uploads uses the full map.
*/
+// Audio extensions (no dot) POST /api/uploads accepts as playable tracks —
+// every audio/* entry above except MIDI, which is a score, not a recording.
+export const UPLOAD_AUDIO_EXTENSIONS = Object.freeze(Object.entries(EXTENSION_MIME_MAP)
+ .filter(([, mime]) => mime.startsWith('audio/') && mime !== 'audio/midi')
+ .map(([ext]) => ext.slice(1)));
+
export const ATTACHMENT_ALLOWED_EXTENSIONS = new Set([
'.txt', '.md', '.json', '.csv', '.xml', '.yaml', '.yml',
'.png', '.jpg', '.jpeg', '.gif', '.webp', '.svg', '.pdf',
diff --git a/server/lib/navManifest.js b/server/lib/navManifest.js
index 0a7a816941..db22b77238 100644
--- a/server/lib/navManifest.js
+++ b/server/lib/navManifest.js
@@ -54,6 +54,7 @@ const RAW_NAV_COMMANDS = [
{ id: 'nav.media.history', path: '/media/history', label: 'Media History', section: 'Create', tabGroup: 'media', tabId: 'history', tabLabel: 'History', previousPaths: ['/media-history'], aliases: ['media-history', 'video-history'], keywords: ['videos', 'gallery', 'stitch'] },
{ id: 'nav.media.collections', path: '/media/collections', label: 'Collections', section: 'Create', tabGroup: 'media', tabId: 'collections', aliases: ['collections', 'media-collections', 'stacks', 'projects'], keywords: ['bucket', 'group', 'project', 'album', 'organize'] },
{ id: 'nav.create.video', path: '/video', label: 'Video', section: 'Create', aliases: ['video', 'browse-video'], keywords: ['videos', 'watch', 'browse', 'commission outputs'] },
+ { id: 'nav.create.code-animation', path: '/code-animation', label: 'Code Animation', section: 'Create', aliases: ['code-animation', 'codeanimation', 'code-video', 'procedural-animation', 'animation-prompt'], keywords: ['animation', 'canvas', 'webgl', 'procedural', 'no assets', 'llm prompt', 'motion graphics', 'universe style', 'mood board', 'audio reactive', 'record video', 'html animation'] },
{ id: 'nav.create.creative-director', path: '/creative-director', label: 'Creative Director', section: 'Create', previousPaths: ['/media/creative-director', '/media/creative-director/:id', '/media/creative-director/:id/:tab'], aliases: ['creative-director', 'creative', 'director', 'producer', 'orchestrator', 'long-form', 'episode', 'video-production', 'create-video', 'video-workspace'], keywords: ['story', 'episode', 'narrative', 'agent', 'auto-video', 'long-form', 'directive', 'production plan', 'plan board', 'orchestrator', 'studio', 'producer'] },
{ id: 'nav.create.creative-commission', path: '/creative-commission', label: 'Creative Commissions', section: 'Create', aliases: ['creative-commission', 'commissions', 'commission', 'creation-engine', 'autonomous-creation', 'standing-brief', 'recurring-brief'], keywords: ['schedule', 'recurring', 'nightly', 'brief', 'autonomous', 'creation engine', 'cron', 'feedback', 'taste', 'standing commission', 'auto-generate'] },
{ id: 'nav.create.fableloom', path: '/fableloom', label: 'FableLoom', section: 'Create', aliases: ['fableloom', 'fable-loom', 'loom', 'branching-narrative', 'interactive-story', 'branching-story'], keywords: ['branching', 'interactive', 'narrative', 'intent', 'endings', 'reader', 'scene', 'node', 'graph', 'nonlinear', 'play', 'story graph'] },
diff --git a/server/routes/codeAnimation.js b/server/routes/codeAnimation.js
new file mode 100644
index 0000000000..c51ead25e6
--- /dev/null
+++ b/server/routes/codeAnimation.js
@@ -0,0 +1,97 @@
+/**
+ * Code Animation routes — build an LLM prompt for a procedurally coded
+ * animation film (and optionally run it to get the HTML).
+ *
+ * GET /api/code-animation/options formats, limits, host contract
+ * POST /api/code-animation/prompt resolve configurations → { prompt, attachments, frame }
+ * POST /api/code-animation/generate start a provider run → 202 job
+ * GET /api/code-animation/generate/:id poll a job (html once completed)
+ */
+
+import { Router } from 'express';
+import { z } from 'zod';
+import { asyncHandler, ServerError } from '../lib/errorHandler.js';
+import { validateRequest } from '../lib/validation.js';
+import { EFFORT_LEVELS } from '../lib/providerModels.js';
+import { emptyToNull } from '../lib/zodCompat.js';
+import {
+ buildCodeAnimationRequest,
+ getCodeAnimationJob,
+ getCodeAnimationOptions,
+ startCodeAnimationGeneration,
+} from '../services/codeAnimation/index.js';
+import {
+ CODE_ANIMATION_ASPECT_RATIOS,
+ CODE_ANIMATION_LIMITS,
+ CODE_ANIMATION_RENDERERS,
+ CODE_ANIMATION_RESOLUTIONS,
+} from '../services/codeAnimation/prompt.js';
+
+const router = Router();
+const L = CODE_ANIMATION_LIMITS;
+
+// An upload basename as POST /api/uploads returns it — never a path.
+const uploadFilenameSchema = z.string().trim().min(1).max(256)
+ .regex(/^[^/\\]+$/, 'filename must be an upload basename');
+const optionalId = z.preprocess(emptyToNull, z.string().trim().min(1).max(128).nullable().optional());
+
+const briefSchema = z.object({
+ title: z.string().trim().max(200).default(''),
+ concept: z.string().trim().min(1, 'Describe what happens in the animation').max(L.conceptMax),
+ onScreenText: z.string().trim().max(L.textMax).default(''),
+ // Refinements on top of the universe style — the universe is the art direction.
+ styleNotes: z.string().trim().max(L.styleNotesMax).default(''),
+ format: z.object({
+ durationSeconds: z.number().int().min(L.durationMin).max(L.durationMax).default(20),
+ aspectRatio: z.enum(Object.keys(CODE_ANIMATION_ASPECT_RATIOS)).default('16:9'),
+ resolution: z.enum(Object.keys(CODE_ANIMATION_RESOLUTIONS)).default('1080p'),
+ fps: z.number().int().refine((fps) => L.fpsOptions.includes(fps), 'Unsupported frame rate').default(30),
+ }).prefault({}),
+ renderer: z.enum(CODE_ANIMATION_RENDERERS).default('auto'),
+ interactive: z.boolean().default(false),
+ soundtrack: z.enum(['none', 'procedural']).default('none'),
+ universeId: optionalId,
+ // Absent → follow the universe's linked board; '' / null → no board.
+ moodBoardId: optionalId,
+ includeMoodBoardImages: z.boolean().default(true),
+ referenceImages: z.array(z.object({
+ filename: uploadFilenameSchema,
+ 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(),
+}).strict();
+
+const generateSchema = briefSchema.extend({
+ providerId: z.string().trim().min(1).max(128),
+ model: z.string().trim().max(256).optional(),
+ effort: z.preprocess(emptyToNull, z.enum(EFFORT_LEVELS).nullable().optional()),
+}).strict();
+
+router.get('/options', (_req, res) => {
+ res.json(getCodeAnimationOptions());
+});
+
+router.post('/prompt', asyncHandler(async (req, res) => {
+ const input = validateRequest(briefSchema, req.body ?? {});
+ const { prompt, frame, attachments, audioUrl, moodBoardId } = await buildCodeAnimationRequest(input);
+ res.json({ prompt, frame, attachments, audioUrl, moodBoardId });
+}));
+
+router.post('/generate', asyncHandler(async (req, res) => {
+ const input = validateRequest(generateSchema, req.body ?? {});
+ res.status(202).json(await startCodeAnimationGeneration(input));
+}));
+
+router.get('/generate/:id', asyncHandler(async (req, res) => {
+ const job = getCodeAnimationJob(req.params.id);
+ if (!job) throw new ServerError('Generation job not found (it may have expired or the server restarted)', { status: 404, code: 'NOT_FOUND' });
+ res.json(job);
+}));
+
+export default router;
diff --git a/server/routes/codeAnimation.test.js b/server/routes/codeAnimation.test.js
new file mode 100644
index 0000000000..8bd1af0fd9
--- /dev/null
+++ b/server/routes/codeAnimation.test.js
@@ -0,0 +1,170 @@
+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
+import express from 'express';
+import { mkdirSync, writeFileSync } from 'fs';
+import { join } from 'path';
+import { request } from '../lib/testHelper.js';
+import { errorMiddleware } from '../lib/errorHandler.js';
+import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../lib/mockPathsDataRoot.js';
+
+vi.mock('../lib/paths.js', async (importOriginal) =>
+ makePathsProxy(await importOriginal(), { dataRoot: () => lazyTempDataRoot('portos-code-animation-') }));
+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/promptRunner.js', () => ({ runPromptThroughProvider: vi.fn() }));
+
+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 { runPromptThroughProvider } from '../services/promptRunner.js';
+import routes from './codeAnimation.js';
+
+const makeApp = () => {
+ const app = express();
+ app.use(express.json());
+ app.use('/api/code-animation', routes);
+ app.use(errorMiddleware);
+ return app;
+};
+
+const UNIVERSE = {
+ id: 'universe-1',
+ name: 'Example Universe',
+ influences: { embrace: ['ink wash', 'muted indigo'], avoid: ['photorealism'] },
+ styleNotes: 'quiet and melancholic',
+ styleReferences: [{ id: 'ref-1', title: 'Night markets', prompt: 'paper lanterns', imageRefs: ['style-ref.png'] }],
+ moodBoardId: 'board-1',
+};
+const BOARD = {
+ id: 'board-1',
+ name: 'Dusk',
+ description: 'amber evenings',
+ items: [
+ { id: 'i1', type: 'image', mediaKey: 'image:pin.png', caption: 'harbor glow' },
+ { id: 'i2', type: 'text', text: 'long shadows' },
+ { id: 'i3', type: 'image', imageUrl: '/data/image-refs/sheet.png', caption: 'canon sheet' },
+ ],
+};
+const brief = { concept: 'A lantern drifts over a sleeping city', universeId: 'universe-1' };
+
+beforeAll(() => {
+ mkdirSync(PATHS.uploads, { recursive: true });
+ mkdirSync(PATHS.imageRefs, { recursive: true });
+ mkdirSync(PATHS.images, { 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');
+});
+afterAll(cleanupTempDataRoots);
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ getUniverse.mockResolvedValue(UNIVERSE);
+ getBoard.mockResolvedValue(BOARD);
+});
+
+describe('POST /api/code-animation/prompt', () => {
+ it('builds the art direction from the universe and its linked mood board', async () => {
+ const res = await request(makeApp()).post('/api/code-animation/prompt').send({
+ ...brief,
+ referenceImages: [{ filename: 'abc12345-hero.png', label: 'hero.png', note: 'the silhouette' }],
+ audio: { filename: 'abc12345-theme.mp3', label: 'theme.mp3', durationSeconds: 30, notes: '120 BPM' },
+ });
+ expect(res.status).toBe(200);
+ expect(getBoard).toHaveBeenCalledWith('board-1');
+ expect(res.body.moodBoardId).toBe('board-1');
+ expect(res.body.prompt).toContain('The art style comes from the universe "Example Universe"');
+ expect(res.body.prompt).toContain('ink wash, muted indigo');
+ expect(res.body.prompt).toContain('note: long shadows');
+ expect(res.body.prompt).toContain('"theme.mp3" (30.0s long)');
+ expect(res.body.frame).toEqual({ width: 1920, height: 1080, fps: 30, durationSeconds: 20 });
+ // Uploads first, then the universe's style image, then the board's pin —
+ // and only served URLs reach the client.
+ expect(res.body.attachments).toEqual([
+ { label: 'hero.png', origin: 'upload', url: '/api/uploads/abc12345-hero.png' },
+ { label: 'Night markets', origin: 'universe', url: '/data/image-refs/style-ref.png' },
+ { label: 'harbor glow', origin: 'mood-board', url: '/data/images/pin.png' },
+ { label: 'canon sheet', origin: 'mood-board', url: '/data/image-refs/sheet.png' },
+ ]);
+ expect(res.body.audioUrl).toBe('/api/uploads/abc12345-theme.mp3');
+ expect(JSON.stringify(res.body)).not.toContain(PATHS.data);
+ });
+
+ it('skips the board when the user explicitly picks none', async () => {
+ const res = await request(makeApp()).post('/api/code-animation/prompt').send({ ...brief, moodBoardId: '' });
+ expect(res.status).toBe(200);
+ expect(getBoard).not.toHaveBeenCalled();
+ expect(res.body.moodBoardId).toBeNull();
+ expect(res.body.prompt).not.toContain('Mood board:');
+ });
+
+ it('rejects a missing brief, a stray upload, and an unknown universe', async () => {
+ const app = makeApp();
+ expect((await request(app).post('/api/code-animation/prompt').send({ concept: '' })).status).toBe(400);
+ const stray = await request(app).post('/api/code-animation/prompt').send({ ...brief, referenceImages: [{ filename: 'missing.png' }] });
+ expect(stray.status).toBe(400);
+ expect(stray.body.code).toBe('REFERENCE_NOT_FOUND');
+ const traversal = await request(app).post('/api/code-animation/prompt').send({ ...brief, audio: { filename: '../secret.mp3' } });
+ expect(traversal.status).toBe(400);
+ 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);
+ });
+});
+
+describe('POST /api/code-animation/generate', () => {
+ const pollUntilSettled = async (app, id) => {
+ let job;
+ await vi.waitFor(async () => {
+ job = (await request(app).get(`/api/code-animation/generate/${id}`)).body;
+ expect(job.status).not.toBe('running');
+ });
+ return job;
+ };
+
+ it('runs the prompt on an API provider with the references attached and returns the HTML', async () => {
+ getProviderById.mockResolvedValue({ id: 'api-1', type: 'api', enabled: true });
+ runPromptThroughProvider.mockResolvedValue({
+ runId: 'run-1',
+ text: 'Here:\n```html\n<!DOCTYPE html><html><body><canvas></canvas></body></html>\n```',
+ provider: { id: 'api-1' },
+ model: 'example-model',
+ });
+ const app = makeApp();
+ const res = await request(app).post('/api/code-animation/generate').send({ ...brief, providerId: 'api-1' });
+ expect(res.status).toBe(202);
+ expect(res.body.status).toBe('running');
+ const job = await pollUntilSettled(app, res.body.id);
+ expect(job).toMatchObject({ status: 'completed', providerId: 'api-1', model: 'example-model', runId: 'run-1' });
+ expect(job.html).toBe('<!DOCTYPE html><html><body><canvas></canvas></body></html>');
+ const call = runPromptThroughProvider.mock.calls[0][0];
+ expect(call.source).toBe('code-animation-generation');
+ expect(call.cwd).toBe(PATHS.data);
+ expect(call.screenshots).toEqual([join(PATHS.imageRefs, 'style-ref.png'), join(PATHS.images, 'pin.png'), join(PATHS.imageRefs, 'sheet.png')]);
+ expect(call.prompt).toContain('attached to this request');
+ });
+
+ it('fails the job when the response holds no HTML document', async () => {
+ getProviderById.mockResolvedValue({ id: 'cli-1', type: 'cli', enabled: true });
+ runPromptThroughProvider.mockResolvedValue({ text: 'I wrote the file to disk.', provider: { id: 'cli-1' } });
+ const app = makeApp();
+ const res = await request(app).post('/api/code-animation/generate').send({ ...brief, providerId: 'cli-1' });
+ expect(runPromptThroughProvider.mock.calls[0][0].screenshots).toEqual([]);
+ const job = await pollUntilSettled(app, res.body.id);
+ expect(job.status).toBe('failed');
+ expect(job.error).toMatch(/did not contain an HTML document/);
+ });
+
+ it('refuses a disabled provider before starting a job', async () => {
+ getProviderById.mockResolvedValue({ id: 'api-1', type: 'api', enabled: false });
+ const res = await request(makeApp()).post('/api/code-animation/generate').send({ ...brief, providerId: 'api-1' });
+ expect(res.status).toBe(400);
+ expect(runPromptThroughProvider).not.toHaveBeenCalled();
+ });
+
+ it('404s an unknown job', async () => {
+ expect((await request(makeApp()).get('/api/code-animation/generate/nope')).status).toBe(404);
+ });
+});
diff --git a/server/routes/moodBoard.js b/server/routes/moodBoard.js
index 33948ace2d..d4254a0c41 100644
--- a/server/routes/moodBoard.js
+++ b/server/routes/moodBoard.js
@@ -25,6 +25,7 @@ import { synthesizeBoardStyle } from '../services/moodBoardStyleSynthesis.js';
import { STYLE_NOTES_MAX } from '../services/universeBuilder.js';
import {
listBoards,
+ listBoardNames,
getBoard,
createBoard,
updateBoard,
@@ -50,6 +51,11 @@ router.get('/', asyncHandler(async (req, res) => {
res.json(paginateArray(boards, req.query, { defaultLimit: 50, maxLimit: 500 }));
}));
+// Registered ahead of `/:id` so the literal path is not read as a board id.
+router.get('/names', asyncHandler(async (_req, res) => {
+ res.json(await listBoardNames());
+}));
+
router.get('/:id', asyncHandler(async (req, res) => {
const board = await getBoard(req.params.id);
if (!board) throw new ServerError('Mood board not found', { status: 404, code: 'NOT_FOUND' });
diff --git a/server/routes/moodBoard.test.js b/server/routes/moodBoard.test.js
index 39e5ccc323..325149c46c 100644
--- a/server/routes/moodBoard.test.js
+++ b/server/routes/moodBoard.test.js
@@ -7,6 +7,7 @@ import { errorMiddleware } from '../lib/errorHandler.js';
// not the DB-backed board logic (covered by moodBoard/db.test.js).
vi.mock('../services/moodBoard/index.js', () => ({
listBoards: vi.fn(async () => []),
+ listBoardNames: vi.fn(async () => []),
getBoard: vi.fn(),
createBoard: vi.fn(),
updateBoard: vi.fn(),
@@ -40,6 +41,14 @@ const makeApp = () => {
describe('mood-board routes', () => {
beforeEach(() => vi.clearAllMocks());
+ it('GET /names serves the picker projection rather than a board lookup', async () => {
+ svc.listBoardNames.mockResolvedValueOnce([{ id: 'mb-1', name: 'A' }]);
+ const res = await request(makeApp()).get('/api/mood-boards/names');
+ expect(res.status).toBe(200);
+ expect(res.body).toEqual([{ id: 'mb-1', name: 'A' }]);
+ expect(svc.getBoard).not.toHaveBeenCalled();
+ });
+
describe('GET /', () => {
it('returns the full boards array by default', async () => {
svc.listBoards.mockResolvedValueOnce([{ id: 'mb-1', name: 'A' }]);
diff --git a/server/services/codeAnimation/index.js b/server/services/codeAnimation/index.js
new file mode 100644
index 0000000000..02cf7481cb
--- /dev/null
+++ b/server/services/codeAnimation/index.js
@@ -0,0 +1,299 @@
+/**
+ * Code Animation orchestration — resolves a brief's configurations (universe,
+ * mood board, reference uploads, audio) into prompt inputs, builds the prompt,
+ * and optionally runs it through an AI provider to get the animation's HTML.
+ *
+ * Nothing is persisted: the prompt is returned for the user to copy, and a
+ * generation is a short-lived in-memory job the page polls until the HTML is
+ * ready. The page then previews, records, and saves the result through the
+ * existing gallery-video upload path, which is where the durable artifact
+ * lives. A server restart simply forgets in-flight jobs.
+ *
+ * The heavy dependencies (provider runner, universe + mood-board stores) are
+ * imported lazily so the options/prompt path and its tests stay light.
+ */
+
+import { randomUUID } from 'crypto';
+import { ServerError } from '../../lib/errorHandler.js';
+import { PATHS } from '../../lib/paths.js';
+import { makePathResolver, resolveGalleryImage, resolveImageRef } from '../../lib/pathSafety.js';
+import { universeVisualStyleTokens } from '../../lib/universeVisualStyle.js';
+import { isNonBlankStr, trimTo } from '../../lib/textUtils.js';
+import { UPLOAD_AUDIO_EXTENSIONS } from '../../lib/mimeTypes.js';
+import {
+ buildCodeAnimationPrompt,
+ extractAnimationHtml,
+ resolveFrameSize,
+ CODE_ANIMATION_ASPECT_RATIOS,
+ CODE_ANIMATION_AUDIO_GLOBAL,
+ CODE_ANIMATION_LIMITS,
+ CODE_ANIMATION_MESSAGES,
+ CODE_ANIMATION_RENDERERS,
+ CODE_ANIMATION_RESOLUTIONS,
+} from './prompt.js';
+
+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 JOB_TTL_MS = 60 * 60 * 1000;
+const JOBS_MAX = 20;
+const jobs = new Map();
+
+export function getCodeAnimationOptions() {
+ return {
+ aspectRatios: Object.keys(CODE_ANIMATION_ASPECT_RATIOS),
+ resolutions: Object.keys(CODE_ANIMATION_RESOLUTIONS),
+ renderers: CODE_ANIMATION_RENDERERS,
+ limits: CODE_ANIMATION_LIMITS,
+ messages: CODE_ANIMATION_MESSAGES,
+ audioGlobal: CODE_ANIMATION_AUDIO_GLOBAL,
+ audioExtensions: UPLOAD_AUDIO_EXTENSIONS,
+ };
+}
+
+// The two served image dirs a reference can live in, by asset kind.
+const IMAGE_DIRS = {
+ 'image-ref': { resolve: resolveImageRef, urlPrefix: '/data/image-refs/' },
+ image: { resolve: resolveGalleryImage, urlPrefix: '/data/images/' },
+};
+
+// A local image as a prompt reference, or null when the file is missing.
+function localReference(kind, filename, label, origin) {
+ const dir = IMAGE_DIRS[kind];
+ const path = dir?.resolve(filename);
+ return path ? { label, origin, path, url: `${dir.urlPrefix}${encodeURIComponent(filename)}` } : null;
+}
+
+// Resolve reference candidates in order until `slots` are filled, so a
+// universe or board with many images costs only the stats it can use.
+function fillReferences(candidates, slots) {
+ const images = [];
+ for (const candidate of candidates) {
+ if (images.length >= slots) break;
+ const image = candidate();
+ if (image && !images.some((existing) => existing.path === image.path)) images.push(image);
+ }
+ return images;
+}
+
+async function resolveUniverse(universeId, { imageSlots }) {
+ if (!universeId) return null;
+ const { getUniverse } = await import('../universeBuilder/crud.js');
+ const universe = await getUniverse(universeId).catch((error) => {
+ if (error?.code === 'NOT_FOUND') throw new ServerError('Universe not found', { status: 404, code: 'NOT_FOUND' });
+ throw error;
+ });
+ const { embrace, avoid } = universeVisualStyleTokens(universe);
+ const refs = Array.isArray(universe.styleReferences) ? universe.styleReferences : [];
+ const styleReferences = refs
+ .filter((ref) => isNonBlankStr(ref?.prompt))
+ .slice(0, 6)
+ .map((ref) => ({ title: trimTo(ref.title, 120), prompt: trimTo(ref.prompt, 600) }));
+ // A style image lives in either served dir depending on how it was made
+ // (style-reference upload vs gallery probe), so try refs first, then gallery.
+ const styleImage = (filename, label) => () => localReference('image-ref', filename, label, 'universe')
+ || localReference('image', filename, label, 'universe');
+ const candidates = [
+ ...refs.map((ref) => [ref?.imageRefs?.[0], trimTo(ref?.title, 120) || 'Universe style reference']),
+ ...(Array.isArray(universe.styleImageRefs) ? universe.styleImageRefs : []).map((filename) => [filename, 'Universe style probe']),
+ ].filter(([filename]) => isNonBlankStr(filename)).map(([filename, label]) => styleImage(filename, label));
+ const images = fillReferences(candidates, imageSlots);
+ return {
+ name: universe.name,
+ embrace,
+ avoid,
+ styleNotes: trimTo(universe.styleNotes, 2_000),
+ styleReferences,
+ moodBoardId: isNonBlankStr(universe.moodBoardId) ? universe.moodBoardId : null,
+ images,
+ };
+}
+
+async function resolveMoodBoard(moodBoardId, { imageSlots }) {
+ if (!moodBoardId) return { board: null, images: [] };
+ const [{ getBoard }, { collectBoardStyleContext }, { boardItemLocalImage }] = await Promise.all([
+ import('../moodBoard/db.js'),
+ import('../moodBoard/styleContext.js'),
+ import('../moodBoard/logic.js'),
+ ]);
+ const board = await getBoard(moodBoardId);
+ if (!board) throw new ServerError('Mood board not found', { status: 404, code: 'NOT_FOUND' });
+ // Text items, videos, and external pins attach nothing — they still
+ // contribute their caption/analysis text through the board context.
+ const candidates = (board.items || []).map((item) => () => {
+ const asset = boardItemLocalImage(item);
+ return asset ? localReference(asset.kind, asset.filename, trimTo(item.caption, 120) || asset.filename, 'mood-board') : null;
+ });
+ return { board: collectBoardStyleContext(board), images: fillReferences(candidates, imageSlots) };
+}
+
+function resolveUploadedImages(referenceImages) {
+ return referenceImages.map((ref) => {
+ const path = resolveUploadImage(ref.filename);
+ if (!path) {
+ throw new ServerError(`Reference image not found: ${ref.filename}`, { status: 400, code: 'REFERENCE_NOT_FOUND' });
+ }
+ return {
+ label: trimTo(ref.label, 120) || ref.filename,
+ origin: 'upload',
+ note: ref.note,
+ path,
+ url: `/api/uploads/${encodeURIComponent(ref.filename)}`,
+ };
+ });
+}
+
+function resolveAudio(audio) {
+ if (!audio) return null;
+ if (!resolveUploadAudio(audio.filename)) {
+ throw new ServerError(`Audio file not found: ${audio.filename}`, { status: 400, code: 'AUDIO_NOT_FOUND' });
+ }
+ return {
+ name: trimTo(audio.label, 200) || audio.filename,
+ durationSeconds: audio.durationSeconds ?? null,
+ notes: audio.notes,
+ url: `/api/uploads/${encodeURIComponent(audio.filename)}`,
+ };
+}
+
+/**
+ * Resolve every configuration a brief references and build its prompt.
+ * `delivery` decides how reference images are described to the model
+ * (attached for copy/API, on-disk paths for CLI agents).
+ */
+export async function buildCodeAnimationRequest(input, { delivery = 'copy' } = {}) {
+ const uploads = resolveUploadedImages(input.referenceImages || []);
+ const audio = resolveAudio(input.audio);
+ const universe = await resolveUniverse(input.universeId, {
+ imageSlots: Math.max(0, CODE_ANIMATION_LIMITS.referenceImagesMax - uploads.length),
+ });
+ // The universe is the art direction, so its linked mood board is the default:
+ // an ABSENT moodBoardId follows the universe, an explicit null means none.
+ const moodBoardId = input.moodBoardId === undefined ? universe?.moodBoardId : input.moodBoardId;
+ // Reference-image slots go to the user's own uploads first, then the
+ // universe's style images, then the board's pins.
+ const universeImages = universe?.images || [];
+ const { board, images: boardImages } = await resolveMoodBoard(moodBoardId, {
+ imageSlots: input.includeMoodBoardImages === false
+ ? 0
+ : Math.max(0, CODE_ANIMATION_LIMITS.referenceImagesMax - uploads.length - universeImages.length),
+ });
+ const referenceImages = [...uploads, ...universeImages, ...boardImages];
+ const prompt = buildCodeAnimationPrompt({
+ title: input.title,
+ concept: input.concept,
+ onScreenText: input.onScreenText,
+ styleNotes: input.styleNotes,
+ format: input.format,
+ renderer: input.renderer,
+ interactive: input.interactive,
+ soundtrack: input.soundtrack,
+ audio,
+ universe,
+ moodBoard: board,
+ referenceImages,
+ delivery,
+ });
+ return {
+ prompt,
+ moodBoardId: moodBoardId || null,
+ frame: { ...resolveFrameSize(input.format.aspectRatio, input.format.resolution), fps: input.format.fps, durationSeconds: input.format.durationSeconds },
+ // Absolute paths never leave the server — the client gets served URLs only.
+ attachments: referenceImages.map(({ label, origin, url }) => ({ label, origin, url })),
+ audioUrl: audio?.url || null,
+ referencePaths: referenceImages.map((image) => image.path),
+ };
+}
+
+// Drop settled jobs past their TTL, then the oldest settled ones past the cap.
+// A running job is never evicted — its result would have nowhere to land.
+function pruneJobs() {
+ const now = Date.now();
+ const settled = [...jobs.values()].filter((job) => job.status !== 'running')
+ .sort((a, b) => a.updatedAtMs - b.updatedAtMs);
+ let overflow = jobs.size - JOBS_MAX;
+ for (const job of settled) {
+ if (overflow > 0 || now - job.updatedAtMs > JOB_TTL_MS) {
+ jobs.delete(job.id);
+ overflow -= 1;
+ }
+ }
+}
+
+const publicJob = ({ updatedAtMs: _updatedAtMs, ...job }) => job;
+
+function settleJob(id, patch) {
+ const job = jobs.get(id);
+ if (!job) return;
+ jobs.set(id, { ...job, ...patch, completedAt: new Date().toISOString(), updatedAtMs: Date.now() });
+}
+
+async function runGeneration(jobId, { provider, model, effort, prompt, referencePaths }) {
+ const { runPromptThroughProvider } = await import('../promptRunner.js');
+ const result = await runPromptThroughProvider({
+ provider,
+ model: model || undefined,
+ effort: effort || undefined,
+ prompt,
+ source: 'code-animation-generation',
+ // CLI/TUI agents only need to read the references and print a document;
+ // keep them in runtime data so a generation can't become a code-editing
+ // session in the PortOS checkout.
+ cwd: PATHS.data,
+ screenshots: provider.type === 'api' ? referencePaths : [],
+ timeout: Math.max(provider.timeout || 0, 15 * 60 * 1000),
+ });
+ const html = extractAnimationHtml(result.text);
+ if (!html) throw new Error('The model response did not contain an HTML document');
+ return { html, provider: result.provider?.id || provider.id, model: result.model || null, runId: result.runId || null };
+}
+
+/**
+ * Start generating the animation HTML. Resolves the provider and builds the
+ * prompt synchronously (so a bad provider/universe/upload is a 4xx on this
+ * request), then runs the model in the background and returns the job.
+ */
+export async function startCodeAnimationGeneration(input) {
+ const { getProviderById } = await import('../providers.js');
+ const provider = await getProviderById(input.providerId);
+ if (!provider || provider.enabled === false) {
+ throw new ServerError('Choose an enabled AI provider', { status: 400, code: 'PROVIDER_UNAVAILABLE' });
+ }
+ const built = await buildCodeAnimationRequest(input, { delivery: provider.type === 'api' ? 'api' : 'cli' });
+ pruneJobs();
+ const id = randomUUID();
+ const now = new Date().toISOString();
+ jobs.set(id, {
+ id,
+ status: 'running',
+ providerId: provider.id,
+ model: input.model || null,
+ frame: built.frame,
+ audioUrl: built.audioUrl,
+ html: null,
+ error: null,
+ runId: null,
+ startedAt: now,
+ completedAt: null,
+ updatedAtMs: Date.now(),
+ });
+ console.log(`🎞️ Code animation generation ${id.slice(0, 8)} started on ${provider.id}`);
+ runGeneration(id, { provider, model: input.model, effort: input.effort, prompt: built.prompt, referencePaths: built.referencePaths })
+ .then(({ html, provider: ranOn, model, runId }) => {
+ settleJob(id, { status: 'completed', html, providerId: ranOn, model, runId });
+ console.log(`✅ Code animation generation ${id.slice(0, 8)} completed (${html.length} chars)`);
+ })
+ .catch((error) => {
+ const message = String(error?.message || error || 'Generation failed').slice(0, 2_000);
+ settleJob(id, { status: 'failed', error: message });
+ console.error(`❌ Code animation generation ${id.slice(0, 8)} failed: ${message}`);
+ });
+ return { ...publicJob(jobs.get(id)), prompt: built.prompt, attachments: built.attachments };
+}
+
+export function getCodeAnimationJob(id) {
+ const job = jobs.get(id);
+ return job ? publicJob(job) : null;
+}
+
diff --git a/server/services/codeAnimation/prompt.js b/server/services/codeAnimation/prompt.js
new file mode 100644
index 0000000000..e8454caf92
--- /dev/null
+++ b/server/services/codeAnimation/prompt.js
@@ -0,0 +1,266 @@
+/**
+ * Code Animation prompt builder (pure).
+ *
+ * Code Animation asks an LLM to write ONE self-contained HTML file that draws
+ * an animated film procedurally — no image/font/library assets, every frame
+ * produced by code. The art style comes from the universe's style guide (its
+ * curated embrace/avoid tokens, style references, and tone notes), refined by a
+ * mood board's notes/captions/analyses, reference images, optional per-film
+ * style notes, and an audio track.
+ *
+ * The prompt also pins a small RUNTIME CONTRACT the PortOS preview host relies
+ * on — a deterministic `renderFrame(t)`, `ANIMATION_META`, the audio URL hook,
+ * and a postMessage recording handshake — so a generated page can be previewed,
+ * scrubbed, and recorded to a WebM video without PortOS knowing anything else
+ * about its internals. The page stays fully usable standalone (its own Record
+ * button downloads the video) when the user pastes the prompt into an external
+ * LLM instead.
+ *
+ * Everything here is deterministic string assembly over already-resolved
+ * inputs; loading the universe/board and resolving file paths happens in
+ * `index.js`.
+ */
+
+import { isNonBlankStr, trimTo } from '../../lib/textUtils.js';
+
+// The postMessage vocabulary between the preview host (parent) and the
+// generated page (sandboxed iframe). Served to the client through the options
+// endpoint so both halves read one definition.
+export const CODE_ANIMATION_MESSAGES = Object.freeze({
+ ready: 'code-animation:ready',
+ record: 'code-animation:record',
+ recorded: 'code-animation:recorded',
+ progress: 'code-animation:progress',
+ error: 'code-animation:error',
+});
+
+// The global the host sets (before any page script runs) to the audio track's
+// URL. Absent when the user supplied no audio or opened the file standalone.
+export const CODE_ANIMATION_AUDIO_GLOBAL = 'ANIMATION_AUDIO_URL';
+
+export const CODE_ANIMATION_ASPECT_RATIOS = Object.freeze({
+ '16:9': { width: 16, height: 9 },
+ '9:16': { width: 9, height: 16 },
+ '1:1': { width: 1, height: 1 },
+ '4:5': { width: 4, height: 5 },
+ '4:3': { width: 4, height: 3 },
+ '21:9': { width: 21, height: 9 },
+});
+
+// The SHORT side, in pixels. 1080p renders are the default; 720p keeps a heavy
+// particle or oil-stroke style inside a real-time frame budget.
+export const CODE_ANIMATION_RESOLUTIONS = Object.freeze({ '720p': 720, '1080p': 1080 });
+
+export const CODE_ANIMATION_RENDERERS = Object.freeze(['auto', 'canvas2d', 'webgl', 'svg']);
+
+export const CODE_ANIMATION_LIMITS = Object.freeze({
+ durationMin: 3,
+ durationMax: 180,
+ fpsOptions: [24, 30, 60],
+ conceptMax: 6_000,
+ textMax: 4_000,
+ styleNotesMax: 2_000,
+ referenceImagesMax: 8,
+ referenceNoteMax: 300,
+ audioNotesMax: 1_500,
+});
+
+const RENDERER_GUIDANCE = {
+ auto: 'Pick the renderer that best serves the style: Canvas 2D for most illustrative looks, raw WebGL (no libraries) when you need thousands of primitives or shader effects.',
+ canvas2d: 'Render with the Canvas 2D API.',
+ webgl: 'Render with raw WebGL / WebGL2 and hand-written shaders (no libraries).',
+ svg: 'Render with inline SVG driven from script, rasterized onto the recording canvas each frame (draw the serialized SVG via an Image) so recording still captures it.',
+};
+
+/** Even pixel dimensions for an aspect ratio at a short-side resolution. */
+export function resolveFrameSize(aspectRatio, resolution) {
+ const ratio = CODE_ANIMATION_ASPECT_RATIOS[aspectRatio] || CODE_ANIMATION_ASPECT_RATIOS['16:9'];
+ const shortSide = CODE_ANIMATION_RESOLUTIONS[resolution] || CODE_ANIMATION_RESOLUTIONS['1080p'];
+ const even = (n) => Math.round(n / 2) * 2;
+ if (ratio.width >= ratio.height) {
+ return { width: even((shortSide * ratio.width) / ratio.height), height: shortSide };
+ }
+ return { width: shortSide, height: even((shortSide * ratio.height) / ratio.width) };
+}
+
+const bulletList = (values) => values.map((value) => `- ${value}`).join('\n');
+
+// The art direction. The universe's style guide IS the look — the same curated
+// tokens every other Create surface renders that world with — so the film
+// matches the universe's stills and videos; the per-animation notes only
+// refine it. The model's job is to translate that look into drawing code.
+function artDirectionSection({ universe, styleNotes, hasMoodBoard }) {
+ const lines = [];
+ if (universe) {
+ lines.push(`The art style comes from the universe "${universe.name}". Match its established look exactly — this film must sit beside the universe's other artwork as the same world.`);
+ if (universe.embrace?.length) lines.push(`Visual style to embrace: ${universe.embrace.join(', ')}`);
+ if (universe.avoid?.length) lines.push(`Visual style to avoid: ${universe.avoid.join(', ')}`);
+ if (universe.styleReferences?.length) {
+ lines.push('Style references curated for this universe:');
+ lines.push(bulletList(universe.styleReferences.map((ref) => (ref.title ? `${ref.title}: ${ref.prompt}` : ref.prompt))));
+ }
+ if (isNonBlankStr(universe.styleNotes)) {
+ lines.push(`Tone and staging notes (context for mood — do not depict entities they name unless the brief asks): ${universe.styleNotes}`);
+ }
+ }
+ if (isNonBlankStr(styleNotes)) {
+ lines.push(`${universe ? 'Refinements for this animation' : 'Style direction from the artist'}: ${trimTo(styleNotes, CODE_ANIMATION_LIMITS.styleNotesMax)}`);
+ }
+ if (!lines.length && !hasMoodBoard) {
+ lines.push('No style was specified — choose a distinctive, cohesive art style that suits the brief and commit to it.');
+ }
+ if (lines.length || hasMoodBoard) {
+ lines.push('Translate the style into drawing technique: decide how its medium, line quality, texture, palette, and lighting are produced procedurally (layered translucent fills for washes, pressure-modulated strokes for ink, low-res upscaling with dithering for pixel art, additive glow passes for neon, noise-driven grain for paper or film), then apply that technique consistently to every element.');
+ }
+ return lines.join('\n');
+}
+
+function moodBoardSection(board) {
+ if (!board) return '';
+ const lines = [`Mood board: "${board.name || 'Untitled board'}" — distill its through-line (palette, texture, lighting, rhythm, mood), not any single item.`];
+ if (isNonBlankStr(board.description)) lines.push(`Board description: ${board.description}`);
+ const fragments = (board.items || []).map((item) => {
+ const parts = [];
+ if (item.note) parts.push(`note: ${item.note}`);
+ if (item.caption) parts.push(`caption: ${item.caption}`);
+ if (item.analyzedPrompt) parts.push(`visual analysis: ${item.analyzedPrompt}`);
+ if (item.analyzedNegative) parts.push(`avoid: ${item.analyzedNegative}`);
+ return parts.join('; ');
+ }).filter(Boolean);
+ if (fragments.length) lines.push(bulletList(fragments));
+ if (board.droppedItems) lines.push(`(${board.droppedItems} more board items omitted for length.)`);
+ return lines.join('\n');
+}
+
+function referenceImagesSection(images, delivery) {
+ if (!images.length) return '';
+ const intro = {
+ copy: 'Reference images are attached alongside this prompt, in this order:',
+ api: 'Reference images are attached to this request, in this order:',
+ cli: 'Reference images are on disk — open and study each one:',
+ }[delivery] || 'Reference images, in order:';
+ const rows = images.map((image, index) => {
+ const where = delivery === 'cli' && image.path ? ` (${image.path})` : '';
+ const note = isNonBlankStr(image.note) ? ` — ${trimTo(image.note, CODE_ANIMATION_LIMITS.referenceNoteMax)}` : '';
+ const origin = { 'mood-board': ' [from the mood board]', universe: ' [universe style image]' }[image.origin] || '';
+ return `${index + 1}. ${image.label}${origin}${where}${note}`;
+ });
+ return `${intro}\n${rows.join('\n')}\nUse them for palette, composition, silhouettes, texture, and lighting. Do NOT embed, fetch, or base64 them — recreate what matters procedurally in code.`;
+}
+
+function audioSection({ audio, soundtrack, durationSeconds }) {
+ if (audio) {
+ const lines = [
+ `An audio track drives this animation: "${audio.name}"${audio.durationSeconds ? ` (${audio.durationSeconds.toFixed(1)}s long)` : ''}.`,
+ ];
+ if (isNonBlankStr(audio.notes)) lines.push(`What the artist says about the track (tempo, sections, cues): ${trimTo(audio.notes, CODE_ANIMATION_LIMITS.audioNotesMax)}`);
+ lines.push(
+ `- Read the track URL from \`window.${CODE_ANIMATION_AUDIO_GLOBAL}\` (set by the host before your script runs). Play it through an <audio> element routed into Web Audio (createMediaElementSource → AnalyserNode → destination).`,
+ '- While audio plays, the timeline clock IS `audio.currentTime` so picture and sound never drift. Map the analyser\'s bass / mid / treble energy and detected onsets onto motion, scale, color, and cuts so the picture visibly dances to the music.',
+ `- If \`window.${CODE_ANIMATION_AUDIO_GLOBAL}\` is unset (the file was opened on its own), show a small "Load audio" file input in the controls overlay and fall back to a silent clock until a file is chosen.`,
+ `- The video lasts ${durationSeconds}s; if the track is longer, fade the audio out over the final second.`,
+ );
+ return lines.join('\n');
+ }
+ if (soundtrack === 'procedural') {
+ return 'No audio file was supplied. Compose a procedural soundtrack with the Web Audio API (oscillators, noise, envelopes, a simple sequencer) that matches the mood and is synchronized to the visual beats. Start it on the first user gesture (Play/Record); resume a suspended AudioContext.';
+ }
+ return 'The animation is silent — no audio.';
+}
+
+function runtimeContract({ width, height, fps, durationSeconds, interactive, hasAudio }) {
+ const m = CODE_ANIMATION_MESSAGES;
+ const audioTrack = hasAudio
+ ? ' Mix the audio in: route the audio graph into a MediaStreamAudioDestinationNode and add its track to the recorded stream.'
+ : '';
+ const interaction = interactive
+ ? '\n8. Interactivity: pointer movement/clicks and a few keys should perturb the scene in-style (e.g. attract particles, shift light, trigger an accent). Interaction is a live layer on top of the timeline — `renderFrame(t)` with no interaction must still reproduce the authored film exactly, and recording always uses that clean path.'
+ : '';
+ return `RUNTIME CONTRACT (required — the PortOS preview host depends on every item):
+1. One <canvas> with an internal resolution of exactly ${width}×${height}px, CSS-scaled to fit the viewport with letterboxing on a black background. Every visible pixel of the film is drawn onto this canvas.
+2. \`window.ANIMATION_META = { title, duration: ${durationSeconds}, fps: ${fps}, width: ${width}, height: ${height} }\`.
+3. \`window.renderFrame(t)\` draws the frame at time t (seconds, 0 ≤ t ≤ ${durationSeconds}) DETERMINISTICALLY: use a seeded PRNG, never Math.random/Date.now/performance.now inside drawing, and derive all motion from t (plus audio analysis while audio plays). Scrubbing to the same t twice must look the same.
+4. A requestAnimationFrame loop advances a clock and calls renderFrame(clock). The film loops back to 0 at the end unless it is recording.
+5. A minimal controls overlay OUTSIDE the canvas (so it never appears in a recording): play/pause, restart, a scrub bar with the current time, and a Record button. Autoplay on load when the browser allows it; otherwise show a clear play prompt.
+6. \`window.recordAnimation()\` returns a Promise<Blob>: restart at t=0, capture \`canvas.captureStream(${fps})\` with MediaRecorder (prefer "video/webm;codecs=vp9", fall back to "video/webm"), play exactly ${durationSeconds}s, stop, and resolve the Blob.${audioTrack} The Record button calls it and downloads the result as a .webm file when the page is not embedded (window.parent === window).
+7. postMessage handshake with the embedding host (always target "*"):
+ - once ready: \`parent.postMessage({ type: '${m.ready}', meta: window.ANIMATION_META }, '*')\`
+ - listen for \`{ type: '${m.record}' }\` → run recordAnimation(); while recording post \`{ type: '${m.progress}', t }\` about once per second; on success post \`{ type: '${m.recorded}', blob, mimeType }\`; on failure post \`{ type: '${m.error}', message }\`.${interaction}
+${interactive ? '9' : '8'}. Self-contained: no external scripts, stylesheets, fonts, images, or network requests of any kind; system fonts only. It must run from a sandboxed iframe (scripts allowed, no same-origin) and as a local file.
+${interactive ? '10' : '9'}. Hold ${fps}fps: pre-render static layers and textures to offscreen canvases once, reuse typed arrays, and avoid per-frame allocation.`;
+}
+
+/**
+ * Build the Code Animation prompt.
+ *
+ * @param {object} input
+ * @param {string} [input.title]
+ * @param {string} input.concept - what happens in the film (required upstream)
+ * @param {string} [input.onScreenText] - titles, captions, narration beats
+ * @param {string} [input.styleNotes] - refinements on top of the universe style
+ * @param {{ durationSeconds: number, aspectRatio: string, resolution: string, fps: number }} input.format
+ * @param {'auto'|'canvas2d'|'webgl'|'svg'} [input.renderer]
+ * @param {boolean} [input.interactive]
+ * @param {'none'|'procedural'} [input.soundtrack]
+ * @param {{ name: string, durationSeconds?: number|null, notes?: string }|null} [input.audio]
+ * @param {object|null} [input.universe] - `{ name, embrace, avoid, styleNotes, styleReferences }`
+ * @param {object|null} [input.moodBoard] - `collectBoardStyleContext` output
+ * @param {Array<{ label: string, origin: 'upload'|'universe'|'mood-board', note?: string, path?: string }>} [input.referenceImages]
+ * @param {'copy'|'api'|'cli'} [input.delivery] - how reference images reach the model
+ * @returns {string}
+ */
+export function buildCodeAnimationPrompt({
+ title = '',
+ concept,
+ onScreenText = '',
+ styleNotes = '',
+ format,
+ renderer = 'auto',
+ interactive = false,
+ soundtrack = 'none',
+ audio = null,
+ universe = null,
+ moodBoard = null,
+ referenceImages = [],
+ delivery = 'copy',
+}) {
+ const { width, height } = resolveFrameSize(format.aspectRatio, format.resolution);
+ const { durationSeconds, fps } = format;
+ const sections = [
+ `You are an award-winning creative coder and motion designer. Write ONE complete, self-contained HTML file that renders a ${durationSeconds}-second animated film entirely in code — no image, video, font, or library assets. Every shape, texture, character, and effect is drawn procedurally in the browser, in the art style below, with the craft of a finished title sequence rather than a tech demo.`,
+ `BRIEF${isNonBlankStr(title) ? ` — "${trimTo(title, 200)}"` : ''}:\n${trimTo(concept, CODE_ANIMATION_LIMITS.conceptMax)}`,
+ ];
+ if (isNonBlankStr(onScreenText)) {
+ sections.push(`ON-SCREEN TEXT / NARRATION BEATS (render typography procedurally, timed to the story; system fonts only):\n${trimTo(onScreenText, CODE_ANIMATION_LIMITS.textMax)}`);
+ }
+ sections.push(`ART DIRECTION:\n${artDirectionSection({ universe, styleNotes, hasMoodBoard: !!moodBoard })}`);
+ const boardText = moodBoardSection(moodBoard);
+ if (boardText) sections.push(boardText);
+ const imagesText = referenceImagesSection(referenceImages, delivery);
+ if (imagesText) sections.push(imagesText);
+ sections.push(`SOUND:\n${audioSection({ audio, soundtrack, durationSeconds })}`);
+ sections.push(`FORMAT: ${format.aspectRatio} at ${width}×${height}px, ${fps}fps, ${durationSeconds}s. ${RENDERER_GUIDANCE[renderer] || RENDERER_GUIDANCE.auto}
+Plan the film as a sequence of beats with clear timestamps (establish → develop → climax → resolve) and build smooth transitions between them. Use easing curves, anticipation, overlap, and secondary motion; vary shot scale and camera movement (pan, zoom, parallax) so it feels directed.`);
+ sections.push(runtimeContract({ width, height, fps, durationSeconds, interactive, hasAudio: !!audio }));
+ sections.push(`OUTPUT: Return ONLY the finished HTML document in a single \`\`\`html fenced code block, starting with <!DOCTYPE html>. No explanation before or after it.${delivery === 'cli' ? ' Do not create or edit any files — print the document as your final answer.' : ''}`);
+ return sections.join('\n\n');
+}
+
+/**
+ * Pull the HTML document out of a model response: a ```html fence first, then
+ * any fence holding a document, then a bare `<!DOCTYPE html>…</html>` / `<html…>`
+ * span. Returns null when the response holds no HTML document.
+ */
+export function extractAnimationHtml(text) {
+ if (!isNonBlankStr(text)) return null;
+ const looksLikeDocument = (value) => /<html[\s>]/i.test(value) || /<!doctype html/i.test(value);
+ const fences = [...text.matchAll(/```([a-z]*)[^\n]*\n([\s\S]*?)```/gi)];
+ const htmlFence = fences.find(([, lang, body]) => lang.toLowerCase() === 'html' && looksLikeDocument(body))
+ || fences.find(([, , body]) => looksLikeDocument(body));
+ if (htmlFence) return htmlFence[2].trim();
+ const start = text.search(/<!doctype html|<html[\s>]/i);
+ if (start === -1) return null;
+ const endMatch = text.slice(start).match(/<\/html>/i);
+ const end = endMatch ? start + endMatch.index + endMatch[0].length : text.length;
+ return text.slice(start, end).trim();
+}
diff --git a/server/services/codeAnimation/prompt.test.js b/server/services/codeAnimation/prompt.test.js
new file mode 100644
index 0000000000..4cf1ec4462
--- /dev/null
+++ b/server/services/codeAnimation/prompt.test.js
@@ -0,0 +1,111 @@
+import { describe, expect, it } from 'vitest';
+import {
+ buildCodeAnimationPrompt,
+ extractAnimationHtml,
+ resolveFrameSize,
+ CODE_ANIMATION_AUDIO_GLOBAL,
+ CODE_ANIMATION_MESSAGES,
+} from './prompt.js';
+
+const format = { durationSeconds: 20, aspectRatio: '16:9', resolution: '1080p', fps: 30 };
+
+describe('buildCodeAnimationPrompt', () => {
+ it('makes the universe style the art direction, refined by the per-film notes', () => {
+ const prompt = buildCodeAnimationPrompt({
+ concept: 'A lantern drifts over a sleeping city',
+ styleNotes: 'slower camera, more fog',
+ format,
+ universe: {
+ name: 'Example Universe',
+ embrace: ['ink wash', 'muted indigo'],
+ avoid: ['photorealism'],
+ styleNotes: 'quiet and melancholic',
+ styleReferences: [{ title: 'Night markets', prompt: 'paper lanterns, wet cobblestones' }],
+ },
+ });
+ expect(prompt).toContain('The art style comes from the universe "Example Universe"');
+ expect(prompt).toContain('Visual style to embrace: ink wash, muted indigo');
+ expect(prompt).toContain('Visual style to avoid: photorealism');
+ expect(prompt).toContain('Night markets: paper lanterns, wet cobblestones');
+ expect(prompt).toContain('Refinements for this animation: slower camera, more fog');
+ expect(prompt).not.toContain('No style was specified');
+ });
+
+ it('lets the model choose a style only when nothing configures one', () => {
+ expect(buildCodeAnimationPrompt({ concept: 'x', format })).toContain('No style was specified');
+ const withBoard = buildCodeAnimationPrompt({
+ concept: 'x',
+ format,
+ moodBoard: { name: 'Dusk', description: null, items: [{ kind: 'text', note: 'amber haze' }], droppedItems: 0 },
+ });
+ expect(withBoard).not.toContain('No style was specified');
+ expect(withBoard).toContain('note: amber haze');
+ });
+
+ it('pins the host runtime contract at the resolved frame size', () => {
+ const prompt = buildCodeAnimationPrompt({ concept: 'x', format: { ...format, aspectRatio: '9:16', resolution: '720p', fps: 24 } });
+ expect(prompt).toContain('exactly 720×1280px');
+ expect(prompt).toContain('window.renderFrame(t)');
+ expect(prompt).toContain('canvas.captureStream(24)');
+ for (const type of [CODE_ANIMATION_MESSAGES.ready, CODE_ANIMATION_MESSAGES.record, CODE_ANIMATION_MESSAGES.recorded, CODE_ANIMATION_MESSAGES.error]) {
+ expect(prompt).toContain(type);
+ }
+ });
+
+ it('drives the timeline from a supplied track, and composes one only on request', () => {
+ const withTrack = buildCodeAnimationPrompt({
+ concept: 'x',
+ format,
+ audio: { name: 'theme.mp3', durationSeconds: 31.5, notes: '120 BPM, drop at 0:16' },
+ });
+ expect(withTrack).toContain(`window.${CODE_ANIMATION_AUDIO_GLOBAL}`);
+ expect(withTrack).toContain('"theme.mp3" (31.5s long)');
+ expect(withTrack).toContain('120 BPM, drop at 0:16');
+ expect(withTrack).toContain('MediaStreamAudioDestinationNode');
+
+ expect(buildCodeAnimationPrompt({ concept: 'x', format, soundtrack: 'procedural' })).toContain('procedural soundtrack');
+ expect(buildCodeAnimationPrompt({ concept: 'x', format })).toContain('The animation is silent');
+ });
+
+ it('gives CLI agents on-disk reference paths and keeps them out of a copied prompt', () => {
+ const referenceImages = [{ label: 'hero.png', origin: 'upload', path: '/tmp/example/hero.png', note: 'the silhouette' }];
+ const cli = buildCodeAnimationPrompt({ concept: 'x', format, referenceImages, delivery: 'cli' });
+ expect(cli).toContain('1. hero.png (/tmp/example/hero.png) — the silhouette');
+ expect(cli).toContain('Do not create or edit any files');
+ const copy = buildCodeAnimationPrompt({ concept: 'x', format, referenceImages, delivery: 'copy' });
+ expect(copy).toContain('attached alongside this prompt');
+ expect(copy).not.toContain('/tmp/example/hero.png');
+ });
+});
+
+describe('resolveFrameSize', () => {
+ it('keeps the short side at the resolution and both sides even', () => {
+ expect(resolveFrameSize('16:9', '1080p')).toEqual({ width: 1920, height: 1080 });
+ expect(resolveFrameSize('9:16', '1080p')).toEqual({ width: 1080, height: 1920 });
+ expect(resolveFrameSize('21:9', '720p')).toEqual({ width: 1680, height: 720 });
+ expect(resolveFrameSize('4:5', '1080p')).toEqual({ width: 1080, height: 1350 });
+ });
+});
+
+describe('extractAnimationHtml', () => {
+ const doc = '<!DOCTYPE html>\n<html><body><canvas></canvas></body></html>';
+
+ it.each([
+ ['an html fence with commentary around it', `Here you go:\n\`\`\`html\n${doc}\n\`\`\`\nEnjoy!`],
+ ['an unlabeled fence holding a document', `\`\`\`\n${doc}\n\`\`\``],
+ ['a bare document', `Sure.\n${doc}\nThat is all.`],
+ ])('reads %s', (_label, text) => {
+ expect(extractAnimationHtml(text)).toBe(doc);
+ });
+
+ it('prefers the document fence over an earlier code snippet fence', () => {
+ const text = `Setup:\n\`\`\`js\nconst x = 1;\n\`\`\`\n\`\`\`html\n${doc}\n\`\`\``;
+ expect(extractAnimationHtml(text)).toBe(doc);
+ });
+
+ it('returns null when the response holds no document', () => {
+ expect(extractAnimationHtml('I cannot do that.')).toBeNull();
+ expect(extractAnimationHtml('')).toBeNull();
+ expect(extractAnimationHtml(null)).toBeNull();
+ });
+});
diff --git a/server/services/moodBoard/db.js b/server/services/moodBoard/db.js
index d05d6a6684..dd8ff79afc 100644
--- a/server/services/moodBoard/db.js
+++ b/server/services/moodBoard/db.js
@@ -83,6 +83,15 @@ export async function listBoards({ includeDeleted = false } = {}) {
return result.rows.map(rowToBoard);
}
+/**
+ * Live boards as `{ id, name }`, newest first — for pickers that need only the
+ * label, without reading and shipping every board's items (up to 500 each).
+ */
+export async function listBoardNames() {
+ const result = await query(`SELECT id, data->>'name' AS name FROM mood_boards WHERE deleted = FALSE ORDER BY updated_at DESC`);
+ return result.rows.map((row) => ({ id: row.id, name: row.name || '' }));
+}
+
export async function getBoard(id, { includeDeleted = false } = {}) {
const result = await query(`SELECT data FROM mood_boards WHERE id = $1`, [id]);
const board = rowToBoard(result.rows[0]);
diff --git a/server/services/moodBoard/db.test.js b/server/services/moodBoard/db.test.js
index 55d784efb8..fa2537f768 100644
--- a/server/services/moodBoard/db.test.js
+++ b/server/services/moodBoard/db.test.js
@@ -66,6 +66,13 @@ describe.skipIf(!runDb)('mood board DB round-trip', () => {
// The pool is closed once, by the federation describe's afterAll (runs last).
});
+ it('lists live boards as id + name only', async () => {
+ const board = await db.createBoard({ name: 'Named board' });
+ created.push(board.id);
+ const row = (await db.listBoardNames()).find((b) => b.id === board.id);
+ expect(row).toEqual({ id: board.id, name: 'Named board' });
+ });
+
it('creates, lists, and gets a board (lossless data)', async () => {
const board = await db.createBoard({ name: 'Test board', description: 'd' });
created.push(board.id);
@@ -125,6 +132,7 @@ describe.skipIf(!runDb)('mood board DB round-trip', () => {
expect(await db.getBoard(board.id)).toBeNull();
expect((await db.listBoards()).some((b) => b.id === board.id)).toBe(false);
expect(await db.listBoardIds()).not.toContain(board.id);
+ expect((await db.listBoardNames()).some((b) => b.id === board.id)).toBe(false);
// …but includeDeleted surfaces it with the tombstone trio set.
const tomb = await db.getBoard(board.id, { includeDeleted: true });
expect(tomb).toMatchObject({ deleted: true });
diff --git a/server/services/moodBoard/index.js b/server/services/moodBoard/index.js
index c0f99a6975..f88d69763f 100644
--- a/server/services/moodBoard/index.js
+++ b/server/services/moodBoard/index.js
@@ -26,6 +26,7 @@ export {
listBoards,
getBoard,
listBoardIds,
+ listBoardNames,
mergeBoardsFromSync,
pruneTombstonedBoards,
} from './db.js';
diff --git a/server/services/moodBoard/logic.js b/server/services/moodBoard/logic.js
index d21395b29e..b99b7279e1 100644
--- a/server/services/moodBoard/logic.js
+++ b/server/services/moodBoard/logic.js
@@ -133,6 +133,21 @@ export function imageUrlToAppAsset(imageUrl) {
return null; // some other absolute path → not a served gallery asset
}
+/**
+ * An image item's LOCAL asset as `{ kind: 'image'|'image-ref', filename }` —
+ * from its `image:<file>` media key or an app-path `imageUrl` — or null for
+ * text/video items and external pins. The one rule for "which file on this
+ * install is this pin", for callers that hand board images to a model.
+ */
+export function boardItemLocalImage(item) {
+ if (item?.type !== 'image') return null;
+ if (isStr(item.mediaKey) && item.mediaKey.startsWith('image:')) {
+ const filename = assetBasename(item.mediaKey.slice('image:'.length));
+ return filename ? { kind: 'image', filename } : null;
+ }
+ return imageUrlToAppAsset(item.imageUrl);
+}
+
// Apply a PATCH to board-level fields (name/description). Absent keys preserve
// the original; a present empty string clears (description). `items` is managed
// only through the dedicated item ops below, never a bulk board PATCH.
diff --git a/server/services/moodBoard/styleContext.js b/server/services/moodBoard/styleContext.js
new file mode 100644
index 0000000000..dcf15e2a28
--- /dev/null
+++ b/server/services/moodBoard/styleContext.js
@@ -0,0 +1,71 @@
+/**
+ * Mood board → style-relevant text context (pure).
+ *
+ * Shared by the style synthesis run (`moodBoardStyleSynthesis.js`) and Code
+ * Animation's art direction, and kept dependency-light so a caller that only
+ * needs the board's text fragments doesn't import the provider stack.
+ */
+
+import { trimTo } from '../../lib/textUtils.js';
+
+// Context bounds: a board caps at 500 items, but the synthesis context must
+// stay well inside a chat-completion window. Items are taken in board order
+// (the user's curation order); fragments beyond either cap are dropped and
+// the count is reported in the result so the UI can say so. The aggregate
+// character budget is the load-bearing one — 60 items can each carry four
+// 600-char fields, far past what a small local model's window fits — and it
+// is a FIXED conservative budget (≈6k tokens) rather than model-aware:
+// provider window metadata isn't reliably known here, and a proposal
+// synthesized from the first N curated items beats a request the model
+// truncates or rejects.
+const CONTEXT_ITEMS_MAX = 60;
+const CONTEXT_FIELD_MAX = 600;
+const CONTEXT_TOTAL_CHARS_MAX = 24000;
+
+/**
+ * Reduce a board to the style-relevant text fragments the LLM sees. An item
+ * contributes only what it actually carries: a text note, a caption, and/or a
+ * persisted analysis (prompt + negative + rationale). Media items without any
+ * of those contribute nothing — synthesis reads text, not pixels (analyzing
+ * an item is Phase 3's explicit per-item vision step).
+ */
+export function collectBoardStyleContext(board) {
+ const items = Array.isArray(board?.items) ? board.items : [];
+ const fragments = [];
+ let dropped = 0;
+ let totalChars = 0;
+ for (const it of items) {
+ if (!it || typeof it !== 'object') continue;
+ const entry = {};
+ if (it.type === 'text' && typeof it.text === 'string' && it.text.trim()) {
+ entry.note = trimTo(it.text, CONTEXT_FIELD_MAX);
+ }
+ if (typeof it.caption === 'string' && it.caption.trim()) {
+ entry.caption = trimTo(it.caption, CONTEXT_FIELD_MAX);
+ }
+ const analysis = it.analysis;
+ if (analysis && typeof analysis === 'object' && typeof analysis.prompt === 'string' && analysis.prompt.trim()) {
+ entry.analyzedPrompt = trimTo(analysis.prompt, CONTEXT_FIELD_MAX);
+ if (typeof analysis.negativePrompt === 'string' && analysis.negativePrompt.trim()) {
+ entry.analyzedNegative = trimTo(analysis.negativePrompt, CONTEXT_FIELD_MAX);
+ }
+ if (typeof analysis.rationale === 'string' && analysis.rationale.trim()) {
+ entry.analysisRationale = trimTo(analysis.rationale, CONTEXT_FIELD_MAX);
+ }
+ }
+ if (!Object.keys(entry).length) continue;
+ const entrySize = Object.values(entry).reduce((sum, v) => sum + v.length, 0);
+ if (fragments.length >= CONTEXT_ITEMS_MAX || totalChars + entrySize > CONTEXT_TOTAL_CHARS_MAX) {
+ dropped += 1;
+ continue;
+ }
+ totalChars += entrySize;
+ fragments.push({ kind: it.type, ...entry });
+ }
+ return {
+ name: trimTo(board?.name, 200) || null,
+ description: trimTo(board?.description, 2000) || null,
+ items: fragments,
+ droppedItems: dropped,
+ };
+}
diff --git a/server/services/moodBoard/styleContext.test.js b/server/services/moodBoard/styleContext.test.js
new file mode 100644
index 0000000000..9ce29270a0
--- /dev/null
+++ b/server/services/moodBoard/styleContext.test.js
@@ -0,0 +1,61 @@
+import { describe, expect, it } from 'vitest';
+import { collectBoardStyleContext } from './styleContext.js';
+
+const boardWith = (items) => ({
+ id: 'mb-1',
+ name: 'Universe refs',
+ description: 'Dusty painted sci-fi.',
+ items,
+});
+
+const analyzedItem = {
+ id: 'i1',
+ type: 'image',
+ mediaKey: 'image:ref.png',
+ caption: 'palette anchor',
+ analysis: {
+ prompt: 'a weathered foundry in granular ink wash',
+ negativePrompt: 'gloss, neon',
+ rationale: 'muted, tactile look',
+ analyzedAt: '2026-08-14T00:00:00.000Z',
+ },
+};
+
+describe('collectBoardStyleContext', () => {
+ it('gathers notes, captions, and persisted analyses; skips media items with neither', () => {
+ const ctx = collectBoardStyleContext(boardWith([
+ analyzedItem,
+ { id: 'i2', type: 'text', text: 'lean grim and spiritual', caption: null },
+ { id: 'i3', type: 'video', mediaKey: 'video:clip.mp4', caption: null, analysis: null },
+ ]));
+ expect(ctx.description).toBe('Dusty painted sci-fi.');
+ expect(ctx.items).toHaveLength(2);
+ expect(ctx.items[0]).toMatchObject({
+ kind: 'image',
+ caption: 'palette anchor',
+ analyzedPrompt: expect.stringContaining('granular ink wash'),
+ analyzedNegative: 'gloss, neon',
+ });
+ expect(ctx.items[1]).toMatchObject({ kind: 'text', note: 'lean grim and spiritual' });
+ expect(ctx.droppedItems).toBe(0);
+ });
+
+ it('caps the fragment list and reports the overflow', () => {
+ const many = Array.from({ length: 70 }, (_, i) => ({ id: `t${i}`, type: 'text', text: `note ${i}` }));
+ const ctx = collectBoardStyleContext(boardWith(many));
+ expect(ctx.items).toHaveLength(60);
+ expect(ctx.droppedItems).toBe(10);
+ });
+
+ it('bounds the AGGREGATE character budget, not just the fragment count', () => {
+ // 50 items × ~600 chars each ≈ 30k chars — under the 60-item cap but past
+ // the 24k aggregate budget, so the tail must be dropped.
+ const big = Array.from({ length: 50 }, (_, i) => ({ id: `t${i}`, type: 'text', text: 'x'.repeat(600) }));
+ const ctx = collectBoardStyleContext(boardWith(big));
+ expect(ctx.items.length).toBeLessThan(50);
+ expect(ctx.items.length).toBeGreaterThan(0);
+ expect(ctx.droppedItems).toBe(50 - ctx.items.length);
+ const total = ctx.items.reduce((sum, it) => sum + it.note.length, 0);
+ expect(total).toBeLessThanOrEqual(24000);
+ });
+});
diff --git a/server/services/moodBoardStyleSynthesis.js b/server/services/moodBoardStyleSynthesis.js
index 508fa09241..b20f5f3d4c 100644
--- a/server/services/moodBoardStyleSynthesis.js
+++ b/server/services/moodBoardStyleSynthesis.js
@@ -20,70 +20,10 @@ import {
} from './universeBuilder.js';
import { buildStyleReferenceDiff } from './universeStyleReference.js';
import { trimTo } from '../lib/textUtils.js';
+import { collectBoardStyleContext } from './moodBoard/styleContext.js';
-// Context bounds: a board caps at 500 items, but the synthesis context must
-// stay well inside a chat-completion window. Items are taken in board order
-// (the user's curation order); fragments beyond either cap are dropped and
-// the count is reported in the result so the UI can say so. The aggregate
-// character budget is the load-bearing one — 60 items can each carry four
-// 600-char fields, far past what a small local model's window fits — and it
-// is a FIXED conservative budget (≈6k tokens) rather than model-aware:
-// provider window metadata isn't reliably known here, and a proposal
-// synthesized from the first N curated items beats a request the model
-// truncates or rejects.
-const CONTEXT_ITEMS_MAX = 60;
-const CONTEXT_FIELD_MAX = 600;
-const CONTEXT_TOTAL_CHARS_MAX = 24000;
const RATIONALE_MAX = 1000;
-/**
- * Reduce a board to the style-relevant text fragments the LLM sees. An item
- * contributes only what it actually carries: a text note, a caption, and/or a
- * persisted analysis (prompt + negative + rationale). Media items without any
- * of those contribute nothing — synthesis reads text, not pixels (analyzing
- * an item is Phase 3's explicit per-item vision step).
- */
-export function collectBoardStyleContext(board) {
- const items = Array.isArray(board?.items) ? board.items : [];
- const fragments = [];
- let dropped = 0;
- let totalChars = 0;
- for (const it of items) {
- if (!it || typeof it !== 'object') continue;
- const entry = {};
- if (it.type === 'text' && typeof it.text === 'string' && it.text.trim()) {
- entry.note = trimTo(it.text, CONTEXT_FIELD_MAX);
- }
- if (typeof it.caption === 'string' && it.caption.trim()) {
- entry.caption = trimTo(it.caption, CONTEXT_FIELD_MAX);
- }
- const analysis = it.analysis;
- if (analysis && typeof analysis === 'object' && typeof analysis.prompt === 'string' && analysis.prompt.trim()) {
- entry.analyzedPrompt = trimTo(analysis.prompt, CONTEXT_FIELD_MAX);
- if (typeof analysis.negativePrompt === 'string' && analysis.negativePrompt.trim()) {
- entry.analyzedNegative = trimTo(analysis.negativePrompt, CONTEXT_FIELD_MAX);
- }
- if (typeof analysis.rationale === 'string' && analysis.rationale.trim()) {
- entry.analysisRationale = trimTo(analysis.rationale, CONTEXT_FIELD_MAX);
- }
- }
- if (!Object.keys(entry).length) continue;
- const entrySize = Object.values(entry).reduce((sum, v) => sum + v.length, 0);
- if (fragments.length >= CONTEXT_ITEMS_MAX || totalChars + entrySize > CONTEXT_TOTAL_CHARS_MAX) {
- dropped += 1;
- continue;
- }
- totalChars += entrySize;
- fragments.push({ kind: it.type, ...entry });
- }
- return {
- name: trimTo(board?.name, 200) || null,
- description: trimTo(board?.description, 2000) || null,
- items: fragments,
- droppedItems: dropped,
- };
-}
-
export function buildBoardStyleSynthesisPrompt({ context, styleNotes, influences, locked }) {
const payload = JSON.stringify({
board: context,
@@ -190,4 +130,4 @@ export async function synthesizeBoardStyle({
};
}
-export const __testing = { collectBoardStyleContext, buildBoardStyleSynthesisPrompt };
+export const __testing = { buildBoardStyleSynthesisPrompt };
diff --git a/server/services/moodBoardStyleSynthesis.test.js b/server/services/moodBoardStyleSynthesis.test.js
index c0def3ee23..40a804e1d8 100644
--- a/server/services/moodBoardStyleSynthesis.test.js
+++ b/server/services/moodBoardStyleSynthesis.test.js
@@ -12,7 +12,6 @@ vi.mock('./promptRunner.js', async (importActual) => {
const aiProvider = await import('./aiProvider.js');
const promptRunner = await import('./promptRunner.js');
const {
- collectBoardStyleContext,
buildBoardStyleSynthesisPrompt,
synthesizeBoardStyle,
} = await import('./moodBoardStyleSynthesis.js');
@@ -53,45 +52,6 @@ beforeEach(() => {
promptRunner.runPromptThroughProvider.mockResolvedValue({ text: synthesisText, model: 'qwen' });
});
-describe('collectBoardStyleContext', () => {
- it('gathers notes, captions, and persisted analyses; skips media items with neither', () => {
- const ctx = collectBoardStyleContext(boardWith([
- analyzedItem,
- { id: 'i2', type: 'text', text: 'lean grim and spiritual', caption: null },
- { id: 'i3', type: 'video', mediaKey: 'video:clip.mp4', caption: null, analysis: null },
- ]));
- expect(ctx.description).toBe('Dusty painted sci-fi.');
- expect(ctx.items).toHaveLength(2);
- expect(ctx.items[0]).toMatchObject({
- kind: 'image',
- caption: 'palette anchor',
- analyzedPrompt: expect.stringContaining('granular ink wash'),
- analyzedNegative: 'gloss, neon',
- });
- expect(ctx.items[1]).toMatchObject({ kind: 'text', note: 'lean grim and spiritual' });
- expect(ctx.droppedItems).toBe(0);
- });
-
- it('caps the fragment list and reports the overflow', () => {
- const many = Array.from({ length: 70 }, (_, i) => ({ id: `t${i}`, type: 'text', text: `note ${i}` }));
- const ctx = collectBoardStyleContext(boardWith(many));
- expect(ctx.items).toHaveLength(60);
- expect(ctx.droppedItems).toBe(10);
- });
-
- it('bounds the AGGREGATE character budget, not just the fragment count', () => {
- // 50 items × ~600 chars each ≈ 30k chars — under the 60-item cap but past
- // the 24k aggregate budget, so the tail must be dropped.
- const big = Array.from({ length: 50 }, (_, i) => ({ id: `t${i}`, type: 'text', text: 'x'.repeat(600) }));
- const ctx = collectBoardStyleContext(boardWith(big));
- expect(ctx.items.length).toBeLessThan(50);
- expect(ctx.items.length).toBeGreaterThan(0);
- expect(ctx.droppedItems).toBe(50 - ctx.items.length);
- const total = ctx.items.reduce((sum, it) => sum + it.note.length, 0);
- expect(total).toBeLessThanOrEqual(24000);
- });
-});
-
describe('synthesizeBoardStyle', () => {
it('400s a board with no synthesizable content', async () => {
await expect(synthesizeBoardStyle({