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: give Code Animation its own Gallery tab with poster thumbnails
[._.]/ Adam Eivy8dbf2f5ca8e9
diff --git a/client/src/App.jsx b/client/src/App.jsxindex 84334b7cb7..d0b1c52e7a 100644--- a/client/src/App.jsx+++ b/client/src/App.jsx@@ -624,6 +624,7 @@ export default function App() {<Route path="objects" element={<CreativeLibrary key="objects" libraryId="objects" />} /><Route path="objects/:id/:tab?" element={<CatalogIngredient />} /><Route path="code-animation" element={<CodeAnimation />} />+ <Route path="code-animation/gallery" element={<CodeAnimation />} /><Route path="code-animation/:jobId" element={<CodeAnimation />} /><Route path="code-animation/production" element={<CodeAnimation />} /><Route path="code-animation/production/:projectId" element={<CodeAnimation />} />diff --git a/client/src/components/codeAnimation/CodeAnimationGallery.jsx b/client/src/components/codeAnimation/CodeAnimationGallery.jsxnew file mode 100644index 0000000000..29cb593d6c--- /dev/null+++ b/client/src/components/codeAnimation/CodeAnimationGallery.jsx@@ -0,0 +1,133 @@+import { useCallback, useEffect, useRef, useState } from 'react';+import { AlertTriangle, CheckCircle2, Clock3, FileCode2, ImageOff, LoaderCircle, Sparkles } from 'lucide-react';+import { Link } from 'react-router';+import useMounted from '../../hooks/useMounted';+import { usePagedCollection } from '../../hooks/usePagedCollection';+import { useSocketSubscription } from '../../hooks/useSocketSubscription';+import socket from '../../services/socket';+import { codeAnimationPosterUrl, listCodeAnimationJobPage, requestCodeAnimationPoster } from '../../services/api';+import { formatCount, timeAgo } from '../../utils/formatters';+import InfiniteScrollFooter from '../ui/InfiniteScrollFooter';++const STATUS = {+ running: { icon: Clock3, label: 'In progress', tone: 'text-port-accent' },+ completed: { icon: CheckCircle2, label: 'Completed', tone: 'text-port-success' },+ failed: { icon: AlertTriangle, label: 'Failed', tone: 'text-port-error' },+};++function PosterPlaceholder({ item, capturing }) {+ if (item.status === 'running') {+ return <LoaderCircle className="h-8 w-8 animate-spin text-port-accent" aria-hidden="true" />;+ }+ if (item.status === 'failed') return <AlertTriangle className="h-8 w-8 text-port-error" aria-hidden="true" />;+ if (capturing) {+ return (+ <span className="flex flex-col items-center gap-2 text-xs text-gray-400">+ <LoaderCircle className="h-6 w-6 animate-spin" aria-hidden="true" /> Drawing thumbnail…+ </span>+ );+ }+ return <ImageOff className="h-8 w-8 text-gray-600" aria-hidden="true" />;+}++function GalleryCard({ item, capturing }) {+ const status = STATUS[item.status] || STATUS.failed;+ const StatusIcon = status.icon;+ return (+ <Link+ to={`/code-animation/${encodeURIComponent(item.id)}`}+ className="group min-w-0 overflow-hidden rounded-xl border border-port-border bg-port-card transition-colors hover:border-port-accent"+ >+ <div className="relative flex aspect-video items-center justify-center bg-black">+ {item.posterVersion+ ? <img src={codeAnimationPosterUrl(item.id, item.posterVersion)} alt="" loading="lazy" className="h-full w-full object-contain" />+ : <PosterPlaceholder item={item} capturing={capturing} />}+ {item.status !== 'completed' && (+ <span className="port-media-overlay absolute left-2 top-2 inline-flex items-center gap-1 rounded px-2 py-0.5 text-xs">+ <StatusIcon className={`h-3 w-3 ${status.tone}`} aria-hidden="true" /> {status.label}+ </span>+ )}+ </div>+ <div className="space-y-1 p-3">+ <p className="truncate text-sm font-medium text-white group-hover:text-port-accent">{item.title || 'Untitled animation'}</p>+ <div className="flex items-center justify-between gap-2 text-xs text-gray-500">+ <span className="min-w-0 truncate">{item.status === 'completed' ? (item.model || 'Completed') : status.label}</span>+ <span className="shrink-0">{timeAgo(item.createdAt)}</span>+ </div>+ </div>+ </Link>+ );+}++/** Every saved Fast HTML generation, newest first, each opening its job route. */+export default function CodeAnimationGallery() {+ const fetchPage = useCallback(async ({ cursor, signal }) => {+ const page = await listCodeAnimationJobPage({ cursor, signal });+ return { ...page, meta: page.counts };+ }, []);+ const gallery = usePagedCollection(fetchPage);+ const { items, setItems, refreshFirst } = gallery;+ useSocketSubscription('code-animation', { onResubscribe: refreshFirst });+ useEffect(() => {+ const refresh = () => refreshFirst();+ socket.on('code-animation:changed', refresh);+ return () => socket.off('code-animation:changed', refresh);+ }, [refreshFirst]);++ // A completed job with no poster (one from before posters existed, or whose+ // capture was interrupted) gets one request per visit; the server draws them+ // one at a time. The mount guard is lifetime-scoped on purpose: this effect+ // re-runs on every items change, which must not drop an in-flight answer.+ const mounted = useMounted();+ const requested = useRef(new Set());+ const [capturing, setCapturing] = useState(() => new Set());+ useEffect(() => {+ const missing = items.filter((item) => item.status === 'completed' && !item.posterVersion && !requested.current.has(item.id));+ if (!missing.length) return;+ setCapturing((previous) => new Set([...previous, ...missing.map((item) => item.id)]));+ for (const { id } of missing) {+ requested.current.add(id);+ requestCodeAnimationPoster(id, { silent: true })+ .then(({ posterVersion }) => posterVersion)+ .catch(() => null)+ .then((posterVersion) => {+ if (!mounted.current) return;+ setCapturing((previous) => { const next = new Set(previous); next.delete(id); return next; });+ if (posterVersion) setItems((previous) => previous.map((entry) => (entry.id === id ? { ...entry, posterVersion } : entry)));+ });+ }+ }, [items, setItems, mounted]);++ const counts = gallery.meta || { running: 0, completed: 0 };+ return (+ <div className="space-y-4">+ <div className="flex flex-wrap items-center justify-between gap-3">+ <p className="text-sm text-gray-400">+ {formatCount(counts.completed, { fallback: '0' })} completed · {formatCount(counts.running, { fallback: '0' })} in progress+ </p>+ <Link+ to="/code-animation"+ className="inline-flex items-center gap-2 rounded-lg bg-port-accent px-3 py-1.5 text-sm text-white hover:opacity-90"+ >+ <Sparkles className="h-4 w-4" /> New animation+ </Link>+ </div>+ {!gallery.loaded && <p className="text-sm text-gray-500">Loading animations…</p>}+ {gallery.loaded && items.length === 0 && !gallery.error && (+ <div className="flex flex-col items-center gap-3 rounded-xl border border-dashed border-port-border p-10 text-center">+ <FileCode2 className="h-8 w-8 text-gray-600" aria-hidden="true" />+ <p className="text-sm text-gray-400">Animations you generate in Fast HTML appear here.</p>+ </div>+ )}+ {items.length > 0 && (+ <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3 2xl:grid-cols-4">+ {items.map((item) => (+ <GalleryCard key={item.id} item={item} capturing={capturing.has(item.id)} />+ ))}+ </div>+ )}+ <InfiniteScrollFooter hasMore={gallery.hasMore} loading={gallery.loading} error={gallery.error}+ onLoadMore={gallery.loadMore} label="Load older animations" />+ </div>+ );+}diff --git a/client/src/pages/CodeAnimation.jsx b/client/src/pages/CodeAnimation.jsxindex 5d2148a847..e092dedc69 100644--- a/client/src/pages/CodeAnimation.jsx+++ b/client/src/pages/CodeAnimation.jsx@@ -1,6 +1,6 @@import { useCallback, useEffect, useMemo, useRef, useState } from 'react';-import { AlertTriangle, CheckCircle2, Clock3, Copy, FileCode2, Film, Globe, ImagePlus, LoaderCircle, Music2, PenLine, Sparkles, Wand2, X } from 'lucide-react';-import { Link, useLocation, useNavigate, useParams, useSearchParams } from 'react-router';+import { Copy, FileCode2, Film, Globe, Images, ImagePlus, LoaderCircle, Music2, PenLine, Sparkles, Wand2, X } from 'lucide-react';+import { useLocation, useNavigate, useParams, useSearchParams } from 'react-router';import PageHeader from '../components/PageHeader';import RouteTabsHeader from '../components/ui/RouteTabsHeader';import ProviderModelSelector from '../components/ProviderModelSelector';@@ -9,20 +9,16 @@ import CodeAnimationPreview from '../components/codeAnimation/CodeAnimationPreviimport FilmStylePicker from '../components/codeAnimation/FilmStylePicker';import GalleryVideoPicker from '../components/videoGen/GalleryVideoPicker';import ProductionProjects from '../components/codeAnimation/ProductionProjects';+import CodeAnimationGallery from '../components/codeAnimation/CodeAnimationGallery';import UniverseMoodBoardPicker, { BOARD_FOLLOW_UNIVERSE, BOARD_NONE, useStyleSourceLists } from '../components/media/UniverseMoodBoardPicker';-import InfiniteScrollFooter from '../components/ui/InfiniteScrollFooter';import useProviderModels from '../hooks/useProviderModels';-import { usePagedCollection } from '../hooks/usePagedCollection';-import { useSocketSubscription } from '../hooks/useSocketSubscription';import { useSocketResource } from '../hooks/useSocketResource';-import socket from '../services/socket';import toast from '../components/ui/Toast';import {buildCodeAnimationPrompt,generateCodeAnimationBrief,getCodeAnimationJob,getCodeAnimationOptions,- listCodeAnimationJobPage,listTracks,startCodeAnimationGeneration,uploadFile,@@ -31,7 +27,6 @@ import { copyToClipboard } from '../lib/clipboard';import { pluralize } from '../lib/textUtils';import { safeReadJsonStorage, safeWriteJsonStorage } from '../lib/safeStorage';import { UPLOAD_IMAGE_ACCEPT, validateImageFile } from '../utils/fileUpload';-import { formatCount, timeAgo } from '../utils/formatters';const DRAFT_KEY = 'portos.codeAnimation.draft';const JOB_EVENTS = ['code-animation:changed'];@@ -239,20 +234,6 @@ function draftFromJob(job) {};}-function galleryJob(job) {- return {- id: job.id,- status: job.status,- title: job.title,- providerId: job.providerId,- model: job.model,- error: job.error,- createdAt: job.createdAt,- startedAt: job.startedAt,- completedAt: job.completedAt,- };-}-const readAudioDuration = (file) => new Promise((resolve) => {const url = URL.createObjectURL(file);const audio = new Audio();@@ -296,7 +277,6 @@ function FastCodeAnimation() {const [built, setBuilt] = useState(null);const [starting, setStarting] = useState(false);const [job, setJob] = useState(null);- const [galleryCounts, setGalleryCounts] = useState({ running: 0, completed: 0 });const [effort, setEffort] = useState('');const [briefEffort, setBriefEffort] = useState('');const [pastedHtml, setPastedHtml] = useState('');@@ -326,21 +306,6 @@ function FastCodeAnimation() {const onStyleGrammarChange = useCallback((styleGrammarId) => setDraft((prev) => ({ ...prev, styleGrammarId })), []);const updateFormat = (patch) => setDraft((prev) => ({ ...prev, format: { ...prev.format, ...patch } }));- const fetchGalleryPage = useCallback(async ({ cursor, signal }) => {- const page = await listCodeAnimationJobPage({ cursor, signal });- if (!signal.aborted) setGalleryCounts(page.counts);- return page;- }, []);- const gallery = usePagedCollection(fetchGalleryPage);- const savedJobs = gallery.items;- const setSavedJobs = gallery.setItems;- useSocketSubscription('code-animation', { onResubscribe: gallery.refreshFirst });- useEffect(() => {- const refresh = () => gallery.refreshFirst();- socket.on('code-animation:changed', refresh);- return () => socket.off('code-animation:changed', refresh);- }, [gallery.refreshFirst]);-useEffect(() => { safeWriteJsonStorage(DRAFT_KEY, draft); }, [draft]);useEffect(() => {@@ -365,8 +330,6 @@ function FastCodeAnimation() {// blank-slate idea generator.const briefSeeds = !!(draft.universeId || draft.seedIdea.trim() || draft.concept.trim() || draft.title.trim());const canWriteBrief = briefSeeds && !writingBrief;- const inProgressCount = galleryCounts.running;- const completedCount = galleryCounts.completed;// Clear route-specific output before applying the newly selected resource.useEffect(() => {@@ -397,10 +360,6 @@ function FastCodeAnimation() {setJob(next);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)]- .sort((a, b) => (b.createdAt || '').localeCompare(a.createdAt || '')));- }if (locallyStartedJobIdRef.current !== requested&& hydratedJobIdRef.current !== requested&& next.input) {@@ -539,7 +498,6 @@ function FastCodeAnimation() {setBuilt({ prompt: started.prompt, attachments: started.attachments, frame: started.frame, audioUrl: started.audioUrl, moodBoardId: started.moodBoardId, briefKey });setJob(started);setPreview(null);- setSavedJobs((previous) => [galleryJob(started), ...previous.filter((item) => item.id !== started.id)]);navigate(`/code-animation/${encodeURIComponent(started.id)}`);};@@ -552,59 +510,6 @@ function FastCodeAnimation() {return (<div className="mx-auto max-w-7xl space-y-4">- <section className="space-y-3 rounded-xl border border-port-border bg-port-card p-4" aria-labelledby="ca-gallery-heading">- <div className="flex flex-wrap items-center justify-between gap-3">- <div>- <h2 id="ca-gallery-heading" className="text-sm font-semibold text-white">Animation gallery</h2>- <p className="mt-1 text-xs text-gray-500">- {formatCount(inProgressCount)} in progress · {formatCount(completedCount)} completed- </p>- </div>- <Link to="/code-animation" className={buttonSecondary}>- <Sparkles className="h-4 w-4" /> New animation- </Link>- </div>- {!gallery.loaded && <p className="text-xs text-gray-500">Loading animations…</p>}- {gallery.loaded && savedJobs.length === 0 && !gallery.error && (- <p className="text-xs text-gray-500">Generated animations will appear here so you can reopen them later.</p>- )}- {savedJobs.length > 0 && (- <div className="grid max-h-64 grid-cols-1 gap-2 overflow-y-auto pr-1 sm:grid-cols-2 xl:grid-cols-3">- {savedJobs.map((item) => {- const StatusIcon = item.status === 'running'- ? Clock3- : item.status === 'completed'- ? CheckCircle2- : AlertTriangle;- const statusLabel = item.status === 'running'- ? 'In progress'- : item.status === 'completed'- ? 'Completed'- : 'Failed';- return (- <Link- key={item.id}- to={`/code-animation/${encodeURIComponent(item.id)}`}- aria-current={jobId === item.id ? 'page' : undefined}- className={`min-w-0 rounded-lg border p-3 transition-colors hover:border-port-accent ${jobId === item.id ? 'border-port-accent bg-port-accent/10' : 'border-port-border bg-port-bg/60'}`}- >- <div className="flex items-center gap-2">- <StatusIcon className={`h-4 w-4 shrink-0 ${item.status === 'failed' ? 'text-port-error' : item.status === 'completed' ? 'text-port-success' : 'text-port-accent'}`} />- <p className="min-w-0 flex-1 truncate text-sm font-medium text-white">{item.title || 'Untitled animation'}</p>- </div>- <div className="mt-2 flex items-center justify-between gap-2 text-xs text-gray-500">- <span>{statusLabel}{item.model ? ` · ${item.model}` : ''}</span>- <span className="shrink-0">{timeAgo(item.createdAt)}</span>- </div>- </Link>- );- })}- </div>- )}- <InfiniteScrollFooter hasMore={gallery.hasMore} loading={gallery.loading} error={gallery.error}- onLoadMore={gallery.loadMore} autoLoad={false} label="Load older animations" />- </section>-<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">@@ -901,7 +806,9 @@ function FastCodeAnimation() {// Route-mounted lanes keep inactive galleries and provider calls idle.export default function CodeAnimation() {const { pathname } = useLocation();- const production = pathname.startsWith('/code-animation/production');+ const mode = pathname.startsWith('/code-animation/production')+ ? 'production'+ : pathname === '/code-animation/gallery' || pathname.startsWith('/code-animation/gallery/') ? 'gallery' : 'fast';return <div className="flex h-full min-h-0 flex-col"><PageHeadericon={FileCode2}@@ -911,15 +818,16 @@ export default function CodeAnimation() {<RouteTabsHeaderariaLabel="Animation mode"- activeTab={production ? 'production' : 'fast'}+ activeTab={mode}tabs={[{ id: 'fast', label: 'Fast HTML', to: '/code-animation', icon: FileCode2 },+ { id: 'gallery', label: 'Gallery', to: '/code-animation/gallery', icon: Images },{ id: 'production', label: 'Production', to: '/code-animation/production', icon: Film },]}/><div className="flex-1 min-h-0 overflow-auto p-4 md:p-6"><div className="mx-auto max-w-7xl">- {production ? <ProductionProjects /> : <FastCodeAnimation />}+ {mode === 'production' ? <ProductionProjects /> : mode === 'gallery' ? <CodeAnimationGallery /> : <FastCodeAnimation />}</div></div></div>;diff --git a/client/src/pages/CodeAnimation.test.jsx b/client/src/pages/CodeAnimation.test.jsxindex f165d44a57..420ecf2629 100644--- a/client/src/pages/CodeAnimation.test.jsx+++ b/client/src/pages/CodeAnimation.test.jsx@@ -1,7 +1,7 @@import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';import { act, render, screen, waitFor } from '@testing-library/react';import userEvent from '@testing-library/user-event';-import { MemoryRouter, Route, Routes } from 'react-router';+import { Link, MemoryRouter, Route, Routes } from 'react-router';const socketHarness = vi.hoisted(() => ({ handlers: new Map(), emit: vi.fn() }));@@ -38,6 +38,8 @@ vi.mock('../services/api', () => ({getFilmStyle: vi.fn(),listFilmStyles: vi.fn(),listCodeAnimationJobPage: vi.fn().mockResolvedValue({ items: [], total: 0, counts: { running: 0, completed: 0 }, nextCursor: null }),+ codeAnimationPosterUrl: (id, version) => `/posters/${id}.jpg?v=${version}`,+ requestCodeAnimationPoster: vi.fn(),listMoodBoardNames: vi.fn(),listTracks: vi.fn().mockResolvedValue([]),listUniverseNames: vi.fn(),@@ -69,6 +71,7 @@ import {generateCodeAnimationBrief,getCodeAnimationJob,listCodeAnimationJobPage,+ requestCodeAnimationPoster,getCodeAnimationOptions,getFilmStyle,listFilmStyles,@@ -97,11 +100,13 @@ const BLUEPRINT = {nativeMoves: [{ name: 'Exploded assembly', how: 'Pull apart.', fitsContentLike: ['product anatomy', 'teardowns'] }],};-const renderPage = async (initialEntry = '/code-animation') => {+const renderPage = async (initialEntry = '/code-animation', navLinks = []) => {const result = render(<MemoryRouter initialEntries={[initialEntry]}>+ {navLinks.map((to) => <Link key={to} to={to}>Open {to}</Link>)}<Routes><Route path="/code-animation" element={<CodeAnimation />} />+ <Route path="/code-animation/gallery" element={<CodeAnimation />} /><Route path="/code-animation/:jobId" element={<CodeAnimation />} /></Routes></MemoryRouter>,@@ -177,7 +182,6 @@ describe('Code Animation page', () => {await emitSocket('code-animation:changed', { id: 'job-1' });expect(getCodeAnimationJob).toHaveBeenCalledTimes(2);expect(await screen.findByRole('button', { name: 'Run with audio' })).toBeInTheDocument();- expect(screen.getByRole('link', { name: /Example animation/ })).toHaveTextContent('Completed');await userEvent.setup().click(screen.getByRole('button', { name: 'Preview without audio' }));const frame = await screen.findByTitle('Code animation preview');expect(frame.tagName).toBe('IMG');@@ -230,10 +234,8 @@ describe('Code Animation page', () => {getCodeAnimationJob.mockImplementationOnce(() => new Promise(resolve => { resolveFirst = resolve; })).mockResolvedValue({ ...runningJob, id: 'job-2', title: 'Second animation',input: { title: 'Second animation', concept: 'Another scene' } });- listCodeAnimationJobPage.mockResolvedValue({ items: [{ ...runningJob, id: 'job-2', title: 'Second animation' }],- total: 1, counts: { running: 1, completed: 0 }, nextCursor: null });- const view = await renderPage('/code-animation/job-1');- await userEvent.setup().click(screen.getByRole('link', { name: /Second animation/ }));+ const view = await renderPage('/code-animation/job-1', ['/code-animation/job-2']);+ await userEvent.setup().click(screen.getByRole('link', { name: 'Open /code-animation/job-2' }));await waitFor(() => expect(screen.getByLabelText(/^title/i)).toHaveValue('Second animation'));await act(async () => resolveFirst(completedJob));expect(screen.getByLabelText(/^title/i)).toHaveValue('Second animation');@@ -260,16 +262,47 @@ describe('Code Animation page', () => {expect(screen.getByText('Reference images (0/8)')).toBeInTheDocument();});+ it('keeps the job list off Fast HTML and opens it as the Gallery tab', async () => {+ await renderPage();+ expect(listCodeAnimationJobPage).not.toHaveBeenCalled();+ await userEvent.setup().click(screen.getByRole('tab', { name: /Gallery/ }));+ expect(await screen.findByText('Animations you generate in Fast HTML appear here.')).toBeInTheDocument();+ expect(listCodeAnimationJobPage).toHaveBeenCalledTimes(1);+ });++ it('shows saved posters, draws a missing one once, and labels unfinished jobs', async () => {+ listCodeAnimationJobPage.mockResolvedValue({ items: [+ { id: 'job-a', status: 'completed', title: 'With poster', posterVersion: 11, createdAt: '2026-01-03T00:00:00.000Z' },+ { id: 'job-b', status: 'completed', title: 'Needs poster', createdAt: '2026-01-02T00:00:00.000Z' },+ { id: 'job-c', status: 'running', title: 'Still going', createdAt: '2026-01-01T00:00:00.000Z' },+ ], total: 3, counts: { running: 1, completed: 2 }, nextCursor: null });+ let drawPoster;+ requestCodeAnimationPoster.mockImplementation(() => new Promise((resolve) => { drawPoster = resolve; }));+ const { container } = await renderPage('/code-animation/gallery');+ await waitFor(() => expect(screen.getByRole('link', { name: /With poster/ })).toHaveAttribute('href', '/code-animation/job-a'));+ expect(container.querySelector('img[src="/posters/job-a.jpg?v=11"]')).not.toBeNull();+ expect(screen.getByText('Drawing thumbnail…')).toBeInTheDocument();+ expect(screen.getAllByText('In progress').length).toBeGreaterThan(0);+ expect(requestCodeAnimationPoster).toHaveBeenCalledTimes(1);+ expect(requestCodeAnimationPoster).toHaveBeenCalledWith('job-b', { silent: true });+ await act(async () => drawPoster({ posterVersion: 22 }));+ expect(container.querySelector('img[src="/posters/job-b.jpg?v=22"]')).not.toBeNull();+ expect(screen.queryByText('Drawing thumbnail…')).not.toBeInTheDocument();+ await emitSocket('code-animation:changed', { id: 'job-c' });+ expect(requestCodeAnimationPoster).toHaveBeenCalledTimes(1);+ });+it('loads one compact page, stays idle, and refreshes on durable changes and reconnect', async () => {const jobs = Array.from({ length: 50 }, (_, n) => ({id: `job-${n}`, status: 'completed', title: `Animation ${n}`, createdAt: '2026-01-01T00:00:00.000Z',}));listCodeAnimationJobPage.mockResolvedValue({ items: jobs, total: 1000,counts: { running: 0, completed: 1000 }, nextCursor: 'next-page' });- await renderPage();+ requestCodeAnimationPoster.mockResolvedValue({ posterVersion: null });+ await renderPage('/code-animation/gallery');await waitFor(() => expect(screen.getAllByRole('link', { name: /Animation \d+/ })).toHaveLength(50));expect(listCodeAnimationJobPage).toHaveBeenCalledTimes(1);- expect(screen.getByText('0 in progress · 1,000 completed')).toBeInTheDocument();+ expect(screen.getByText('1,000 completed · 0 in progress')).toBeInTheDocument();expect(screen.getByRole('button', { name: 'Load older animations' })).toBeInTheDocument();vi.useFakeTimers();await act(async () => { vi.advanceTimersByTime(60_000); });diff --git a/client/src/services/README.md b/client/src/services/README.mdindex a0788f62d6..5cb4469808 100644--- a/client/src/services/README.md+++ b/client/src/services/README.md@@ -116,7 +116,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, LLM-written briefs from a universe, universe-styled prompt building, a persistent generation gallery, provider jobs, frame-exact export, portable package download, and opt-in Production project settings, immutable candidate/accepted source imports, brief handoff paged run history, and bounded production stage runs (start, cancel, resume). |+| `apiCodeAnimation.js` | Code Animation: host-contract options, LLM-written briefs from a universe, universe-styled prompt building, a persistent generation gallery with poster thumbnails, provider jobs, frame-exact export, portable package download, and opt-in Production project settings, immutable candidate/accepted source imports, brief handoff paged run history, and bounded production stage runs (start, cancel, resume). || `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/apiCodeAnimation.js b/client/src/services/apiCodeAnimation.jsindex 56557657fc..793a90eaf1 100644--- a/client/src/services/apiCodeAnimation.js+++ b/client/src/services/apiCodeAnimation.js@@ -45,6 +45,14 @@ export const listCodeAnimationJobPage = ({ cursor, signal, limit = 50 } = {}) =>request(`/code-animation/jobs?limit=${limit}${cursor ? `&cursor=${encodeURIComponent(cursor)}` : ''}`,{ signal, silent: true });+// `version` is the poster's mtime from the jobs page; the server caches each URL forever.+export const codeAnimationPosterUrl = (id, version) =>+ `/api/code-animation/jobs/${encodeURIComponent(id)}/poster?v=${encodeURIComponent(version)}`;++// Resolves { posterVersion } once captured (null when the page drew nothing); captures run one at a time.+export const requestCodeAnimationPoster = (id, options) =>+ request(`/code-animation/jobs/${encodeURIComponent(id)}/poster`, { method: 'POST', ...options });+export const getCodeAnimationJob = (id, options) =>request(`/code-animation/generate/${encodeURIComponent(id)}`, options);diff --git a/docs/API.md b/docs/API.mdindex 21a06f8faa..4a9b3d7e4e 100644--- a/docs/API.md+++ b/docs/API.md@@ -828,7 +828,7 @@ Every mounted API prefix (see `server/index.js` for the authoritative list). Dom| `/api/sprites` | Sprite catalog / export; `POST /import` is host control (it names a host source tree to copy from) || `/api/threejs-models` | Procedural Three.js models || `/api/film-styles` | Read-only film style grammar catalog: picker list (`GET /`), full grammar record (`GET /:id`) and rendered prompt-section preview (`GET /:id/prompt?parts=motion,camera`) |-| `/api/code-animation` | Code Animation: LLM-written briefs, prompt building, persistent jobs gallery, generated HTML retrieval, frame-exact MP4 export (`POST /:id/export` → HTML-composition media job), the vendored three.js modules the `three` renderer's preview inlines (`GET /vendor/three`; the export stages the same files, hashed, beside the page), portable source download (`GET /:id/package`), and data-only package validation (`POST /packages/validate`; [contract](CODE_ANIMATION_PACKAGES.md)) |+| `/api/code-animation` | Code Animation: LLM-written briefs, prompt building, persistent jobs gallery with poster thumbnails (`GET`/`POST /jobs/:id/poster`; captured in the jailed preview browser), generated HTML retrieval, frame-exact MP4 export (`POST /:id/export` → HTML-composition media job), the vendored three.js modules the `three` renderer's preview inlines (`GET /vendor/three`; the export stages the same files, hashed, beside the page), portable source download (`GET /:id/package`), and data-only package validation (`POST /packages/validate`; [contract](CODE_ANIMATION_PACKAGES.md)) || `/api/code-animation/execution` | Code Animation contained production execution: platform sandbox and lane readiness (`GET /`), operator-owned tool paths (`PUT /tools`, host control) and the on-demand adversarial containment check (`POST /probe`, host control) ([contract](CODE_ANIMATION_PACKAGES.md#contained-production-execution)) || `/api/image-to-3d` | Image-to-3D conversion || `/api/rigging` | Auto-skin rigging and animation retargeting for image-to-3D models |diff --git a/docs/STORAGE.md b/docs/STORAGE.mdindex 5269c1f9a4..37ac8715eb 100644--- a/docs/STORAGE.md+++ b/docs/STORAGE.md@@ -149,7 +149,7 @@ does not recover nonempty output or general failed saves; those still require th- `games` — Game studio workspaces (#3177): one row per managed-app asset plan, with the full reusable sprite/music binding set, current compiled-manifest pointer, compile history, and user-requested AI feedback history in `data` JSONB; `app_id`/`name`/`updated_at` are mirrored for list and relationship queries. The record is **machine-local** because managed-app registration, sprite atlases, and music-library bytes are machine-local; there is no peer-sync cursor or tombstone, and deletes are hard deletes. Compiled manifests are immutable, SHA-256-addressed artifacts under `data/games/{id}/manifests/`; their pointers and hashes live in the DB record. Adapter: `server/services/games/db.js`, selected pg-vs-collectionStore by `server/services/games/store.js` (collectionStore is test/unsupported file escape hatch only).- `fableloom_stories` — FableLoom branching narratives: one row per loom (a branching-narrative story), with episodes, scene-node graphs, and intent transitions in `data` JSONB; `name`/`universe_id`/`series_id`/`updated_at` are mirrored for list and relationship queries (both refs are soft — no FK). `db-primary` because looms relate to universes and series and the index queries by recency. Federates through the opt-in per-record `fableLoom` category: whole-record LWW merges carry soft-delete tombstones, conflict-journal recovery, and hashed manifests for scene images/videos; there is no snapshot cursor or `sync_sequence`. Adapter: `server/services/fableLoom/db.js`, selected pg-vs-collectionStore by `server/services/fableLoom/store.js` (collectionStore is the test/unsupported file escape hatch only). Feature doc: [FableLoom](./features/fableloom.md).- `threejs_models` — generated procedural 3D-model workspaces: one row per model with gallery-image lineage, provider/model attribution, generation/refinement status, and the validated declarative scene spec in `data` JSONB. The referenced image bytes remain under `data/images/`; deterministic Three.js source is derived from the stored spec rather than persisted as a second mutable artifact. The table is local-only in this first slice, with soft-delete columns retained so federation can be added without a record-shape migration.-- `code_animation_jobs` — Code Animation generation history (`db-primary` record with a managed HTML output asset): job status/title and the generation brief/provider details are stored in PostgreSQL so the gallery can list and reopen jobs after navigation or restart. The generated HTML is kept as a managed file at `data/code-animations/<id>.html`; PostgreSQL stores only its job record, not the output bytes. Jobs are machine-local and never federated. The database dump covers records and the normal filesystem backup includes the HTML assets.+- `code_animation_jobs` — Code Animation generation history (`db-primary` record with a managed HTML output asset): job status/title and the generation brief/provider details are stored in PostgreSQL so the gallery can list and reopen jobs after navigation or restart. The generated HTML is kept as a managed file at `data/code-animations/<id>.html`, with its derived gallery poster beside it at `data/code-animations/<id>.jpg` (drawn from the page in the jailed preview browser when the job completes, or on first gallery view for older jobs; a missing poster is simply redrawn, so it needs no row of its own); PostgreSQL stores only its job record, not the output bytes. Jobs are machine-local and never federated. The database dump covers records and the normal filesystem backup includes the HTML assets.- `code_animation_projects`, `code_animation_project_revisions`, `code_animation_project_runs` — opt-in Code Animation Production settings, accepted/candidate source pointers, immutable source/package hashes, portable manifest metadata and bounded import history. PostgreSQL owns metadata; source/asset bytes are write-once files under `data/code-animations/projects/<project-id>/revisions/<revision-id>/`. Settings, reference IDs, execution snapshots, managed paths and run IDs are machine-local and never federate. Budgets independently record iterations, elapsed time, tokens, render time and total retained disk bytes; imports consume disk only and never execute or install dependencies. Every attempted import has its own UUID-owned destination; failed/interrupted staging stays attributable to its run and never replaces accepted source. Boot DDL and migration 420 install empty tables without a seed. The PostgreSQL dump covers all three tables, and normal filesystem backup includes the entire project directory (no new excludes). Brief handoff omits local settings/IDs/paths; revision packages export only the validated portable contract. Source acceptance is explicit and does not assert visual, motion, sound or render evidence. Contained production workers stage each run in its own `data/code-animation-workspaces/<uuid>/` (excluded from backups, removed when the run ends); their operator-chosen tool paths are the machine-local `codeAnimationExecution` slice of `data/settings.json`.- `ai_connections` / `ai_harness_bindings` / `ai_route_bindings` — AI **services** (instances a harness is pointed at) and the graph the **presets** derived from them are projected through (#6367 → #7561; user guide [AI_PROVIDERS.md](./AI_PROVIDERS.md), design record [provider connections and harnesses](./plans/2026-09-06-provider-connections-and-harnesses.md)): the backend a harness talks to, each harness configuration bound to it, and the executable route each one projects. `db-primary` because it is a real graph — a connection has many bindings, a binding has one route per mode, and the uniqueness rules (`UNIQUE(binding_id, mode)`, `UNIQUE(connection_id, harness_id, variant_key)` plus a partial index for null-harness API bindings) are integrity constraints a set of JSON files cannot hold. `data/providers.json` REMAINS the execution contract and stays fully materialized: every connection-owned value is projected back into it, so a downgraded release runs unchanged with these tables simply idle. **Intentionally machine-local — never federated**: rows carry endpoints, credential material and this host's execution environment (ADR [privacy records machine-local](./decisions/2026-08-08-privacy-records-machine-local.md)). No `sync_sequence`, no tombstones, no `PORTOS_SCHEMA_VERSIONS` entry, no `dataSync` category; deletes are hard deletes and are refused while a binding still references the row. `ai_route_bindings.projected` / `.pending` are the projection snapshots that make an interrupted file write recoverable — as private as the credentials, and covered by the Postgres dump like every other db-primary table. Adapters: `server/services/providerGraphStore.js` (rows) and `server/services/providerGraph.js` (import, reconciliation, link/unlink), over the pure `server/lib/providerGraphRecords.js`. Since #7563 an `ai_connections` row is also one SERVICE INSTANCE of a `server/lib/serviceDefinitions.js` entry: additive `slug` (unique, the address a composite provider id will carry), `definition_id`, `plan` (`free` / `paid` / `subscription` / `local`), `enabled` and `credential_via` (`stored` / `env` / `cli-login` / `bootstrap` — only `stored` holds a secret), with `catalog` gaining optional per-model `capabilities` and `refreshedAt`. The columns are backfilled from `kind` by the boot reconcile pass (`planServiceColumnBackfill` in `server/lib/providerServiceInstances.js`) — derived from the install's own rows, never seeded, idempotent — and managed through `server/services/providerServices.js` (`/api/providers/services*`), which refreshes a catalog through the definition's listing strategy without needing an executable route. Since #7565 a `data/providers.json` record may name the instance it is DERIVED from (`harnessId` / `method` / `serviceId`, plus `catalogNarrowing` and `credentialBootstrapId`): its connection-owned values are re-materialized from that row on every save and on every service edit, while the file stays the fully materialized execution contract — an older release runs the record unchanged and its schema strips the keys it never saw. The stamping of existing records rides the same boot reconcile pass (`planPresetBackfill` in `server/lib/providerPresets.js`), additive and idempotent; see `docs/PROVIDER_COMPOSITION.md` § Presets.- `privacy_subjects` / `privacy_vault_records` / `privacy_consents` / `privacy_orgs` / `privacy_org_holdings` / `privacy_change_events` / `privacy_brokers` / `privacy_broker_cases` — the Privacy Center (epic #2138): the household subjects the suite works on behalf of (`self` plus consenting partners/children/parents — every other table carries a `subject_id` FK defaulted to the seeded `self` row, #3658), the encrypted PII vault, the trusted-organization registry with per-field holdings, the change-of-address inventory, and the data-broker opt-out ledger. Relational by nature (org ↔ holdings ↔ vault records ↔ change events ↔ broker cases), which is why they are `db-primary`. Vault *values* are AES-256-GCM ciphertext (`v1:<iv>:<tag>:<ct>`, key from `PRIVACY_VAULT_KEY`) — the DB holds bytes of ciphertext, never plaintext PII, and plaintext never appears in logs (`server/lib/vaultCrypto.js`). Broker-case `evidence` follows the same rule (#8333): the matched name/location and the identity-bearing search/listing URLs a scan records are sealed under `evidence.sealed_identity` with the same key, erased on `confirmed_removed`, on the per-case erase action, and when the source `legal_name`/`address` vault record is deleted. **Intentionally machine-local — never federated**, and this is a product *guarantee*, not a deferred feature (ADR [privacy records machine-local](./decisions/2026-08-08-privacy-records-machine-local.md), #2148). NO `sync_sequence`, NO peer-sync record kind, NO `dataSync` category, NO `PORTOS_SCHEMA_VERSIONS` entry, and no `deleted`/`deleted_at` tombstones — deletes are hard deletes, mirroring `tribe`. The reasoning is the same class as the Tribe graph but stronger: the peer-sync **pull** path (`GET /api/peer-sync/record`) carries no peer identity, `masked_value` is plaintext by design so even ciphertext-only sync would leak a PII fingerprint, and a shared `PRIVACY_VAULT_KEY` would widen the at-rest blast radius to every peer's `.env`. A second machine gets the vault by restoring a backup and copying the key by hand — a deliberate act, not continuous replication. Enforced by `server/services/sharing/privacyNeverFederates.test.js`. Adapters: `server/services/privacySubjects.js`, `privacyVault.js`, `privacyOrgs.js`, `privacyChanges.js`, `privacyBrokers.js`, `privacyOptOut.js`.diff --git a/server/lib/navManifest.js b/server/lib/navManifest.jsindex ea2a6fd678..ec760a36f9 100644--- a/server/lib/navManifest.js+++ b/server/lib/navManifest.js@@ -60,6 +60,7 @@ const RAW_NAV_COMMANDS = [{ 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.code-animation.gallery', path: '/code-animation/gallery', label: 'Code Animation Gallery', section: 'Create', aliases: ['code-animation-gallery', 'animation-gallery', 'past-animations'], keywords: ['gallery', 'thumbnails', 'posters', 'past animations', 'history', 'reopen animation', 'saved animations'] },{ id: 'nav.create.code-animation.production', path: '/code-animation/production', label: 'Code Animation Production', section: 'Create', aliases: ['code-animation-production', 'animation-production', 'production-animation'], keywords: ['film projects', 'accepted output', 'compare runs', 'evidence', 'source packages', 'immutable revisions', 'animation history'] },{ 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'] },diff --git a/server/routes/codeAnimation.js b/server/routes/codeAnimation.jsindex f44958e7b8..3be6a94f7d 100644--- a/server/routes/codeAnimation.js+++ b/server/routes/codeAnimation.js@@ -8,6 +8,8 @@* 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/jobs list saved jobs for the gallery+ * GET /api/code-animation/jobs/:id/poster a completed job's gallery poster (JPEG)+ * POST /api/code-animation/jobs/:id/poster capture a missing poster → { posterVersion } (null when it could not be drawn)* 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* GET /api/code-animation/:id/package download a portable source package@@ -31,6 +33,8 @@ import { filmStyleIdSchema } from '../lib/filmStyleGrammarValidation.js';import { getFilmStyleGrammar } from '../lib/filmStyleGrammars.js';import {buildCodeAnimationRequest,+ captureCodeAnimationJobPoster,+ codeAnimationPosterPath,generateCodeAnimationBrief,getCodeAnimationJob,listCodeAnimationJobs,@@ -196,14 +200,28 @@ router.get('/jobs', asyncHandler(async (req, res) => {: await pageCodeAnimationJobs(validateRequest(jobsPageSchema, req.query)));}));+const exportParamsSchema = z.object({ id: z.string().uuid() }).strict();++router.get('/jobs/:id/poster', asyncHandler(async (req, res) => {+ const { id } = validateRequest(exportParamsSchema, req.params);+ // The gallery requests it with ?v=<poster mtime>, so a recapture is a new URL.+ // The header rides only a sent file, so a missing poster's 404 is not cached.+ res.sendFile(codeAnimationPosterPath(id), { headers: { 'Cache-Control': 'private, max-age=31536000, immutable' } }, (error) => {+ if (error && !res.headersSent) res.status(404).json({ error: 'Poster not found', code: 'NOT_FOUND' });+ });+}));++router.post('/jobs/:id/poster', asyncHandler(async (req, res) => {+ const { id } = validateRequest(exportParamsSchema, req.params);+ res.json(await captureCodeAnimationJobPoster(id));+}));+router.get('/generate/:id', asyncHandler(async (req, res) => {const job = await getCodeAnimationJob(req.params.id);if (!job) throw new ServerError('Generation job not found', { status: 404, code: 'NOT_FOUND' });res.json(job);}));-const exportParamsSchema = z.object({ id: z.string().uuid() }).strict();-const projectPageSchema = z.object({limit: z.coerce.number().int().min(1).max(100).default(50),cursor: z.string().regex(/^(0|[1-9][0-9]{0,8})$/).optional(),diff --git a/server/routes/codeAnimation.test.js b/server/routes/codeAnimation.test.jsindex 5c45ea95bb..4e4d0909f9 100644--- a/server/routes/codeAnimation.test.js+++ b/server/routes/codeAnimation.test.js@@ -11,9 +11,11 @@ import { createCodeAnimationPackage, CODE_ANIMATION_PACKAGE_LIMITS } from '../liimport { JSON_BODY_LIMIT } from '../lib/uploadLimits.js';import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../lib/mockPathsDataRoot.js';-const { codeAnimationRecords, codeAnimationHtml } = vi.hoisted(() => ({+const { codeAnimationRecords, codeAnimationHtml, codeAnimationPosters } = vi.hoisted(() => ({codeAnimationRecords: new Map(),codeAnimationHtml: new Map(),+ // id → poster mtime; capture is a jailed-browser render, doubled here.+ codeAnimationPosters: new Map(),}));vi.mock('../lib/paths.js', async (importOriginal) =>@@ -35,6 +37,15 @@ vi.mock('../services/codeAnimation/jobStore.js', () => ({readCodeAnimationHtml: vi.fn(async (id) => codeAnimationHtml.get(id)),saveCodeAnimationHtml: vi.fn(async (id, html) => codeAnimationHtml.set(id, html)),saveCodeAnimationJobRecord: vi.fn(async (job) => codeAnimationRecords.set(job.id, job)),+ codeAnimationPosterPath: (id) => `${process.env.PORTOS_TEST_POSTER_DIR}/${id}.jpg`,+ codeAnimationPosterVersions: vi.fn(async (ids) => new Map(ids.filter((id) => codeAnimationPosters.has(id)).map((id) => [id, codeAnimationPosters.get(id)]))),+}));+vi.mock('../services/codeAnimation/poster.js', () => ({+ captureCodeAnimationPoster: vi.fn(async (id) => {+ writeFileSync(`${process.env.PORTOS_TEST_POSTER_DIR}/${id}.jpg`, 'jpeg-bytes');+ codeAnimationPosters.set(id, 1700000000000);+ return true;+ }),}));vi.mock('../services/socket.js', () => ({// Observe the persisted state at emit time: a notification before a save@@ -67,6 +78,7 @@ import { getTrack } from '../services/tracks/index.js';import { listCodeAnimationJobPage, listCodeAnimationJobRecords, readCodeAnimationHtml, saveCodeAnimationHtml, saveCodeAnimationJobRecord } from '../services/codeAnimation/jobStore.js';import { assertProvider, resolveProviderAndModel, runPromptThroughProvider } from '../services/promptRunner.js';import { enqueueJob } from '../services/mediaJobQueue/index.js';+import { captureCodeAnimationPoster } from '../services/codeAnimation/poster.js';import routes from './codeAnimation.js';const makeApp = () => {@@ -103,6 +115,8 @@ const BOARD = {const brief = { concept: 'A lantern drifts over a sleeping city', universeId: 'universe-1' };beforeAll(() => {+ process.env.PORTOS_TEST_POSTER_DIR = join(PATHS.data, 'code-animations');+ mkdirSync(process.env.PORTOS_TEST_POSTER_DIR, { recursive: true });mkdirSync(PATHS.uploads, { recursive: true });mkdirSync(PATHS.imageRefs, { recursive: true });mkdirSync(PATHS.images, { recursive: true });@@ -121,6 +135,7 @@ beforeEach(() => {vi.clearAllMocks();codeAnimationRecords.clear();codeAnimationHtml.clear();+ codeAnimationPosters.clear();getUniverse.mockResolvedValue(UNIVERSE);getBoard.mockResolvedValue(BOARD);resolveProviderAndModel.mockResolvedValue({ provider: { id: 'api-1', type: 'api' }, selectedModel: 'example-model' });@@ -379,6 +394,39 @@ describe('GET /api/code-animation/jobs', () => {});});+describe('Code Animation gallery posters', () => {+ const id = '00000000-0000-4000-8000-0000000000aa';+ const completed = { id, status: 'completed', title: 'Lantern', concept: 'x', createdAt: '2026-01-01T00:00:00.000Z' };++ it('draws a missing poster on request, lists its version, and serves it cacheably', async () => {+ codeAnimationRecords.set(id, completed);+ const app = makeApp();+ const before = await request(app).get('/api/code-animation/jobs?limit=50');+ expect(before.body.items[0]).not.toHaveProperty('posterVersion');+ const missing = await request(app).get(`/api/code-animation/jobs/${id}/poster?v=1`);+ expect(missing.status).toBe(404);+ expect(missing.headers['cache-control'] || '').not.toMatch(/immutable/);++ const drawn = await request(app).post(`/api/code-animation/jobs/${id}/poster`);+ expect(drawn.status).toBe(200);+ expect(drawn.body).toEqual({ posterVersion: 1700000000000 });+ expect((await request(app).get('/api/code-animation/jobs?limit=50')).body.items[0].posterVersion).toBe(1700000000000);+ const served = await request(app).get(`/api/code-animation/jobs/${id}/poster?v=1700000000000`);+ expect(served.status).toBe(200);+ expect(served.headers['content-type']).toMatch(/image\/jpeg/);+ expect(served.headers['cache-control']).toMatch(/immutable/);+ });++ it('refuses a poster for a job that has not completed, an unknown job, and a non-uuid id', async () => {+ codeAnimationRecords.set(id, { ...completed, status: 'running' });+ const app = makeApp();+ expect((await request(app).post(`/api/code-animation/jobs/${id}/poster`)).status).toBe(409);+ expect((await request(app).post('/api/code-animation/jobs/00000000-0000-4000-8000-0000000000bb/poster')).status).toBe(404);+ expect((await request(app).get('/api/code-animation/jobs/..%2F..%2Fsecrets/poster')).status).toBe(400);+ expect(captureCodeAnimationPoster).not.toHaveBeenCalled();+ });+});+describe('POST /api/code-animation/brief', () => {const briefResponse = (body) => ({ runId: 'run-b', text: `\`\`\`json\n${JSON.stringify(body)}\n\`\`\`` });@@ -636,6 +684,7 @@ describe('POST /api/code-animation/generate', () => {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');+ await vi.waitFor(() => expect(captureCodeAnimationPoster).toHaveBeenCalledWith(job.id));});it('attaches the references for a vision-capable CLI provider instead of only naming their paths', async () => {diff --git a/server/services/codeAnimation/index.js b/server/services/codeAnimation/index.jsindex 2bc2ed9ff9..8003d2e010 100644--- a/server/services/codeAnimation/index.js+++ b/server/services/codeAnimation/index.js@@ -32,6 +32,7 @@ import {listRunningCodeAnimationJobIds,listCodeAnimationJobPage,countCodeAnimationJobs,+ codeAnimationPosterVersions,readCodeAnimationHtml,saveCodeAnimationHtml,saveCodeAnimationJobRecord,@@ -397,7 +398,9 @@ export async function pageCodeAnimationJobs({ limit = JOB_PAGE_SIZE, cursor } =listCodeAnimationJobPage({ limit: size, cursor: after }),countCodeAnimationJobs(),]);- const items = rows.slice(0, size);+ const page = rows.slice(0, size);+ const posters = await codeAnimationPosterVersions(page.filter((job) => job.status === 'completed').map((job) => job.id));+ const items = page.map((job) => (posters.has(job.id) ? { ...job, posterVersion: posters.get(job.id) } : job));const last = items.at(-1);return {items,@@ -507,6 +510,10 @@ export async function startCodeAnimationGeneration(input) {emitCodeAnimationChanged(id);activeJobs.delete(id);console.log(`✅ Code animation generation ${id.slice(0, 8)} completed (${html.length} chars)`);+ // Detached: the gallery shows a placeholder until the poster lands.+ import('./poster.js').then(({ captureCodeAnimationPoster }) => captureCodeAnimationPoster(id)).catch((error) => {+ console.error(`❌ Code animation ${id.slice(0, 8)} poster could not start: ${error.message}`);+ });}).catch(async (error) => {const message = String(error?.message || error || 'Generation failed').slice(0, 2_000);@@ -521,6 +528,19 @@ export async function startCodeAnimationGeneration(input) {return job;}+export { codeAnimationPosterPath } from './jobStore.js';++/** Draw a completed job's missing gallery poster; posterVersion is null when the page drew nothing. */+export async function captureCodeAnimationJobPoster(id) {+ 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 has a poster', { status: 409, code: 'NOT_COMPLETED' });+ const { captureCodeAnimationPoster } = await import('./poster.js');+ await captureCodeAnimationPoster(id);+ const versions = await codeAnimationPosterVersions([id]);+ return { posterVersion: versions.get(id) ?? null };+}+export async function getCodeAnimationJob(id) {if (!isCodeAnimationJobId(id)) return null;const record = await getCodeAnimationJobRecord(id);diff --git a/server/services/codeAnimation/jobStore.js b/server/services/codeAnimation/jobStore.jsindex d5c8a78eb0..3c86e131a7 100644--- a/server/services/codeAnimation/jobStore.js+++ b/server/services/codeAnimation/jobStore.js@@ -3,7 +3,7 @@* the generated HTML stays in its managed data directory as a file asset.*/-import { readFile } from 'fs/promises';+import { readFile, stat } from 'fs/promises';import { join } from 'path';import { query } from '../../lib/db.js';import { PATHS } from '../../lib/paths.js';@@ -104,3 +104,21 @@ export async function readCodeAnimationHtml(id) {throw error;}}++// The gallery poster is a derived thumbnail of the completed HTML, beside it.+export function codeAnimationPosterPath(id) {+ return htmlPath(id).replace(/\.html$/, '.jpg');+}++export async function saveCodeAnimationPoster(id, jpeg) {+ await atomicWrite(codeAnimationPosterPath(id), jpeg);+}++/** Poster mtimes (ms) for the given ids; an id without a poster is absent. */+export async function codeAnimationPosterVersions(ids) {+ const entries = await Promise.all(ids.filter(isCodeAnimationJobId).map(async (id) => {+ const info = await stat(codeAnimationPosterPath(id)).catch(() => null);+ return info?.isFile() ? [id, Math.round(info.mtimeMs)] : null;+ }));+ return new Map(entries.filter(Boolean));+}diff --git a/server/services/codeAnimation/poster.js b/server/services/codeAnimation/poster.jsnew file mode 100644index 0000000000..eba03444b6--- /dev/null+++ b/server/services/codeAnimation/poster.js@@ -0,0 +1,110 @@+/**+ * Gallery poster frames for completed Code Animation jobs. The generated page+ * runs in the OS-jailed composition browser (never the user's browser), its+ * animation loop is stopped, and the canvas is read after one deterministic+ * `renderFrame(t)` call — so the poster holds only film pixels, never the+ * page's own controls overlay.+ */+import { randomUUID } from 'crypto';+import { rm } from 'fs/promises';+import { emitCodeAnimationChanged } from '../socket.js';+import { getCodeAnimationJobRecord, isCodeAnimationJobId, readCodeAnimationHtml, saveCodeAnimationPoster } from './jobStore.js';++const POSTER_WIDTH = 640;+const POSTER_TIMEOUT_MS = 45_000;+// Far enough in to be past a fade from black, early enough to precede an ending fade.+const POSTER_POSITION = 0.3;+const VIEWPORT = { width: 1280, height: 720 };++// One capture at a time: each launches a jailed browser.+let tail = Promise.resolve();+const inFlight = new Map();+// Ids whose capture failed in this process, so a gallery reload does not relaunch them.+const failed = new Set();+let isolationUnavailable = false;++export const posterCaptureScript = (fallbackDuration) => `(async () => {+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));+ const until = Date.now() + 8000;+ while (typeof window.renderFrame !== 'function' && Date.now() < until) await sleep(100);+ if (typeof window.renderFrame !== 'function') await sleep(1500);+ window.requestAnimationFrame = () => 0;+ await sleep(50);+ const canvas = [...document.querySelectorAll('canvas')].sort((a, b) => b.width * b.height - a.width * a.height)[0];+ if (!canvas || !canvas.width || !canvas.height) return null;+ const duration = Number(window.ANIMATION_META && window.ANIMATION_META.duration) || ${Number(fallbackDuration) || 0};+ if (typeof window.renderFrame === 'function') window.renderFrame(duration * ${POSTER_POSITION});+ const width = Math.min(${POSTER_WIDTH}, canvas.width);+ const height = Math.max(1, Math.round(canvas.height * width / canvas.width));+ const out = document.createElement('canvas');+ out.width = width;+ out.height = height;+ const ctx = out.getContext('2d');+ ctx.fillStyle = '#000';+ ctx.fillRect(0, 0, width, height);+ ctx.drawImage(canvas, 0, 0, width, height);+ return out.toDataURL('image/jpeg', 0.82).split(',')[1] || null;+})()`;++async function capture(id) {+ const job = await getCodeAnimationJobRecord(id);+ if (job?.status !== 'completed') return false;+ const html = await readCodeAnimationHtml(id);+ const [{ stageCodeAnimationPage }, { openComposition }, { PREVIEW_PAGE_CSP }] = await Promise.all([+ import('../generatedPreview/codeAnimationPage.js'),+ import('../htmlComposition/browser.js'),+ import('../../lib/generatedPreviewSandbox.js'),+ ]);+ const staged = await stageCodeAnimationPage(`poster-${randomUUID()}`, html);+ let page;+ try {+ page = await openComposition(staged.directory, {+ signal: AbortSignal.timeout(POSTER_TIMEOUT_MS),+ ownedBrowser: true,+ isolation: 'required',+ streamMedia: true,+ contentSecurityPolicy: PREVIEW_PAGE_CSP,+ // A page error is reported, not fatal: most films still draw a usable frame.+ previewBridge: true,+ refuseUnknown: 'empty',+ lockLoopback: true,+ onEvent: () => {},+ });+ await page.send('Emulation.setDeviceMetricsOverride', { ...VIEWPORT, deviceScaleFactor: 1, mobile: false });+ const data = await page.evaluate(posterCaptureScript(job.frame?.durationSeconds), 'poster capture');+ if (typeof data !== 'string' || !data) return false;+ await saveCodeAnimationPoster(id, Buffer.from(data, 'base64'));+ return true;+ } finally {+ await page?.close().catch((error) => console.error(`❌ Code animation poster browser close failed: ${error.message}`));+ await rm(staged.scratchRoot, { recursive: true, force: true }).catch((error) => {+ console.error(`❌ Code animation poster scratch cleanup failed: ${error.message}`);+ });+ }+}++/**+ * Capture a completed job's poster. Resolves true when a poster was written;+ * never rejects, because the completion path runs it detached.+ */+export function captureCodeAnimationPoster(id) {+ if (!isCodeAnimationJobId(id) || isolationUnavailable || failed.has(id)) return Promise.resolve(false);+ if (inFlight.has(id)) return inFlight.get(id);+ const run = tail.then(() => capture(id)).then((written) => {+ if (written) {+ console.log(`🖼️ Code animation ${id.slice(0, 8)} poster captured`);+ emitCodeAnimationChanged(id);+ } else {+ failed.add(id);+ }+ return written;+ }).catch((error) => {+ if (error?.code === 'PREVIEW_ISOLATION_UNAVAILABLE') isolationUnavailable = true;+ failed.add(id);+ console.error(`❌ Code animation ${id.slice(0, 8)} poster capture failed: ${error?.message || error}`);+ return false;+ }).finally(() => inFlight.delete(id));+ inFlight.set(id, run);+ tail = run;+ return run;+}diff --git a/server/services/codeAnimation/poster.realBrowser.test.js b/server/services/codeAnimation/poster.realBrowser.test.jsnew file mode 100644index 0000000000..15d0a9fbd1--- /dev/null+++ b/server/services/codeAnimation/poster.realBrowser.test.js@@ -0,0 +1,86 @@+// Real-Chrome check of the gallery poster readout: the page's own animation+// loop must be stopped, the poster must be renderFrame(30% of duration), and+// a controls overlay stacked over the canvas must not appear in it.+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';+import { spawn } from 'node:child_process';+import { join } from 'node:path';+import { chromium } from 'playwright-core';+import { cleanupTempDataRoots, lazyTempDataRoot } from '../../lib/mockPathsDataRoot.js';+import { _cleanupTestBrowser, _createTestArtifactsRoot, _waitForTestChrome } from '../htmlComposition/testBrowserCleanup.js';+import { resolveTestChrome } from '../../lib/browserSuiteGate.js';++vi.mock('../socket.js', () => ({ emitCodeAnimationChanged: vi.fn() }));+vi.mock('./jobStore.js', () => ({}));++const { posterCaptureScript } = await import('./poster.js');+const chrome = resolveTestChrome();++// The rAF loop paints red; renderFrame(t) paints blue proportional to t.+const film = ({ withRenderFrame }) => `<!doctype html><html><head><style>+body { margin: 0; background: #222; } canvas { display: block; width: 100vw; }+#controls { position: fixed; inset: 0 auto auto 0; width: 100vw; height: 100vh; background: rgb(0,255,0); }+</style></head><body><canvas id="film" width="1280" height="720"></canvas><div id="controls">controls</div><script>+window.ANIMATION_META = { duration: 10, fps: 24, width: 1280, height: 720 };+const ctx = document.getElementById('film').getContext('2d');+${withRenderFrame ? `window.renderFrame = (t) => { ctx.fillStyle = 'rgb(0,0,' + Math.round(t * 25.5) + ')'; ctx.fillRect(0, 0, 1280, 720); };` : ''}+const tick = () => { ctx.fillStyle = 'rgb(255,0,0)'; ctx.fillRect(0, 0, 1280, 720); requestAnimationFrame(tick); };+requestAnimationFrame(tick);+</script></body></html>`;++let proc;+let browser;+let artifacts;+const detachedChromeProcessGroupId = () => process.platform === 'win32' ? undefined : proc?.pid;++async function posterPixel(html) {+ const page = await browser.contexts()[0].newPage();+ try {+ await page.setContent(html);+ const data = await page.evaluate(posterCaptureScript(0));+ expect(typeof data).toBe('string');+ return await page.evaluate(async (b64) => {+ const image = new Image();+ image.src = `data:image/jpeg;base64,${b64}`;+ await image.decode();+ const canvas = document.createElement('canvas');+ canvas.width = image.width;+ canvas.height = image.height;+ const ctx = canvas.getContext('2d');+ ctx.drawImage(image, 0, 0);+ const [r, g, b] = ctx.getImageData(image.width / 2, image.height / 2, 1, 1).data;+ return { width: image.width, height: image.height, r, g, b };+ }, data);+ } finally {+ await page.close();+ }+}++describe.skipIf(!chrome)('Code Animation gallery poster readout in real Chrome', () => {+ beforeAll(async () => {+ const profile = join(lazyTempDataRoot('portos-code-animation-poster-'), 'chrome-test-profile');+ proc = spawn(chrome, ['--headless=new', '--mute-audio', '--no-sandbox', '--no-first-run', '--disable-background-networking', '--remote-debugging-port=0', `--user-data-dir=${profile}`, 'about:blank'], { stdio: ['ignore', 'ignore', 'pipe'], detached: process.platform !== 'win32' });+ try {+ const ws = await _waitForTestChrome(proc);+ artifacts = _createTestArtifactsRoot();+ browser = await chromium.connectOverCDP(new URL(ws).origin.replace('ws:', 'http:'), { artifactsDir: artifacts.path });+ } catch (error) {+ await _cleanupTestBrowser({ browser, proc, artifacts, cleanup: cleanupTempDataRoots, startupError: error, detachedProcessGroupId: detachedChromeProcessGroupId() });+ }+ }, 45000);++ afterAll(() => _cleanupTestBrowser({ browser, proc, artifacts, cleanup: cleanupTempDataRoots, detachedProcessGroupId: detachedChromeProcessGroupId() }), 25000);++ it('draws renderFrame at 30% of the film, scaled to 640px, without the loop or the overlay', async () => {+ const pixel = await posterPixel(film({ withRenderFrame: true }));+ expect({ width: pixel.width, height: pixel.height }).toEqual({ width: 640, height: 360 });+ expect(pixel.r).toBeLessThan(20);+ expect(pixel.g).toBeLessThan(20);+ expect(Math.abs(pixel.b - 77)).toBeLessThan(12);+ }, 20000);++ it('still reads the live canvas from a page that skipped the renderFrame contract', async () => {+ const pixel = await posterPixel(film({ withRenderFrame: false }));+ expect(pixel.r).toBeGreaterThan(200);+ expect(pixel.g).toBeLessThan(30);+ }, 20000);+});diff --git a/server/services/generatedPreview/codeAnimationPage.js b/server/services/generatedPreview/codeAnimationPage.jsnew file mode 100644index 0000000000..b685bcbd11--- /dev/null+++ b/server/services/generatedPreview/codeAnimationPage.js@@ -0,0 +1,50 @@+/**+ * Stage a generated Code Animation page for the OS-jailed composition browser.+ * The interactive preview session and the gallery poster capture both run the+ * page from here, so they load the same policy, audio global and three.js+ * vendor files.+ */+import { mkdir, writeFile } from 'node:fs/promises';+import { join } from 'node:path';+import { PATHS } from '../../lib/fileUtils.js';+import { PREVIEW_PAGE_CSP } from '../../lib/generatedPreviewSandbox.js';++const IDENT = /^[A-Za-z_$][A-Za-z0-9_$]{0,63}$/;+const SCRATCH_DIR = 'music-video-song-renders';++// Any CSP the generated page declares is replaced: the host's policy is the only one.+export function injectPolicy(html, { csp, audioGlobal, audioDataUrl }) {+ const stripped = String(html).replace(/<meta\b[^>]*http-equiv\s*=\s*["']?Content-Security-Policy["']?[^>]*>/gi, '');+ const audio = audioDataUrl && IDENT.test(String(audioGlobal || ''))+ ? `<script>window[${JSON.stringify(audioGlobal)}] = ${JSON.stringify(audioDataUrl).replace(/</g, '\\u003c')};</script>`+ : '';+ const tags = `<meta http-equiv="Content-Security-Policy" content="${csp}">${audio}`;+ const head = stripped.match(/<head[^>]*>/i);+ if (!head) return `${tags}${stripped}`;+ const at = head.index + head[0].length;+ return `${stripped.slice(0, at)}${tags}${stripped.slice(at)}`;+}++/** `name` must be unique per run; the caller removes `scratchRoot` when done. */+export async function writeComposition(name, html) {+ const scratchRoot = join(PATHS.data, SCRATCH_DIR, name);+ const composition = join(scratchRoot, 'composition');+ await mkdir(composition, { recursive: true });+ await writeFile(join(composition, 'index.html'), html);+ return { scratchRoot, directory: `${SCRATCH_DIR}/${name}/composition`, composition };+}++export async function stageCodeAnimationPage(name, html, { audioGlobal, audioDataUrl } = {}) {+ const { importsThree, injectThreeImportMap, threeStagedFiles } = await import('../codeAnimation/threeVendor.js');+ const three = importsThree(html);+ const page = injectPolicy(three ? injectThreeImportMap(html) : html, { csp: PREVIEW_PAGE_CSP, audioGlobal, audioDataUrl });+ const written = await writeComposition(name, page);+ if (three) {+ for (const file of await threeStagedFiles()) {+ const target = join(written.composition, file.rel);+ await mkdir(join(target, '..'), { recursive: true });+ await writeFile(target, file.data);+ }+ }+ return written;+}diff --git a/server/services/generatedPreview/sessions.js b/server/services/generatedPreview/sessions.jsindex 3c250191d0..0b98466631 100644--- a/server/services/generatedPreview/sessions.js+++ b/server/services/generatedPreview/sessions.js@@ -7,12 +7,13 @@* generated HTML or private media bytes.*/import { randomUUID } from 'node:crypto';-import { mkdir, rm, writeFile } from 'node:fs/promises';+import { rm, writeFile } from 'node:fs/promises';import { join } from 'node:path';import { z } from 'zod';import { PATHS } from '../../lib/fileUtils.js';import { PREVIEW_PAGE_CSP } from '../../lib/generatedPreviewSandbox.js';import { createCooperativePlayback, playbackSchema } from './cooperativePlayback.js';+import { stageCodeAnimationPage, writeComposition as writeNamedComposition } from './codeAnimationPage.js';const MAX_SESSIONS = 3;const IDLE_MS = 120_000;@@ -20,7 +21,6 @@ const RECORDING_CAP = 8 * 1024 * 1024;const SLICE_BYTES = 256 * 1024;const AUDIO_CAP = 12 * 1024 * 1024;const MUSIC_URL = /^\/data\/music\/([^/]+)$/;-const IDENT = /^[A-Za-z_$][A-Za-z0-9_$]{0,63}$/;const sessions = new Map();const opening = new Map();@@ -344,25 +344,7 @@ async function inlineLibraryAudio(url) {return `data:${mime};base64,${(await readFile(path)).toString('base64')}`;}-function injectPolicy(html, { csp, audioGlobal, audioDataUrl }) {- const stripped = String(html).replace(/<meta\b[^>]*http-equiv\s*=\s*["']?Content-Security-Policy["']?[^>]*>/gi, '');- const audio = audioDataUrl && IDENT.test(String(audioGlobal || ''))- ? `<script>window[${JSON.stringify(audioGlobal)}] = ${JSON.stringify(audioDataUrl).replace(/</g, '\\u003c')};</script>`- : '';- const tags = `<meta http-equiv="Content-Security-Policy" content="${csp}">${audio}`;- const head = stripped.match(/<head[^>]*>/i);- if (!head) return `${tags}${stripped}`;- const at = head.index + head[0].length;- return `${stripped.slice(0, at)}${tags}${stripped.slice(at)}`;-}--async function writeComposition(sessionId, html) {- const scratchRoot = join(PATHS.data, 'music-video-song-renders', `preview-${sessionId}`);- const composition = join(scratchRoot, 'composition');- await mkdir(composition, { recursive: true });- await writeFile(join(composition, 'index.html'), html);- return { scratchRoot, directory: `music-video-song-renders/preview-${sessionId}/composition`, composition };-}+const writeComposition = (sessionId, html) => writeNamedComposition(`preview-${sessionId}`, html);async function openDirectory(session, directory, { width, height, csp, screencast }) {const { openComposition } = await import('../htmlComposition/browser.js');@@ -481,24 +463,14 @@ async function startCodeAnimation(session, input) {error.code = 'NOT_FOUND';throw error;}- const { importsThree, injectThreeImportMap, threeStagedFiles } = await import('../codeAnimation/threeVendor.js');- let pageHtml = importsThree(html) ? injectThreeImportMap(html) : html;let audio = 'none';let audioDataUrl = null;if (input.withAudio) {audioDataUrl = await inlineLibraryAudio(audioUrl);audio = audioDataUrl ? 'ready' : 'unavailable';}- pageHtml = injectPolicy(pageHtml, { csp: PREVIEW_PAGE_CSP, audioGlobal: input.audioGlobal, audioDataUrl });- const written = await writeComposition(session.id, pageHtml);+ const written = await stageCodeAnimationPage(`preview-${session.id}`, html, { audioGlobal: input.audioGlobal, audioDataUrl });session.scratchRoot = written.scratchRoot;- if (importsThree(html)) {- for (const file of await threeStagedFiles()) {- const target = join(written.composition, file.rel);- await mkdir(join(target, '..'), { recursive: true });- await writeFile(target, file.data);- }- }const width = input.width || 1280;const height = input.height || 720;const page = await openDirectory(session, written.directory, { width, height, csp: PREVIEW_PAGE_CSP, screencast: true });