Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat(code-animation): frame-exact MP4 export through the composition renderer (#9078)
[._.]/ Adam Eivy39284f391d13
diff --git a/client/src/components/codeAnimation/CodeAnimationPreview.jsx b/client/src/components/codeAnimation/CodeAnimationPreview.jsxindex 222ee61388..b421d77aab 100644--- a/client/src/components/codeAnimation/CodeAnimationPreview.jsx+++ b/client/src/components/codeAnimation/CodeAnimationPreview.jsx@@ -1,8 +1,9 @@import { useEffect, useMemo, useRef, useState } from 'react';-import { Circle, Download, FileCode2, LoaderCircle, Save } from 'lucide-react';+import { Circle, Clapperboard, Download, FileCode2, LoaderCircle, Save } from 'lucide-react';import { Link } from 'react-router';import toast from '../ui/Toast';-import { uploadGalleryVideo } from '../../services/api';+import { cancelCodeAnimationExport, exportCodeAnimation, uploadGalleryVideo } from '../../services/api';+import { useSseProgress } from '../../hooks/useSseProgress';import { downloadBlob } from '../../lib/downloadBlob';// Seconds past the film's own duration before a silent recording is abandoned@@ -66,7 +67,7 @@ const blobToDataUrl = (blob) => new Promise((resolve, reject) => {* 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 }) {+export default function CodeAnimationPreview({ html, audioUrl, messages, audioGlobal, frame, title, jobId }) {const iframeRef = useRef(null);// A generated page receives the selected track only after an explicit choice.// Tie that choice to the URL so a changed track needs fresh consent.@@ -85,6 +86,24 @@ export default function CodeAnimationPreview({ html, audioUrl, messages, audioGlconst [video, setVideo] = useState(null);const [saving, setSaving] = useState(false);const recordTimerRef = useRef(null);+ // Frame-exact export runs server-side on the media queue; its progress and+ // result stream from the composition job's SSE channel.+ const [exportJob, setExportJob] = useState(null);+ const [exportStarting, setExportStarting] = useState(false);+ const exportUrl = exportJob ? `/api/html-composition/${encodeURIComponent(exportJob)}/events` : null;+ const { latest: exportFrame } = useSseProgress(exportUrl, { enabled: !!exportUrl });+ const exportResult = exportFrame?.type === 'complete' ? exportFrame.result : null;+ const exportError = exportFrame?.type === 'error' ? exportFrame.error : null;+ const exporting = !!exportJob && !exportResult && !exportError && exportFrame?.type !== 'canceled';+ const exportPercent = exportFrame?.type === 'progress' ? Math.round((exportFrame.progress || 0) * 100) : 0;++ useEffect(() => {+ if (exportError) toast.error(`Export failed: ${String(exportError).slice(0, 300)}`);+ }, [exportError]);++ useEffect(() => {+ setExportJob(null);+ }, [jobId]);useEffect(() => {let active = true;@@ -176,6 +195,19 @@ export default function CodeAnimationPreview({ html, audioUrl, messages, audioGl}, (duration + RECORD_GRACE_SECONDS) * 1_000);};+ const handleExport = async () => {+ if (!jobId || exporting || exportStarting) return;+ setExportStarting(true);+ const queued = await exportCodeAnimation(jobId, { silent: true }).catch((error) => {+ toast.error(error.message || 'Failed to start the export');+ return null;+ });+ setExportStarting(false);+ if (!queued?.jobId) return;+ for (const note of queued.notes || []) toast(note);+ setExportJob(queued.jobId);+ };+const handleSave = async () => {if (!video || video.saved || saving) return;setSaving(true);@@ -247,8 +279,29 @@ export default function CodeAnimationPreview({ html, audioUrl, messages, audioGlclassName="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'}+ {recording ? `Recording ${Math.floor(recordProgress)}s / ${Math.round(duration)}s` : 'Record (real-time)'}</button>+ {jobId && (+ <button+ type="button"+ onClick={handleExport}+ disabled={exporting || exportStarting}+ title="Render every frame server-side through renderFrame(t) — no dropped frames, H.264 MP4 in Media History"+ className={BUTTON_PRIMARY}+ >+ {exporting || exportStarting ? <LoaderCircle className="h-4 w-4 animate-spin" /> : <Clapperboard className="h-4 w-4" />}+ {exporting ? `Exporting ${exportPercent}%` : 'Export MP4 (frame-exact)'}+ </button>+ )}+ {exporting && (+ <button+ type="button"+ onClick={() => cancelCodeAnimationExport(exportJob, { silent: true }).catch((error) => toast.error(error.message || 'Failed to cancel the export'))}+ className={BUTTON_SECONDARY}+ >+ Cancel export+ </button>+ )}<buttontype="button"onClick={() => downloadBlob(html, `${fileBase}.html`, 'text/html')}@@ -262,6 +315,18 @@ export default function CodeAnimationPreview({ html, audioUrl, messages, audioGl</span></div>+ {exportResult?.path && (+ <div className="space-y-2 rounded-lg border border-port-border bg-port-card p-3">+ <video src={exportResult.path} controls className="max-h-80 w-full rounded bg-black" aria-label="Exported animation" />+ <div className="flex flex-wrap items-center gap-2">+ <a href={exportResult.path} download={`${fileBase}.mp4`} className={BUTTON_SECONDARY}>+ <Download className="h-4 w-4" /> Download MP4+ </a>+ <Link to="/media/history" className="text-xs text-port-accent hover:underline">Saved to Media History</Link>+ </div>+ </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" />diff --git a/client/src/components/codeAnimation/CodeAnimationPreview.test.jsx b/client/src/components/codeAnimation/CodeAnimationPreview.test.jsxindex 648f53f23f..cc97f1d604 100644--- a/client/src/components/codeAnimation/CodeAnimationPreview.test.jsx+++ b/client/src/components/codeAnimation/CodeAnimationPreview.test.jsx@@ -3,16 +3,19 @@ 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() }));+vi.mock('../../services/api', () => ({ uploadGalleryVideo: vi.fn(), exportCodeAnimation: vi.fn(), cancelCodeAnimationExport: vi.fn() }));+vi.mock('../../hooks/useSseProgress', () => ({ useSseProgress: vi.fn(() => ({ latest: null })) }));import CodeAnimationPreview, { prepareAnimationHtml } from './CodeAnimationPreview';+import { exportCodeAnimation } from '../../services/api';+import { useSseProgress } from '../../hooks/useSseProgress';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 = ({ audioUrl = null } = {}) => render(+const renderPreview = ({ audioUrl = null, jobId } = {}) => render(<MemoryRouter>- <CodeAnimationPreview html={HTML} audioUrl={audioUrl} messages={MESSAGES} audioGlobal="ANIMATION_AUDIO_URL" frame={{ width: 1920, height: 1080, durationSeconds: 5 }} title="Lantern" />+ <CodeAnimationPreview html={HTML} audioUrl={audioUrl} messages={MESSAGES} audioGlobal="ANIMATION_AUDIO_URL" frame={{ width: 1920, height: 1080, durationSeconds: 5 }} title="Lantern" jobId={jobId} /></MemoryRouter>,);@@ -64,7 +67,7 @@ describe('CodeAnimationPreview', () => {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 }));+ await user.click(screen.getByRole('button', { name: /record \(real-time\)/i }));expect(postMessage).toHaveBeenCalledWith({ type: MESSAGES.record }, '*');// A message from any other window is ignored.@@ -106,3 +109,17 @@ describe('CodeAnimationPreview', () => {expect(frame.getAttribute('srcdoc')).not.toContain('ANIMATION_AUDIO_URL');});});++describe('CodeAnimationPreview frame-exact export', () => {+ it('offers export only for a saved job, queues it, and follows the composition job stream', async () => {+ const user = userEvent.setup();+ exportCodeAnimation.mockResolvedValue({ jobId: 'media-1', notes: [] });+ const { unmount } = renderPreview();+ expect(screen.queryByRole('button', { name: /export mp4/i })).toBeNull();+ unmount();+ renderPreview({ jobId: 'job-1' });+ await user.click(screen.getByRole('button', { name: /export mp4/i }));+ expect(exportCodeAnimation).toHaveBeenCalledWith('job-1', { silent: true });+ expect(useSseProgress).toHaveBeenLastCalledWith('/api/html-composition/media-1/events', { enabled: true });+ });+});diff --git a/client/src/pages/CodeAnimation.jsx b/client/src/pages/CodeAnimation.jsxindex 1d42407c6d..1311cf909a 100644--- a/client/src/pages/CodeAnimation.jsx+++ b/client/src/pages/CodeAnimation.jsx@@ -375,7 +375,7 @@ export default function CodeAnimation() {if (!next) return;const requested = jobId;setJob(next);- if (next.status === 'completed' && next.html) setPreview({ html: next.html, audioUrl: next.audioUrl, frame: next.frame });+ if (next.status === 'completed' && next.html) setPreview({ html: next.html, audioUrl: next.audioUrl, frame: next.frame, jobId: next.id });else setPreview(null);if (next.status !== 'missing') {setSavedJobs((previous) => [galleryJob(next), ...previous.filter((item) => item.id !== requested)]@@ -842,6 +842,7 @@ export default function CodeAnimation() {html={preview.html}audioUrl={preview.audioUrl}frame={preview.frame}+ jobId={preview.jobId}messages={options.messages}audioGlobal={options.audioGlobal}title={draft.title || draft.concept.slice(0, 40)}diff --git a/client/src/services/apiCodeAnimation.js b/client/src/services/apiCodeAnimation.jsindex 303d12f29e..14e9562501 100644--- a/client/src/services/apiCodeAnimation.js+++ b/client/src/services/apiCodeAnimation.js@@ -32,3 +32,16 @@ export const listCodeAnimationJobPage = ({ cursor, signal, limit = 50 } = {}) =>export const getCodeAnimationJob = (id, options) =>request(`/code-animation/generate/${encodeURIComponent(id)}`, options);++// Queue a frame-exact MP4 export; returns { jobId, notes }. Progress streams+// from /api/html-composition/:jobId/events.+export const exportCodeAnimation = (id, options) => request(`/code-animation/${encodeURIComponent(id)}/export`, {+ method: 'POST',+ ...options,+});++// Cancel a queued/running export; the renderer removes its partial output.+export const cancelCodeAnimationExport = (exportJobId, options) => request(`/html-composition/${encodeURIComponent(exportJobId)}/cancel`, {+ method: 'POST',+ ...options,+});diff --git a/docs/API.md b/docs/API.mdindex 87d6cf4434..9fec179084 100644--- a/docs/API.md+++ b/docs/API.md@@ -768,7 +768,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: LLM-written briefs, prompt building, persistent jobs gallery, and generated HTML retrieval |+| `/api/code-animation` | Code Animation: LLM-written briefs, prompt building, persistent jobs gallery, generated HTML retrieval, and frame-exact MP4 export (`POST /:id/export` → HTML-composition media job) || `/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/docs/HTML_COMPOSITIONS.md b/docs/HTML_COMPOSITIONS.mdindex a1d5904cc4..67e3f32844 100644--- a/docs/HTML_COMPOSITIONS.md+++ b/docs/HTML_COMPOSITIONS.md@@ -119,7 +119,7 @@ launch-video artifacts are delivered. The completed job's result carriesrelative to the data directory (never an absolute host path) and `url` servesit under `/data/`; tile *n* shows `times[n]`.Launch runs write `proofs/contact-<jobId>.png` beside the run; other-compositions write `data/composition-proofs/`. Both are excluded from backups.+compositions write `data/composition-proofs/`. Both are excluded from backups. Code Animation exports stage `data/code-animation-exports/<job-id>/` (also excluded): the stored HTML with a shim that maps `ANIMATION_META`/`renderFrame(t)` onto `portosComposition`, stops the page's own `requestAnimationFrame` clock, and hides everything but the film canvas.The 202 response contains the media queue's `jobId`. Subscribe to`GET /api/html-composition/:jobId/events` for the usual queued, started, progress,diff --git a/server/routes/codeAnimation.js b/server/routes/codeAnimation.jsindex 55b4d25917..ecbc654c65 100644--- a/server/routes/codeAnimation.js+++ b/server/routes/codeAnimation.js@@ -8,6 +8,7 @@* POST /api/code-animation/generate start a provider run → 202 job* GET /api/code-animation/jobs list saved jobs for the gallery* GET /api/code-animation/generate/:id poll a job (html once completed)+ * POST /api/code-animation/:id/export queue a frame-exact MP4 render → 202 media job*/import { Router } from 'express';@@ -25,6 +26,7 @@ import {getCodeAnimationOptions,startCodeAnimationGeneration,} from '../services/codeAnimation/index.js';+import { startCodeAnimationExport } from '../services/codeAnimation/export.js';import {CODE_ANIMATION_ASPECT_RATIOS,CODE_ANIMATION_LIMITS,@@ -154,4 +156,14 @@ router.get('/generate/:id', asyncHandler(async (req, res) => {res.json(job);}));+const exportParamsSchema = z.object({ id: z.string().uuid() }).strict();++// Frame-exact export: the stored HTML renders through the HTML-composition+// pipeline (seek each frame, H.264 MP4, Media History) on the media queue.+// Progress streams from /api/html-composition/:jobId/events.+router.post('/:id/export', asyncHandler(async (req, res) => {+ const { id } = validateRequest(exportParamsSchema, req.params);+ res.status(202).json(await startCodeAnimationExport(id));+}));+export default router;diff --git a/server/services/backup.js b/server/services/backup.jsindex 26267051c0..ada6810dd3 100644--- a/server/services/backup.js+++ b/server/services/backup.js@@ -171,6 +171,7 @@ export const DEFAULT_EXCLUDES = [{ path: '/cos/reference-repos/', reason: 'Reference upstream repos used by agents — re-cloneable', overridable: true },{ path: '/browser-downloads/', reason: 'Browser downloads cache — large, re-downloadable', overridable: true },{ path: '/composition-proofs/', reason: 'HTML-composition contact-sheet proofs — review stills, re-rendered from the composition source', overridable: true },+ { path: '/code-animation-exports/', reason: 'Code Animation frame-exact export staging — the stored HTML plus render shim, rebuilt on every export', overridable: true },{ path: '/music-video-compositions/', reason: 'In-flight music-video typography overlay scratch — removed when its render ends and swept at boot', overridable: false },{ path: '/launch-videos/*/*/proofs/', reason: 'Launch-video critique-loop contact sheets — re-rendered from the run composition', overridable: true },{ path: '/cache/', reason: 'Remote-API metadata and licensed reading caches — regenerable on demand, and stale on restore anyway', overridable: false },diff --git a/server/services/codeAnimation/export.js b/server/services/codeAnimation/export.jsnew file mode 100644index 0000000000..5432378cf6--- /dev/null+++ b/server/services/codeAnimation/export.js@@ -0,0 +1,127 @@+/**+ * Frame-exact MP4 export for a generated Code Animation (#9078).+ *+ * Real-time recording (MediaRecorder in the user's tab) drops frames whenever+ * renderFrame(t) takes longer than 1/fps. This export instead hands the stored+ * HTML to the HTML-composition renderer, which seeks every frame's time in the+ * managed browser, screenshots it, and encodes H.264/BT.709 through the media+ * queue — so a slow frame costs wall time, never a frame.+ *+ * The bridge is a shim injected before the page's own scripts: it defines+ * `portosComposition` from ANIMATION_META + renderFrame, stops the page's own+ * requestAnimationFrame clock, and hides everything but the film canvas.+ */++import { join } from 'path';+import { mkdir, rm } from 'fs/promises';+import { ServerError } from '../../lib/errorHandler.js';+import { PATHS } from '../../lib/paths.js';+import { atomicWrite } from '../../lib/fileUtils.js';+import { getCodeAnimationJobRecord, isCodeAnimationJobId, readCodeAnimationHtml } from './jobStore.js';+import { CODE_ANIMATION_SONG_GLOBAL } from './prompt.js';++// The frames the composition renderer accepts (htmlCompositionContractSchema).+export const EXPORT_FRAME_SIZES = Object.freeze(['1920x1080', '1080x1920', '1080x1080', '1280x720']);+// The composition renderer's duration cap; longer films export their first 120s.+export const EXPORT_MAX_DURATION_SEC = 120;+export const EXPORT_DIRECTORY_ROOT = 'code-animation-exports';++const scriptLiteral = (value) => JSON.stringify(value).replace(/</g, '\\u003c');++/**+ * The shim script, run before any page script. `song` is the measured beat+ * grid of the attached Music-library track (or null), exposed as+ * window.ANIMATION_SONG (CODE_ANIMATION_SONG_GLOBAL) so audio-reactive films can stay a function of t.+ */+export function buildExportShim({ maxDurationSec = EXPORT_MAX_DURATION_SEC, song = null } = {}) {+ return `(() => {+ const nativeRaf = window.requestAnimationFrame.bind(window);+ ${song ? `window[${scriptLiteral(CODE_ANIMATION_SONG_GLOBAL)}] = ${scriptLiteral(song)};` : ''}+ // The renderer owns the clock: the page's own rAF loop never runs.+ window.requestAnimationFrame = () => 0;+ window.cancelAnimationFrame = () => {};+ let film = null;+ const hideAllButFilm = () => {+ const canvases = [...document.querySelectorAll('canvas')];+ film = canvases.sort((a, b) => (b.width * b.height) - (a.width * a.height))[0] || null;+ if (!film) return;+ film.setAttribute('data-portos-film', '');+ const style = document.createElement('style');+ style.textContent = 'html,body{background:#000!important;margin:0!important;overflow:hidden!important}'+ + 'body *{visibility:hidden!important}'+ + 'canvas[data-portos-film]{visibility:visible!important;position:fixed!important;left:0!important;top:0!important;'+ + 'width:100vw!important;height:100vh!important;transform:none!important;margin:0!important;z-index:2147483647!important}';+ document.head.appendChild(style);+ };+ addEventListener('load', hideAllButFilm, { once: true });+ Object.defineProperty(globalThis, 'portosComposition', { configurable: false, get() {+ if (typeof window.renderFrame !== 'function') {+ throw new Error('This animation does not define window.renderFrame(t), so it cannot export frame-exact — use Record (real-time) instead');+ }+ const meta = window.ANIMATION_META || {};+ if (!film) throw new Error('This animation has no <canvas> to export');+ return {+ durationSec: Math.min(Number(meta.duration), ${Number(maxDurationSec)}),+ fps: Number(meta.fps),+ width: Number(meta.width),+ height: Number(meta.height),+ // Each seek resolves after the next paint so the screenshot holds frame t.+ seek: async (t) => { await window.renderFrame(t); await new Promise((resolve) => nativeRaf(() => resolve())); },+ };+ } });+})();`;+}++/** The stored HTML with the shim inserted as the first script of the document. */+export function injectExportShim(html, shim) {+ const tag = `<script>${shim}</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)}`;+}++// Only a Music-library track can be muxed; `/data/music/<file>` is the URL the+// job stored for it.+function musicTrackOf(job) {+ const match = /^\/data\/music\/([^/]+)$/.exec(job.audioUrl || '');+ return match ? decodeURIComponent(match[1]) : null;+}++/**+ * Validate a completed job, stage its HTML + shim under data/, and enqueue the+ * composition render. Returns the queued media job plus any export notes.+ */+export async function startCodeAnimationExport(id, deps = {}) {+ const {+ enqueueJob = (await import('../mediaJobQueue/index.js')).enqueueJob,+ beatGrid = async (track) => {+ const [{ resolveMusicTrackPath }, { getBeatGrid }] = await Promise.all([import('../pipeline/audioMux.js'), import('../../lib/beatGrid.js')]);+ const path = await resolveMusicTrackPath(track);+ if (!path) throw new ServerError('The animation\'s soundtrack is missing from the Music library', { status: 400, code: 'AUDIO_NOT_FOUND' });+ return getBeatGrid(path).catch(() => null);+ },+ } = deps;+ const job = isCodeAnimationJobId(id) ? await getCodeAnimationJobRecord(id) : null;+ if (!job) throw new ServerError('Code Animation job not found', { status: 404, code: 'NOT_FOUND' });+ if (job.status !== 'completed') throw new ServerError('Only a completed animation can be exported', { status: 409, code: 'NOT_COMPLETED' });+ const { width, height, durationSeconds } = job.frame || {};+ if (!EXPORT_FRAME_SIZES.includes(`${width}x${height}`)) {+ throw new ServerError(`Frame-exact export supports ${EXPORT_FRAME_SIZES.join(', ')}; this animation is ${width}x${height} — use Record (real-time) instead`, { status: 400, code: 'EXPORT_SIZE_UNSUPPORTED' });+ }+ const html = await readCodeAnimationHtml(id);+ const musicTrack = musicTrackOf(job);+ const notes = [];+ if (job.audioUrl && !musicTrack) notes.push('Uploaded audio is not muxed; the export is silent. Attach a Music-library track to include it.');+ if (durationSeconds > EXPORT_MAX_DURATION_SEC) notes.push(`The export is capped at ${EXPORT_MAX_DURATION_SEC}s; this animation runs ${durationSeconds}s.`);+ const song = musicTrack ? await beatGrid(musicTrack) : null;+ const directory = `${EXPORT_DIRECTORY_ROOT}/${id}`;+ const dir = join(PATHS.data, directory);+ // Re-stage from scratch so a stale asset from an earlier export never rides along.+ await rm(dir, { recursive: true, force: true });+ await mkdir(dir, { recursive: true });+ await atomicWrite(join(dir, 'index.html'), injectExportShim(html, buildExportShim({ song })));+ const queued = await enqueueJob({ kind: 'html-composition', params: { directory, ...(musicTrack ? { musicTrack } : {}) } });+ console.log(`🎬 Code animation ${id.slice(0, 8)} frame-exact export queued as ${queued.jobId}`);+ return { ...queued, notes };+}diff --git a/server/services/codeAnimation/export.test.js b/server/services/codeAnimation/export.test.jsnew file mode 100644index 0000000000..2f3a79e61d--- /dev/null+++ b/server/services/codeAnimation/export.test.js@@ -0,0 +1,108 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { mkdtemp, readFile, rm } from 'fs/promises';+import { tmpdir } from 'os';+import { join } from 'path';+import vm from 'vm';++const state = vi.hoisted(() => ({ dataRoot: null, job: null, html: '' }));++vi.mock('../../lib/paths.js', async () => {+ const actual = await vi.importActual('../../lib/paths.js');+ return { ...actual, PATHS: new Proxy(actual.PATHS, { get: (target, prop) => (prop === 'data' ? state.dataRoot : target[prop]) }) };+});+vi.mock('./jobStore.js', () => ({+ isCodeAnimationJobId: (id) => /^[0-9a-f-]{36}$/.test(id),+ getCodeAnimationJobRecord: async () => state.job,+ readCodeAnimationHtml: async () => state.html,+}));++const { buildExportShim, startCodeAnimationExport } = await import('./export.js');++const JOB_ID = '11111111-2222-4333-8444-555555555555';++// Run the shim, then a page script, in a minimal browser-like realm.+function runPage(pageScript, { song } = {}) {+ const listeners = {};+ const canvas = { width: 1920, height: 1080, setAttribute: vi.fn() };+ const ctx = {+ requestAnimationFrame: (callback) => { callback(0); return 1; },+ cancelAnimationFrame: () => {},+ addEventListener: (type, fn) => { listeners[type] = fn; },+ document: {+ querySelectorAll: () => [canvas],+ createElement: () => ({}),+ head: { appendChild: vi.fn() },+ },+ };+ ctx.window = ctx;+ ctx.globalThis = ctx;+ vm.createContext(ctx);+ vm.runInContext(buildExportShim({ song }), ctx);+ vm.runInContext(pageScript, ctx);+ listeners.load?.();+ return { ctx, canvas };+}++describe('buildExportShim', () => {+ it('stops the page clock and exposes renderFrame as a clamped composition seek', async () => {+ const { ctx, canvas } = runPage(`+ window.drawn = [];+ window.ticks = 0;+ window.ANIMATION_META = { duration: 180, fps: 30, width: 1920, height: 1080 };+ window.renderFrame = (t) => { window.drawn.push(t); };+ requestAnimationFrame(() => { window.ticks += 1; });+ `, { song: { bpm: 120, beats: [0.5], downbeats: [], hits: [] } });+ expect(ctx.ticks).toBe(0);+ expect(canvas.setAttribute).toHaveBeenCalledWith('data-portos-film', '');+ expect(ctx.ANIMATION_SONG.bpm).toBe(120);+ const composition = ctx.portosComposition;+ expect(composition).toMatchObject({ durationSec: 120, fps: 30, width: 1920, height: 1080 });+ await composition.seek(2.5);+ expect(ctx.drawn).toEqual([2.5]);+ });++ it('names the reason when the animation has no renderFrame', () => {+ const { ctx } = runPage('window.ANIMATION_META = { duration: 5, fps: 30, width: 1920, height: 1080 };');+ expect(() => ctx.portosComposition).toThrow(/does not define window\.renderFrame\(t\).*Record \(real-time\)/);+ });+});++describe('startCodeAnimationExport', () => {+ let enqueueJob;+ beforeEach(async () => {+ state.dataRoot = await mkdtemp(join(tmpdir(), 'code-animation-export-'));+ state.html = '<!DOCTYPE html><html><head><title>x</title></head><body><script>window.renderFrame=()=>{}</script></body></html>';+ state.job = { id: JOB_ID, status: 'completed', frame: { width: 1920, height: 1080, fps: 30, durationSeconds: 20 }, audioUrl: '/data/music/Song%20A.mp3' };+ enqueueJob = vi.fn(async () => ({ jobId: 'media-1', position: 1, status: 'queued' }));+ });+ afterEach(async () => {+ await rm(state.dataRoot, { recursive: true, force: true });+ });++ it('stages the HTML with the shim ahead of page scripts and queues a composition render with the library track', async () => {+ const beatGrid = vi.fn(async () => ({ bpm: 100, beats: [0.6], downbeats: [0.6], hits: [] }));+ const result = await startCodeAnimationExport(JOB_ID, { enqueueJob, beatGrid });+ expect(result).toMatchObject({ jobId: 'media-1', notes: [] });+ expect(beatGrid).toHaveBeenCalledWith('Song A.mp3');+ expect(enqueueJob).toHaveBeenCalledWith({ kind: 'html-composition',+ params: { directory: `code-animation-exports/${JOB_ID}`, musicTrack: 'Song A.mp3' } });+ const staged = await readFile(join(state.dataRoot, 'code-animation-exports', JOB_ID, 'index.html'), 'utf8');+ expect(staged.indexOf('portosComposition')).toBeLessThan(staged.indexOf('window.renderFrame=()=>{}'));+ expect(staged).toContain('"bpm":100');+ });++ it('exports uploaded-audio and over-long films with explanatory notes', async () => {+ state.job = { ...state.job, audioUrl: '/api/uploads/take.wav', frame: { ...state.job.frame, durationSeconds: 180 } };+ const result = await startCodeAnimationExport(JOB_ID, { enqueueJob, beatGrid: vi.fn() });+ expect(result.notes).toHaveLength(2);+ expect(enqueueJob.mock.calls[0][0].params).toEqual({ directory: `code-animation-exports/${JOB_ID}` });+ });++ it('refuses frame sizes the composition renderer cannot encode and unfinished jobs', async () => {+ state.job = { ...state.job, frame: { ...state.job.frame, width: 1440, height: 1080 } };+ await expect(startCodeAnimationExport(JOB_ID, { enqueueJob })).rejects.toMatchObject({ code: 'EXPORT_SIZE_UNSUPPORTED' });+ state.job = { ...state.job, status: 'running' };+ await expect(startCodeAnimationExport(JOB_ID, { enqueueJob })).rejects.toMatchObject({ code: 'NOT_COMPLETED' });+ expect(enqueueJob).not.toHaveBeenCalled();+ });+});diff --git a/server/services/codeAnimation/prompt.js b/server/services/codeAnimation/prompt.jsindex a50b00273e..3bdc945b7a 100644--- a/server/services/codeAnimation/prompt.js+++ b/server/services/codeAnimation/prompt.js@@ -41,6 +41,11 @@ export const CODE_ANIMATION_MESSAGES = Object.freeze({// URL. Absent when the user supplied no audio or opened the file standalone.export const CODE_ANIMATION_AUDIO_GLOBAL = 'ANIMATION_AUDIO_URL';+// The global the frame-exact exporter sets to the soundtrack's measured beat+// grid ({ bpm, beats, downbeats, hits } — seconds), so audio-reactive motion+// can be a pure function of t with no live playback (#9078).+export const CODE_ANIMATION_SONG_GLOBAL = 'ANIMATION_SONG';+export const CODE_ANIMATION_ASPECT_RATIOS = Object.freeze({'16:9': { width: 16, height: 9 },'9:16': { width: 9, height: 16 },@@ -138,7 +143,8 @@ function audioSection({ audio, soundtrack, durationSeconds }) {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.',+ '- While audio plays, the timeline clock IS `audio.currentTime` so picture and sound never drift.',+ `- Make the picture dance from PRECOMPUTED song data as a function of t: when \`window.${CODE_ANIMATION_SONG_GLOBAL}\` is set (\`{ bpm, beats, downbeats, hits }\`, every entry a time in seconds; bpm may be null) derive pulses, cuts, scale, and color from the nearest beats/downbeats/hits before and after t. The frame-exact MP4 export renders renderFrame(t) with NO audio playing, so a live analyser reads silence there. Use the AnalyserNode's bass / mid / treble energy only as a preview fallback when \`window.${CODE_ANIMATION_SONG_GLOBAL}\` is absent.`,`- 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.`,);@@ -206,7 +212,7 @@ function runtimeContract({ width, height, fps, durationSeconds, interactive, hasreturn `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.+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 (audio-reactive values from the precomputed song data, never only from live playback). Scrubbing to the same t twice must look the same. PortOS exports the film frame-exactly by calling renderFrame(t) once per frame with its own clock, so renderFrame must fully draw frame t on its own, even when called out of order or slower than real time.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; when embedded (window.parent !== window) it posts the result to the host exactly as item 7 does, otherwise it downloads the result as a .webm file.