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: offer a three.js renderer in Code Animation with vendored addons (#10464)
[._.]/ Adam Eivyd17d5c34ea10
diff --git a/client/src/components/codeAnimation/CodeAnimationPreview.jsx b/client/src/components/codeAnimation/CodeAnimationPreview.jsxindex 6583e41e63..e299c4914d 100644--- a/client/src/components/codeAnimation/CodeAnimationPreview.jsx+++ b/client/src/components/codeAnimation/CodeAnimationPreview.jsx@@ -2,9 +2,10 @@ import { useEffect, useMemo, useRef, useState } from 'react';import { Circle, Clapperboard, Download, FileCode2, LoaderCircle, Save } from 'lucide-react';import { Link } from 'react-router';import toast from '../ui/Toast';-import { cancelCodeAnimationExport, exportCodeAnimation, getCodeAnimationPackage, uploadGalleryVideo } from '../../services/api';+import { cancelCodeAnimationExport, exportCodeAnimation, getCodeAnimationPackage, getCodeAnimationThreeVendor, uploadGalleryVideo } from '../../services/api';import { useSseProgress } from '../../hooks/useSseProgress';import { downloadBlob } from '../../lib/downloadBlob';+import { importsThree, inlineThreeVendor } from '../../lib/threeVendorImportMap';import { formatLoudness } from '../../utils/formatters';// Seconds past the film's own duration before a silent recording is abandoned@@ -36,16 +37,31 @@ const ANIMATION_CSP = ["manifest-src 'none'",].join('; ');-export function prepareAnimationHtml(html, globalName, audioDataUrl) {+// The vendored three.js modules, read once per session: they are fixed for the+// installed three version.+let threeVendorLoad = null;+const loadThreeVendor = () => {+ threeVendorLoad ??= getCodeAnimationThreeVendor({ silent: true }).then(({ files }) => files).catch((error) => {+ threeVendorLoad = null;+ throw error;+ });+ return threeVendorLoad;+};++// `vendorFiles` (a three-renderer film) inlines the vendored modules as data:+// URLs behind an import map, so the CSP gains `data:` for scripts and nothing else.+export function prepareAnimationHtml(html, globalName, audioDataUrl, vendorFiles = null) {if (!html) return html;- const policy = `<meta http-equiv="Content-Security-Policy" content="${ANIMATION_CSP}">`;+ const csp = vendorFiles ? ANIMATION_CSP.replace("script-src 'unsafe-inline'", "script-src 'unsafe-inline' data:") : ANIMATION_CSP;+ const page = vendorFiles ? inlineThreeVendor(html, vendorFiles) : html;+ const policy = `<meta http-equiv="Content-Security-Policy" content="${csp}">`;const audio = audioDataUrl? `<script>window[${scriptLiteral(globalName)}] = ${scriptLiteral(audioDataUrl)};</script>`: '';- const head = html.match(/<head[^>]*>/i);- if (!head) return `${policy}${audio}${html}`;+ const head = page.match(/<head[^>]*>/i);+ if (!head) return `${policy}${audio}${page}`;const at = head.index + head[0].length;- return `${html.slice(0, at)}${policy}${audio}${html.slice(at)}`;+ return `${page.slice(0, at)}${policy}${audio}${page.slice(at)}`;}const blobToDataUrl = (blob) => new Promise((resolve, reject) => {@@ -140,12 +156,34 @@ export default function CodeAnimationPreview({ html, audioUrl, messages, audioGlreturn () => { active = false; };}, [audioUrl, audioChoice]);- // Hold the frame back until the audio is in hand so the page boots once,- // with its audio global already set.+ // A three-renderer film needs the vendored modules inlined before it boots.+ const needsThree = useMemo(() => importsThree(html), [html]);+ const [threeVendor, setThreeVendor] = useState({ status: 'idle', files: null });+ useEffect(() => {+ let active = true;+ if (!needsThree) {+ setThreeVendor({ status: 'idle', files: null });+ return () => { active = false; };+ }+ setThreeVendor({ status: 'loading', files: null });+ loadThreeVendor()+ .then((files) => { if (active) setThreeVendor({ status: 'ready', files }); })+ .catch((error) => {+ if (!active) return;+ setThreeVendor({ status: 'failed', files: null });+ toast.error(error.message || 'Failed to load the three.js modules');+ });+ return () => { active = false; };+ }, [needsThree]);++ // Hold the frame back until the audio (and, for three, the vendored modules)+ // are in hand so the page boots once, with its globals already set.+ const vendorFiles = needsThree ? threeVendor.files : null;const srcDoc = useMemo(() => {if (!html || audioChoice == null || audio.status === 'loading') return null;- return prepareAnimationHtml(html, audioGlobal, audio.dataUrl);- }, [html, audioGlobal, audioChoice, audio]);+ if (needsThree && !vendorFiles) return null;+ return prepareAnimationHtml(html, audioGlobal, audio.dataUrl, vendorFiles);+ }, [html, audioGlobal, audioChoice, audio, needsThree, vendorFiles]);useEffect(() => {clearTimeout(recordTimerRef.current);@@ -243,6 +281,13 @@ export default function CodeAnimationPreview({ html, audioUrl, messages, audioGlif (pkg) downloadBlob(JSON.stringify(pkg, null, 2), `${fileBase}.code-animation.json`, 'application/json');};+ // A three film imports bare names the host's import map resolves, so the+ // saved file carries the vendored modules inline and runs on its own.+ const handleDownloadHtml = () => {+ if (needsThree && !vendorFiles) return toast.error('The three.js modules are still loading; try again in a moment.');+ downloadBlob(vendorFiles ? inlineThreeVendor(html, vendorFiles) : html, `${fileBase}.html`, 'text/html');+ };+if (!html) return null;const aspect = frame?.width && frame?.height ? `${frame.width} / ${frame.height}` : '16 / 9';@@ -287,7 +332,11 @@ export default function CodeAnimationPreview({ html, audioUrl, messages, audioGl</div>) : (<div className="flex h-full items-center justify-center gap-2 text-sm text-gray-400">- <LoaderCircle className="h-4 w-4 animate-spin" /> Loading audio track…+ {needsThree && threeVendor.status === 'failed' ? (+ 'The three.js modules could not be loaded; reload the page to retry.'+ ) : (+ <><LoaderCircle className="h-4 w-4 animate-spin" /> {audio.status === 'loading' ? 'Loading audio track…' : 'Loading three.js…'}</>+ )}</div>)}</div>@@ -325,7 +374,7 @@ export default function CodeAnimationPreview({ html, audioUrl, messages, audioGl)}<buttontype="button"- onClick={() => downloadBlob(html, `${fileBase}.html`, 'text/html')}+ onClick={handleDownloadHtml}className={BUTTON_SECONDARY}><FileCode2 className="h-4 w-4" /> Download HTMLdiff --git a/client/src/components/codeAnimation/CodeAnimationPreview.test.jsx b/client/src/components/codeAnimation/CodeAnimationPreview.test.jsxindex 1139f025e2..8fa921ec6e 100644--- a/client/src/components/codeAnimation/CodeAnimationPreview.test.jsx+++ b/client/src/components/codeAnimation/CodeAnimationPreview.test.jsx@@ -3,21 +3,21 @@ 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(), exportCodeAnimation: vi.fn(), cancelCodeAnimationExport: vi.fn(), getCodeAnimationPackage: vi.fn() }));+vi.mock('../../services/api', () => ({ uploadGalleryVideo: vi.fn(), exportCodeAnimation: vi.fn(), cancelCodeAnimationExport: vi.fn(), getCodeAnimationPackage: vi.fn(), getCodeAnimationThreeVendor: vi.fn() }));vi.mock('../../lib/downloadBlob', () => ({ downloadBlob: vi.fn() }));vi.mock('../../hooks/useSseProgress', () => ({ useSseProgress: vi.fn(() => ({ latest: null })) }));import CodeAnimationPreview, { prepareAnimationHtml } from './CodeAnimationPreview';-import { exportCodeAnimation, getCodeAnimationPackage } from '../../services/api';+import { exportCodeAnimation, getCodeAnimationPackage, getCodeAnimationThreeVendor } from '../../services/api';import { downloadBlob } from '../../lib/downloadBlob';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, jobId } = {}) => render(+const renderPreview = ({ audioUrl = null, jobId, html = HTML } = {}) => render(<MemoryRouter>- <CodeAnimationPreview html={HTML} audioUrl={audioUrl} messages={MESSAGES} audioGlobal="ANIMATION_AUDIO_URL" frame={{ width: 1920, height: 1080, durationSeconds: 5 }} title="Lantern" jobId={jobId} />+ <CodeAnimationPreview html={html} audioUrl={audioUrl} messages={MESSAGES} audioGlobal="ANIMATION_AUDIO_URL" frame={{ width: 1920, height: 1080, durationSeconds: 5 }} title="Lantern" jobId={jobId} /></MemoryRouter>,);@@ -57,6 +57,32 @@ describe('CodeAnimationPreview', () => {afterEach(() => vi.unstubAllGlobals());+ it('inlines the vendored three.js modules for a three film, widening the policy to data: scripts only, and downloads a standalone file (#10464)', async () => {+ const user = userEvent.setup();+ getCodeAnimationThreeVendor.mockResolvedValue({ files: [+ { path: 'three.core.js', text: 'export const REVISION = "x";' },+ { path: 'three.module.js', text: "export * from './three.core.js';" },+ ] });+ const three = "<!DOCTYPE html><html><head></head><body><script type=\"module\">import * as THREE from 'three';</script></body></html>";+ renderPreview({ html: three });+ const frame = await screen.findByTitle('Code animation preview');+ const srcDoc = frame.getAttribute('srcdoc');+ expect(srcDoc).toContain("script-src 'unsafe-inline' data:");+ expect(srcDoc).toContain("connect-src 'none'");+ expect(srcDoc.indexOf('Content-Security-Policy')).toBeLessThan(srcDoc.indexOf('type="importmap"'));+ expect(srcDoc).toContain('"three":"data:text/javascript');++ await user.click(screen.getByRole('button', { name: 'Download HTML' }));+ expect(downloadBlob.mock.calls.at(-1)[0]).toContain('type="importmap"');+ expect(downloadBlob.mock.calls.at(-1)[2]).toBe('text/html');++ // A film that does not import three never fetches the modules or gets the wider policy.+ getCodeAnimationThreeVendor.mockClear();+ renderPreview();+ expect((await screen.findAllByTitle('Code animation preview')).at(-1).getAttribute('srcdoc')).toContain("script-src 'unsafe-inline'; style-src");+ expect(getCodeAnimationThreeVendor).not.toHaveBeenCalled();+ });+it('downloads the saved portable package through the public API', async () => {const user = userEvent.setup();const pkg = { schemaVersion: 1, revisionHash: 'example-digest', files: [] };diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex 9f659ce83c..4ba85929c7 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -280,6 +280,7 @@ grep -i "what you want to do" client/src/lib/README.md| `terminalScroll.js` | Scrolling the Shell terminal by touch, wheel, and page controls. xterm 6 binds **no touch handlers at all**, and a TUI’s ALTERNATE screen buffer has no terminal scrollback, so `scrollLines()` clamps to a no-op there. Normal shell scrollback uses `scrollLines()`; alternate-screen wheel gestures are captured before xterm’s mouse listener and translated to standard PageUp/PageDown input, which OpenCode supports for its message viewport, while apps that explicitly enable terminal mouse tracking keep xterm’s native wheel path. `attachTerminalTouchScroll(terminal)` (→ detach fn) reserves one-finger panning while preserving pinch zoom and adds bounded flick momentum to normal shell scrollback; mouse-aware apps receive row-granular wheel events at the touch coordinates, and only apps without wheel support fall back to page keys. `attachTerminalWheelScroll(terminal)` handles native wheel input, and `scrollTerminalPage(terminal, direction)` powers the `SCROLL_KEYS` buttons. `measureTerminalGeometry(terminal)` takes one layout read per gesture; `planTouchScrollSteps(accumPx, rowHeightPx)` is the pure sub-row-remainder core. Wired in `useShellSession`. || `terminalTheme.js` | Pure xterm.js palette builder for the Shell terminal. `buildTerminalTheme({ bg, fg, accent, card, error, success, warning }, mode)` assembles the xterm `theme` object — base ANSI colors from the active theme's CSS vars, the rest from mode-tuned literals (`ANSI_NIGHT` bright/pastel for dark backgrounds, `ANSI_DAY` darkened/saturated so colored CLI output stays legible on daytime themes). `parseCssColorToHex(raw, fallback)` normalizes both the `15 15 15` triple form and the `rgb(7 7 7 / 0.86)` function form (used by `--port-terminal-*` tokens) to `#rrggbb`, dropping alpha. No DOM reads — `Shell.jsx` resolves CSS vars and re-applies on theme switch. || `textUtils.js` | `escapeRegExp(value)`, `countWords(text)`, `isStr(v)` and `isNonBlankStr(v)` re-exported from `server/lib/textUtils.js` — the two members the bundle has callers for (the Writers Room editor and exercise panel and the autobiography tab count words with the same `\S+` rule the server stores). Named exports rather than `export *`, so the file stays the list of what the browser actually uses. Also `pluralize(count, singular, pluralForm?)` — the shared "N item/items" phrasing helper for singular/plural counts. |+| `threeVendorImportMap.js` | Inlines the vendored three.js modules into a Code Animation page for the sandboxed preview (#10464). `importsThree(html)` detects a bare `three` / `three/addons/*` import (mirrors the server's `threeVendor.js`); `buildThreeImportMap(files)` turns the `GET /api/code-animation/vendor/three` bundle into an import map of `data:` URLs (the opaque-origin iframe cannot fetch `./vendor/*.js`), rewriting the vendored files' relative imports to `three-vendor/<path>` ids; `inlineThreeVendor(html, files)` replaces any import map in the page with it. || `brainThreads.js` | Re-export of `server/lib/brainThreads.js` — Brain THREAD statuses, `isTerminalThreadStatus` / `isThreadOverdue`, `threadNextLine` and the server's list comparator `compareThreads`, so the Threads tab and the Open Threads widget group, badge and order rows exactly as `GET /api/brain/threads` does (a *thread* is a tracked open loop, never a message thread). || `threadRefKinds.js` | Re-export of `server/lib/threadRefKinds.js` — the Brain THREAD ref vocabulary and `(kind, id)` → label/URL route table (a *thread* is a tracked topic or commitment, never a message thread). Named exports only — `threadRefLabel`/`threadRefUrl` (what the client renders with) and `THREAD_REF_KIND_IDS` / `EXTERNAL_THREAD_REF_KINDS` (what the Threads tab's ref picker enumerates and how `ThreadRefChip` picks `<a>` over `<Link>`). `pages/CatalogIngredient.jsx` renders its inbound-ref chips through `threadRefUrl`/`threadRefLabel` here instead of its own local switch, so the repo has exactly one kind→route table. || `threejsAnimation.js` | Pure pose evaluator for the declarative clip contract in `server/lib/threejsModel.js`, used by the Three.js Models preview transport. `evaluateThreejsClipPose(clip, timeSeconds)` → `{ timeSeconds, pose, activeSequenceIds, activePartIds }` where `pose` is a null-prototype partId → `{ position?, rotationDegrees?, scale?, opacity?, visible? }` map: each part+channel resolves from the one sequence that owns the instant (the window containing it, else the most recent behind it, else the next ahead), `visible` steps at the window's end rather than interpolating, and a part no sequence drives is absent so the spec renders as authored. `collectThreejsCues(clip, from, to)` returns the data-only sound cues a play loop crossed in the half-open `[from, to)` interval — a scrub calls it never, which is what makes scrubbing silent. `listThreejsClips` / `listThreejsCues` / `resolveThreejsClip` / `getThreejsClipDuration` read a spec that may have no `animation` key at all. |diff --git a/client/src/lib/index.js b/client/src/lib/index.jsindex 1a8d4b91c0..e6f8978d13 100644--- a/client/src/lib/index.js+++ b/client/src/lib/index.js@@ -235,6 +235,7 @@ export * from './terminalFit.js';export * from './terminalScroll.js';export * from './terminalTheme.js';export * from './textUtils.js';+export * from './threeVendorImportMap.js';export * from './threadRefKinds.js';export * from './brainThreads.js';export * from './threejsAnimation.js';diff --git a/client/src/lib/threeVendorImportMap.js b/client/src/lib/threeVendorImportMap.jsnew file mode 100644index 0000000000..c9b27d6655--- /dev/null+++ b/client/src/lib/threeVendorImportMap.js@@ -0,0 +1,61 @@+// Inlines the vendored three.js modules (GET /api/code-animation/vendor/three)+// into a Code Animation page so the sandboxed preview can import them. The+// preview iframe has an opaque origin and a CSP with no network, so it cannot+// load ./vendor/*.js; data: URLs in an import map can. Relative imports inside+// the vendored files are rewritten to bare ids the same map resolves.+// importsThree mirrors server/services/codeAnimation/threeVendor.js.++const BARE_THREE_IMPORT = /(?:\bfrom\s*|\bimport\s*\(?\s*)['"]three(?:\/[^'"]*)?['"]/;+const RELATIVE_SPECIFIER = /(\bfrom\s*|\bimport\s*)(['"])(\.{1,2}\/[^'"]+)\2/g;+const ADDON_PREFIX = 'addons/';+const VENDOR_ID_PREFIX = 'three-vendor/';+const IMPORT_MAP_TAG = /<script\b[^>]*type\s*=\s*["']?importmap["']?[^>]*>[\s\S]*?<\/script>/gi;++/** True when the page's script imports `three` (or one of its addons) by bare name. */+export const importsThree = (html) => BARE_THREE_IMPORT.test(String(html || ''));++const dataUrl = (text) => `data:text/javascript;charset=utf-8,${encodeURIComponent(text)}`;++function normalizePath(path) {+ const parts = [];+ for (const part of path.split('/')) {+ if (part === '..') parts.pop();+ else if (part && part !== '.') parts.push(part);+ }+ return parts.join('/');+}++function rewriteRelativeImports(path, text) {+ const dir = path.includes('/') ? path.slice(0, path.lastIndexOf('/')) : '';+ return text.replace(RELATIVE_SPECIFIER, (_match, lead, quote, specifier) =>+ `${lead}${quote}${VENDOR_ID_PREFIX}${normalizePath(dir ? `${dir}/${specifier}` : specifier)}${quote}`);+}++/**+ * The import map for a vendor bundle `[{ path, text }]`: `three`, every+ * `three/addons/<name>` the model may import, and the `three-vendor/<path>` ids+ * the vendored files use between themselves.+ */+export function buildThreeImportMap(files) {+ const imports = {};+ for (const { path, text } of files) {+ const url = dataUrl(rewriteRelativeImports(path, text));+ imports[`${VENDOR_ID_PREFIX}${path}`] = url;+ if (path === 'three.module.js') imports.three = url;+ if (path.startsWith(ADDON_PREFIX)) imports[`three/${path}`] = url;+ }+ return { imports };+}++// `<` is escaped so no module text can close the script element early.+const scriptJson = (value) => JSON.stringify(value).replace(/</g, '\\u003c');++/** The page with any import map it carries replaced by one that inlines `files`. */+export function inlineThreeVendor(html, files) {+ const stripped = String(html).replace(IMPORT_MAP_TAG, '');+ const tag = `<script type="importmap">${scriptJson(buildThreeImportMap(files))}</script>`;+ const head = stripped.match(/<head[^>]*>/i);+ if (!head) return `${tag}${stripped}`;+ const at = head.index + head[0].length;+ return `${stripped.slice(0, at)}${tag}${stripped.slice(at)}`;+}diff --git a/client/src/lib/threeVendorImportMap.test.js b/client/src/lib/threeVendorImportMap.test.jsnew file mode 100644index 0000000000..e304121ba2--- /dev/null+++ b/client/src/lib/threeVendorImportMap.test.js@@ -0,0 +1,48 @@+import { describe, expect, it } from 'vitest';+import { buildThreeImportMap, importsThree, inlineThreeVendor } from './threeVendorImportMap.js';++const decode = (url) => decodeURIComponent(url.replace(/^data:text\/javascript;charset=utf-8,/, ''));+const FILES = [+ { path: 'three.core.js', text: 'export const REVISION = "x";' },+ { path: 'three.module.js', text: "import { REVISION } from './three.core.js';\nexport { REVISION } from './three.core.js';" },+ { path: 'addons/shaders/CopyShader.js', text: 'export const CopyShader = {};' },+ { path: 'addons/postprocessing/EffectComposer.js', text: "import { Vector2 } from 'three';\nimport { CopyShader } from '../shaders/CopyShader.js';\nimport { Pass } from './Pass.js';" },+ { path: 'addons/postprocessing/Pass.js', text: 'export class Pass {}' },+];++describe('three vendor import map', () => {+ it('maps three, every addon, and the ids the vendored files use between themselves, with relative imports rewritten to those ids', () => {+ const { imports } = buildThreeImportMap(FILES);+ expect(Object.keys(imports).sort()).toEqual([+ 'three', 'three-vendor/addons/postprocessing/EffectComposer.js', 'three-vendor/addons/postprocessing/Pass.js',+ 'three-vendor/addons/shaders/CopyShader.js', 'three-vendor/three.core.js', 'three-vendor/three.module.js',+ 'three/addons/postprocessing/EffectComposer.js', 'three/addons/postprocessing/Pass.js', 'three/addons/shaders/CopyShader.js',+ ]);+ expect(imports.three).toBe(imports['three-vendor/three.module.js']);+ expect(decode(imports.three)).toBe("import { REVISION } from 'three-vendor/three.core.js';\nexport { REVISION } from 'three-vendor/three.core.js';");+ const composer = decode(imports['three/addons/postprocessing/EffectComposer.js']);+ // Bare `three` is left for the map; sibling and parent-directory imports are resolved.+ expect(composer).toContain("from 'three';");+ expect(composer).toContain("from 'three-vendor/addons/shaders/CopyShader.js'");+ expect(composer).toContain("from 'three-vendor/addons/postprocessing/Pass.js'");+ // Every rewritten target is itself in the map.+ for (const target of composer.matchAll(/'(three-vendor\/[^']+)'/g)) expect(imports).toHaveProperty([target[1]]);+ });++ it("replaces the page's own import map and cannot be broken out of through module text", () => {+ const html = '<html><head><script type="importmap">{"imports":{"three":"https://cdn.example.com/t.js"}}</script></head><body></body></html>';+ const page = inlineThreeVendor(html, [...FILES, { path: 'addons/utils/Evil.js', text: 'export default "</script><script>alert(1)</script>";' }]);+ expect(page).not.toContain('cdn.example.com');+ expect(page.match(/<script type="importmap">/g)).toHaveLength(1);+ expect(page.match(/<\/script>/g)).toHaveLength(1);+ expect(page.startsWith('<html><head><script type="importmap">')).toBe(true);+ });++ it('detects bare three imports only', () => {+ expect(importsThree("import * as THREE from 'three';")).toBe(true);+ expect(importsThree('import { Pass } from "three/addons/postprocessing/Pass.js"')).toBe(true);+ expect(importsThree("import './three-local.js'")).toBe(false);+ expect(importsThree('')).toBe(false);+ expect(importsThree(null)).toBe(false);+ });+});diff --git a/client/src/services/apiCodeAnimation.js b/client/src/services/apiCodeAnimation.jsindex cfde02c690..56557657fc 100644--- a/client/src/services/apiCodeAnimation.js+++ b/client/src/services/apiCodeAnimation.js@@ -19,6 +19,9 @@ export const listCodeAnimationProjectHistory = (id, { cursor, signal, limit = 50export const getCodeAnimationOptions = (options) => request('/code-animation/options', options);+// The vendored three.js modules (path + source) a three-renderer preview inlines.+export const getCodeAnimationThreeVendor = (options) => request('/code-animation/vendor/three', options);+// Ask a model to WRITE the brief from the chosen universe's bible and canon cast.export const generateCodeAnimationBrief = (input, options) => request('/code-animation/brief', {method: 'POST',diff --git a/docs/API.md b/docs/API.mdindex 812cc22376..290d15bac2 100644--- a/docs/API.md+++ b/docs/API.md@@ -790,7 +790,7 @@ Every mounted API prefix (see `server/index.js` for the authoritative list). Dom| `/api/sprites` | Sprite catalog / export || `/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), 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, 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/server/routes/codeAnimation.js b/server/routes/codeAnimation.jsindex 4698dd5dc9..f44958e7b8 100644--- a/server/routes/codeAnimation.js+++ b/server/routes/codeAnimation.js@@ -3,6 +3,7 @@* animation film (and optionally run it to get the HTML).** GET /api/code-animation/options formats, limits, host contract+ * GET /api/code-animation/vendor/three the vendored three.js modules the preview inlines* POST /api/code-animation/brief write a brief from the universe → { brief }* POST /api/code-animation/prompt resolve configurations → { prompt, attachments, frame }* POST /api/code-animation/generate start a provider run → 202 job@@ -40,6 +41,7 @@ import {import { startCodeAnimationExport } from '../services/codeAnimation/export.js';import { getBlenderStarterPackage } from '../services/codeAnimation/blenderStarter.js';import { exportCodeAnimationPackage } from '../services/codeAnimation/package.js';+import { readThreeVendor } from '../services/codeAnimation/threeVendor.js';import { codeAnimationPackageSchema, summarizeCodeAnimationPackage } from '../lib/codeAnimationPackage.js';import { codeAnimationProjectSchema, codeAnimationProjectPatchSchema, codeAnimationStageRunSchema } from '../lib/codeAnimationProjects.js';import { acceptProductionOutput, getProductionAcceptance, listAcceptedAssets } from '../services/codeAnimation/acceptance.js';@@ -158,6 +160,15 @@ router.get('/options', (_req, res) => {res.json(getCodeAnimationOptions());});+// The preview iframe has an opaque origin, so it cannot fetch these itself: the+// client reads them once here and inlines them. Fixed for the installed three+// version, hence cacheable.+router.get('/vendor/three', asyncHandler(async (_req, res) => {+ const { version, files } = await readThreeVendor();+ res.set('Cache-Control', 'private, max-age=86400');+ res.json({ version, files: files.filter(({ path }) => path.endsWith('.js')).map(({ path, data, sha256 }) => ({ path, sha256, text: data.toString('utf8') })) });+}));+router.post('/brief', asyncHandler(async (req, res) => {res.json(await generateCodeAnimationBrief(validateRequest(briefIdeaSchema, req.body ?? {})));}));diff --git a/server/routes/codeAnimation.test.js b/server/routes/codeAnimation.test.jsindex 568a0e4013..5c45ea95bb 100644--- a/server/routes/codeAnimation.test.js+++ b/server/routes/codeAnimation.test.js@@ -199,6 +199,17 @@ describe('Code Animation portable packages', () => {expect((await validate(rehash(foreignAuthority))).status).toBe(400);});+ it('serves the vendored three.js modules the sandboxed preview inlines (#10464)', async () => {+ const response = await request(makeApp()).get('/api/code-animation/vendor/three');+ expect(response.status).toBe(200);+ const byPath = new Map(response.body.files.map((file) => [file.path, file]));+ expect(response.body.version).toMatch(/^\d+\.\d+\.\d+$/);+ expect(byPath.get('three.module.js').text).toContain("from './three.core.js'");+ expect(byPath.get('addons/postprocessing/UnrealBloomPass.js').sha256).toMatch(/^[0-9a-f]{64}$/);+ // Only allowlisted addons leave the server; nothing else under three/examples does.+ expect(byPath.has('addons/loaders/GLTFLoader.js')).toBe(false);+ });+it('downloads exact legacy HTML with portable fields, validates it, and still reopens the job', async () => {codeAnimationRecords.set(id, savedJob());codeAnimationHtml.set(id, html);diff --git a/server/services/codeAnimation/export.js b/server/services/codeAnimation/export.jsindex b84b3f0e26..985c7dd738 100644--- a/server/services/codeAnimation/export.js+++ b/server/services/codeAnimation/export.js@@ -21,6 +21,7 @@ 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';+import { importsThree, injectThreeImportMap, threeStagedFiles } from './threeVendor.js';// The frames the composition renderer accepts (htmlCompositionContractSchema).export const EXPORT_FRAME_SIZES = Object.freeze(['1920x1080', '1080x1920', '1080x1080', '1280x720']);@@ -155,7 +156,14 @@ async function startAdmittedExport(id, deps) {const dir = join(PATHS.data, directory);await sweepStaleStagings(join(PATHS.data, EXPORT_DIRECTORY_ROOT, id));await mkdir(dir, { recursive: true });- await atomicWrite(join(dir, 'index.html'), injectExportShim(html, buildExportShim({ song })));+ // A three.js film imports `three` by bare name; the host's import map plus the+ // hashed vendored modules beside it are the only code the render may load.+ const three = importsThree(html);+ const page = three ? injectThreeImportMap(html) : html;+ await atomicWrite(join(dir, 'index.html'), injectExportShim(page, buildExportShim({ song })));+ if (three) {+ for (const { rel, data } of await threeStagedFiles()) await atomicWrite(join(dir, rel), data);+ }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.realBrowser.test.js b/server/services/codeAnimation/export.realBrowser.test.jsindex 3e897bf6c3..941e2770ff 100644--- a/server/services/codeAnimation/export.realBrowser.test.js+++ b/server/services/codeAnimation/export.realBrowser.test.js@@ -2,7 +2,7 @@// the staged document runs in real Chrome, renderComposition encodes it with// real ffmpeg, and the MP4 is compared to direct renderFrame(t) screenshots.import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';-import { existsSync } from 'node:fs';+import { existsSync, readFileSync } from 'node:fs';import { createHash } from 'node:crypto';import { execFileSync, spawn } from 'node:child_process';import { join } from 'node:path';@@ -28,6 +28,7 @@ vi.mock('./jobStore.js', () => ({const { startCodeAnimationExport } = await import('./export.js');const { renderComposition } = await import('../htmlComposition/index.js');+const { openComposition } = await import('../htmlComposition/browser.js');const { PATHS } = await import('../../lib/fileUtils.js');const chrome = [process.env.CHROME_PATH, chromium.executablePath(),@@ -66,6 +67,41 @@ window.renderFrame = (t) => {};</script></body></html>`;+// A three-renderer film (#10464): imports three and addons by bare name and+// never writes an import map, so the host's map and the vendored modules are the+// only way it can run. The post stack is the bloom + OutputPass finish the prompt teaches.+const THREE_FIXTURE = `<!doctype html><html><head><style>body { margin: 0; background: #000; }</style></head><body>+<canvas id="film" width="${WIDTH}" height="${HEIGHT}"></canvas>+<script type="module">+import * as THREE from 'three';+import { EffectComposer } from 'three/addons/postprocessing/EffectComposer.js';+import { RenderPass } from 'three/addons/postprocessing/RenderPass.js';+import { UnrealBloomPass } from 'three/addons/postprocessing/UnrealBloomPass.js';+import { OutputPass } from 'three/addons/postprocessing/OutputPass.js';+import { RoundedBoxGeometry } from 'three/addons/geometries/RoundedBoxGeometry.js';+window.ANIMATION_META = { title: 'Three', duration: 1, fps: ${FPS}, width: ${WIDTH}, height: ${HEIGHT} };+const film = document.getElementById('film');+const renderer = new THREE.WebGLRenderer({ canvas: film, antialias: false, preserveDrawingBuffer: true });+renderer.setPixelRatio(1);+renderer.setSize(${WIDTH}, ${HEIGHT}, false);+const scene = new THREE.Scene();+scene.background = new THREE.Color(0x101820);+const camera = new THREE.PerspectiveCamera(45, ${WIDTH} / ${HEIGHT}, 0.1, 50);+camera.position.set(0, 1, 6);+scene.add(new THREE.HemisphereLight(0xaaccff, 0x222233, 1.2));+const box = new THREE.Mesh(new RoundedBoxGeometry(1.6, 1.6, 1.6, 4, 0.2), new THREE.MeshStandardMaterial({ color: 0xffffff, emissive: new THREE.Color(3, 1.6, 0.8), emissiveIntensity: 0.6 }));+scene.add(box);+const composer = new EffectComposer(renderer);+composer.addPass(new RenderPass(scene, camera));+composer.addPass(new UnrealBloomPass(new THREE.Vector2(${WIDTH}, ${HEIGHT}), 0.6, 0.4, 1.2));+composer.addPass(new OutputPass());+window.renderFrame = (t) => {+ box.rotation.set(t * 3, t * 5, 0);+ box.position.x = Math.sin(t * 4) * 1.5;+ composer.render();+};+</script></body></html>`;+let proc;let browser;const decodeRaw = (input, extra = []) => execFileSync(ffmpeg, ['-v', 'error', '-i', input, ...extra, '-f', 'rawvideo', '-pix_fmt', 'rgb24', '-'], { maxBuffer: 80 * 1024 * 1024 });@@ -78,7 +114,7 @@ const meanAbsDiff = (a, b) => {describe.skipIf(!chrome || !ffmpeg || !ffprobe)('Code Animation frame-exact export with real Chrome and ffmpeg', () => {beforeAll(async () => {const profile = join(lazyTempDataRoot('portos-code-animation-export-'), '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'] });+ proc = spawn(chrome, ['--headless=new', '--mute-audio', '--no-sandbox', '--use-angle=swiftshader', '--enable-unsafe-swiftshader', '--ignore-gpu-blocklist', '--no-first-run', '--disable-background-networking', '--remote-debugging-port=0', `--user-data-dir=${profile}`, 'about:blank'], { stdio: ['ignore', 'ignore', 'pipe'] });try {const ws = await _waitForTestChrome(proc);endpoint = new URL(ws).origin.replace('ws:', 'http:');@@ -133,4 +169,36 @@ describe.skipIf(!chrome || !ffmpeg || !ffprobe)('Code Animation frame-exact expoawait context.close();}}, 120000);++ it('runs a three.js film from the vendored modules alone: repeated renderFrame(t) is pixel-identical, the render is network-free, and the files are hashed', async () => {+ state.html = THREE_FIXTURE;+ const { directory } = await startCodeAnimationExport('11111111-2222-4333-8444-555555555556', {+ enqueueJob: async ({ params }) => ({ jobId: 'three', directory: params.directory }),+ });+ const manifest = JSON.parse(readFileSync(join(PATHS.data, directory, 'dependencies.json'), 'utf8'));+ expect(manifest).toMatchObject({ network: false, packages: [{ name: 'three' }] });+ for (const { path, sha256 } of manifest.packages[0].files) {+ expect(createHash('sha256').update(readFileSync(join(PATHS.data, directory, path))).digest('hex')).toBe(sha256);+ }++ const page = await openComposition(directory);+ const shots = [];+ try {+ const contract = await page.evaluate('(() => { const c = globalThis.portosComposition; return { width: c.width, height: c.height }; })()');+ await page.send('Emulation.setDeviceMetricsOverride', { width: contract.width, height: contract.height, deviceScaleFactor: 1, mobile: false });+ // 0.25, 0.75, then 0.25 again on the same page and the same persistent scene.+ for (const t of [0.25, 0.75, 0.25]) {+ await page.evaluate(`globalThis.portosComposition.seek(${t})`);+ const shot = await page.send('Page.captureScreenshot', { format: 'png', fromSurface: true, captureBeyondViewport: false });+ shots.push(createHash('sha256').update(Buffer.from(shot.data, 'base64')).digest('hex'));+ }+ // close({ verify }) rejects when the page tried a refused (non-vendored) request.+ await page.close({ verify: true });+ } catch (error) {+ await page.close();+ throw error;+ }+ expect(shots[0]).toBe(shots[2]);+ expect(shots[0]).not.toBe(shots[1]);+ }, 120000);});diff --git a/server/services/codeAnimation/export.test.js b/server/services/codeAnimation/export.test.jsindex 0cbd0af887..35571f87eb 100644--- a/server/services/codeAnimation/export.test.js+++ b/server/services/codeAnimation/export.test.js@@ -105,6 +105,22 @@ describe('startCodeAnimationExport', () => {expect(staged).toContain('"bpm":100');});+ it('stages a three.js film with the host import map and the hashed vendored modules beside it, and a plain film with neither (#10464)', async () => {+ state.html = '<html><head><script type="importmap">{"imports":{"three":"https://cdn.example.com/three.js"}}</script></head><body><script type="module">import * as THREE from \'three\';</script></body></html>';+ await startCodeAnimationExport(JOB_ID, { enqueueJob, beatGrid: vi.fn(async () => null) });+ const dir = join(state.dataRoot, enqueueDirectory());+ const staged = await readFile(join(dir, 'index.html'), 'utf8');+ expect(staged).not.toContain('cdn.example.com');+ expect(staged).toContain('"three":"./vendor/three.module.js"');+ expect(staged.indexOf('portosComposition')).toBeLessThan(staged.indexOf('import * as THREE'));+ expect((await readFile(join(dir, 'vendor/three.module.js'), 'utf8'))).toContain("from './three.core.js'");+ expect(JSON.parse(await readFile(join(dir, 'dependencies.json'), 'utf8')).network).toBe(false);++ state.html = '<html><head></head><body><canvas></canvas></body></html>';+ await startCodeAnimationExport(JOB_ID, { enqueueJob, beatGrid: vi.fn(async () => null) });+ await expect(readFile(join(state.dataRoot, enqueueDirectory(), 'dependencies.json'), 'utf8')).rejects.toMatchObject({ code: 'ENOENT' });+ });+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() });diff --git a/server/services/codeAnimation/prompt.js b/server/services/codeAnimation/prompt.jsindex 68b28ce9eb..3f3d491b13 100644--- a/server/services/codeAnimation/prompt.js+++ b/server/services/codeAnimation/prompt.js@@ -60,7 +60,7 @@ export const CODE_ANIMATION_ASPECT_RATIOS = Object.freeze({// particle or oil-stroke style inside a real-time frame budget.export const CODE_ANIMATION_RESOLUTIONS = Object.freeze({ '720p': 720, '1080p': 1080 });-export const CODE_ANIMATION_RENDERERS = Object.freeze(['auto', 'canvas2d', 'webgl', 'svg']);+export const CODE_ANIMATION_RENDERERS = Object.freeze(['auto', 'canvas2d', 'webgl', 'svg', 'three']);export const CODE_ANIMATION_LIMITS = Object.freeze({durationMin: 3,@@ -79,11 +79,16 @@ export const CODE_ANIMATION_LIMITS = Object.freeze({audioNotesMax: 1_500,});+// The host vendors three.js and a fixed set of addons next to the page and+// writes the import map itself (threeVendor.js), so the model only imports.+const THREE_GUIDANCE = `Render with three.js (WebGL, real 3D). The host serves three locally and adds the import map: write \`<script type="module">\` and import by bare name — \`import * as THREE from 'three';\` plus only these addons: three/addons/postprocessing/{EffectComposer,RenderPass,ShaderPass,UnrealBloomPass,OutputPass,BokehPass,MaskPass,Pass}.js, three/addons/shaders/{CopyShader,LuminosityHighPassShader,OutputShader,BokehShader}.js, three/addons/geometries/RoundedBoxGeometry.js, three/addons/environments/RoomEnvironment.js (an asset-free PBR environment map) and three/addons/utils/BufferGeometryUtils.js. Do NOT write an import map or any CDN URL, and load no textures, models or fonts: build every material from colours and procedural CanvasTexture, and every shape from geometry. Create ONE renderer whose canvas is the film canvas (new THREE.WebGLRenderer({ antialias: false, preserveDrawingBuffer: true }), setPixelRatio(1), setSize(W, H, false)), ONE persistent scene and camera, and in renderFrame(t) only pose the scene analytically from t, then render once (composer.render() when you use post-processing). No simulation that accumulates between calls, no THREE.Clock, no Math.random: renderFrame(t) twice must give the same pixels. The page is a module, so it is deferred: define window.ANIMATION_META and window.renderFrame at module top level, not inside a load callback. For a cinematic finish render HDR through EffectComposer (HalfFloatType render target) and finish with OutputPass (tone mapping + sRGB): an UnrealBloomPass whose threshold sits above the sky (about 2.0 by day, 0.95 at night — a threshold of 1.0 turns every daytime frame milky), emissives driven above 1 (new THREE.Color(3, 1.6, 0.8)) so only lamps, screens and sparks glow, a depth-aware depth of field (BokehPass; focus on the subject, aperture small for wide shots and larger for close-ups, animate focus for rack focus), THREE.PCFShadowMap shadows (PCFSoftShadowMap was removed in r186) from a key light that casts shadows plus a soft fill near the camera so faces stay readable, and a vignette and light grain keyed to the frame time. Keep additive particles small and away from the lens. Software-rendered exports are slow: keep geometry modest and shadow maps at or below 2048.`;+const RENDERER_GUIDANCE = {auto: 'Pick the renderer that best serves the style: Canvas 2D for most illustrative looks, raw WebGL (no libraries) when you need thousands of primitives or shader effects.',canvas2d: 'Render with the Canvas 2D API.',webgl: 'Render with raw WebGL / WebGL2 and hand-written shaders (no libraries).',svg: 'Render with inline SVG driven from script, rasterized onto the recording canvas each frame (draw the serialized SVG via an Image) so recording still captures it.',+ three: THREE_GUIDANCE,};/** Even pixel dimensions for an aspect ratio at a short-side resolution. */@@ -227,7 +232,10 @@ const DIRECTION = `DIRECTION — make it feel like a studio short, not a tech de// pre-answer check against the failures one-shot animation code shows most.const SELF_REVIEW = `SELF-REVIEW before you answer: step through renderFrame at every beat's key frame in your head and score it honestly on character on-model, emotion readable from the face and body alone, story clear without sound, composition, depth, scale, lighting, and phone-size readability. Fix anything that would score below 8/10. Hunt especially for: stiff or dead secondary motion, sliding feet or wheels, faces that look like stickers, missing weight on stops and landings, identical-looking transitions, text overlapping during swaps, centered-on-gradient shots, muddy or unreadable text, off-model proportions, empty or static stretches, and beats the brief asked for that never made it on screen.`;-function runtimeContract({ width, height, fps, durationSeconds, interactive, hasAudio }) {+function runtimeContract({ width, height, fps, durationSeconds, interactive, hasAudio, renderer }) {+ const selfContained = renderer === 'three'+ ? 'Self-contained: no external scripts, stylesheets, fonts, images, or network requests of any kind; system fonts only. The ONE exception is the host-provided import map for three.js and its addons (see FORMAT): import those by bare name and nothing else.'+ : 'Self-contained: no external scripts, stylesheets, fonts, images, or network requests of any kind; system fonts only.';const m = CODE_ANIMATION_MESSAGES;const audioTrack = hasAudio? ' Mix the audio in: route the audio graph into a MediaStreamAudioDestinationNode and add its track to the recorded stream.'@@ -245,7 +253,7 @@ function runtimeContract({ width, height, fps, durationSeconds, interactive, has7. postMessage handshake with the embedding host (always target "*"):- once ready: \`parent.postMessage({ type: '${m.ready}', meta: window.ANIMATION_META }, '*')\`- listen for \`{ type: '${m.record}' }\` → run recordAnimation(); while recording post \`{ type: '${m.progress}', t }\` about once per second; on success post \`{ type: '${m.recorded}', blob, mimeType }\`; on failure post \`{ type: '${m.error}', message }\`.${interaction}-${interactive ? '9' : '8'}. Self-contained: no external scripts, stylesheets, fonts, images, or network requests of any kind; system fonts only. It must run from a sandboxed iframe (scripts allowed, no same-origin) and as a local file.+${interactive ? '9' : '8'}. ${selfContained} It must run from a sandboxed iframe (scripts allowed, no same-origin) and as a local file.${interactive ? '10' : '9'}. Hold ${fps}fps: pre-render static layers and textures to offscreen canvases once, reuse typed arrays, and avoid per-frame allocation.`;}@@ -260,7 +268,7 @@ ${interactive ? '10' : '9'}. Hold ${fps}fps: pre-render static layers and textur* @param {string} [input.styleNotes] - refinements on top of the universe style* @param {string|null} [input.styleGrammarId] - film style grammar id (#10253); unknown ids throw a 400* @param {{ durationSeconds: number, aspectRatio: string, resolution: string, fps: number }} input.format- * @param {'auto'|'canvas2d'|'webgl'|'svg'} [input.renderer]+ * @param {'auto'|'canvas2d'|'webgl'|'svg'|'three'} [input.renderer]* @param {boolean} [input.interactive]* @param {'none'|'procedural'} [input.soundtrack]* @param {{ name: string, durationSeconds?: number|null, notes?: string }|null} [input.audio]@@ -308,7 +316,7 @@ export function buildCodeAnimationPrompt({sections.push(`SOUND:\n${audioSection({ audio, soundtrack, durationSeconds })}`);sections.push(`FORMAT: ${format.aspectRatio} at ${width}×${height}px, ${fps}fps, ${durationSeconds}s. ${RENDERER_GUIDANCE[renderer] || RENDERER_GUIDANCE.auto}`);sections.push(DIRECTION);- sections.push(runtimeContract({ width, height, fps, durationSeconds, interactive, hasAudio: !!audio || soundtrack === 'procedural' }));+ sections.push(runtimeContract({ width, height, fps, durationSeconds, interactive, hasAudio: !!audio || soundtrack === 'procedural', renderer }));sections.push(SELF_REVIEW);sections.push(`OUTPUT: Return ONLY the finished HTML document in a single \`\`\`html fenced code block, starting with <!DOCTYPE html>. No explanation before or after it.${delivery === 'cli' ? ' Do not create or edit any files — print the document as your final answer.' : ''}`);return sections.join('\n\n');diff --git a/server/services/codeAnimation/prompt.test.js b/server/services/codeAnimation/prompt.test.jsindex 51642449e8..e0c2f31f78 100644--- a/server/services/codeAnimation/prompt.test.js+++ b/server/services/codeAnimation/prompt.test.js@@ -53,6 +53,23 @@ describe('buildCodeAnimationPrompt', () => {expect(at('Refinements for this animation')).toBeLessThan(at('SOUND:'));});+ it('teaches the three renderer to import through the host import map, and leaves the other renderers untouched (#10464)', () => {+ const input = { concept: 'A lantern drifts over a sleeping city', format };+ const three = buildCodeAnimationPrompt({ ...input, renderer: 'three' });+ expect(three).toContain("import * as THREE from 'three'");+ expect(three).toContain('host serves three locally and adds the import map');+ expect(three).toContain('three/addons/postprocessing/');+ expect(three).toContain('about 2.0 by day');+ expect(three).toContain('PCFSoftShadowMap was removed');+ // The no-library rule gains exactly one exception, and only for three.+ expect(three).toContain('The ONE exception is the host-provided import map');+ for (const renderer of ['auto', 'canvas2d', 'webgl', 'svg']) {+ const prompt = buildCodeAnimationPrompt({ ...input, renderer });+ expect(prompt).not.toContain('import map');+ expect(prompt).toContain('no external scripts, stylesheets, fonts, images, or network requests of any kind; system fonts only. It must run');+ }+ });+it('rejects an unknown style grammar id', () => {expect(() => buildCodeAnimationPrompt({ concept: 'x', format, styleGrammarId: 'no-such-style' })).toThrow(/Unknown film style grammar/);});diff --git a/server/services/codeAnimation/threeVendor.js b/server/services/codeAnimation/threeVendor.jsnew file mode 100644index 0000000000..90566b1552--- /dev/null+++ b/server/services/codeAnimation/threeVendor.js@@ -0,0 +1,134 @@+/**+ * The three.js renderer's vendored dependency set (#10464).+ *+ * A Code Animation that chooses the `three` renderer imports `three` and a small+ * allowlist of `three/addons/*` modules. The host never lets the page reach a+ * CDN: it copies these files next to the staged HTML under `vendor/`, hashes+ * them (`dependencies.json`, the same shape music-video documents record) and+ * points an import map at them. The render containment serves only files inside+ * the staged directory, so nothing outside this allowlist can be imported.+ */++import { createHash } from 'crypto';+import { createRequire } from 'module';+import { readFile } from 'fs/promises';+import { dirname, join, posix } from 'path';++// Addon modules (under three/examples/jsm) a film may import. Every relative+// import inside them must itself be listed — readThreeVendor() enforces it.+export const THREE_ADDON_ALLOWLIST = Object.freeze([+ 'environments/RoomEnvironment.js',+ 'geometries/RoundedBoxGeometry.js',+ 'postprocessing/BokehPass.js',+ 'postprocessing/EffectComposer.js',+ 'postprocessing/MaskPass.js',+ 'postprocessing/OutputPass.js',+ 'postprocessing/Pass.js',+ 'postprocessing/RenderPass.js',+ 'postprocessing/ShaderPass.js',+ 'postprocessing/UnrealBloomPass.js',+ 'shaders/BokehShader.js',+ 'shaders/CopyShader.js',+ 'shaders/LuminosityHighPassShader.js',+ 'shaders/OutputShader.js',+ 'utils/BufferGeometryUtils.js',+]);++export const THREE_VENDOR_DIRECTORY = 'vendor';+export const THREE_IMPORT_MAP = Object.freeze({+ imports: Object.freeze({+ three: `./${THREE_VENDOR_DIRECTORY}/three.module.js`,+ 'three/addons/': `./${THREE_VENDOR_DIRECTORY}/addons/`,+ }),+});++const CORE_FILES = Object.freeze(['three.module.js', 'three.core.js']);+const RELATIVE_IMPORT = /(?:^|\n)\s*(?:import|export)\b[^'"\n;]*?from\s*['"](\.{1,2}\/[^'"]+)['"]|(?:^|\n)\s*import\s*['"](\.{1,2}\/[^'"]+)['"]/g;++const sha256 = (data) => createHash('sha256').update(data).digest('hex');++/** The relative specifiers a vendored module imports, resolved against its own path. */+export function relativeImportsOf(path, text) {+ const found = [];+ for (const match of text.matchAll(RELATIVE_IMPORT)) {+ found.push(posix.normalize(posix.join(posix.dirname(path), match[1] || match[2])));+ }+ return found;+}++let cached = null;++/**+ * Read the vendored files from the installed `three` package. Paths are relative+ * to the vendor directory: `three.module.js`, `three.core.js`, `LICENSE`, and+ * `addons/<group>/<Name>.js`. The result is process-cached; the package is fixed+ * for the life of the server.+ */+export function readThreeVendor() {+ cached ??= loadThreeVendor().catch((error) => {+ cached = null;+ throw error;+ });+ return cached;+}++async function loadThreeVendor() {+ const require = createRequire(import.meta.url);+ const packageRoot = dirname(dirname(require.resolve('three')));+ const pkg = JSON.parse(await readFile(join(packageRoot, 'package.json'), 'utf8'));+ const sources = [+ ...CORE_FILES.map((name) => ({ path: name, from: join(packageRoot, 'build', name) })),+ { path: 'LICENSE', from: join(packageRoot, 'LICENSE') },+ ...THREE_ADDON_ALLOWLIST.map((name) => ({ path: `addons/${name}`, from: join(packageRoot, 'examples', 'jsm', name) })),+ ];+ const files = await Promise.all(sources.map(async ({ path, from }) => {+ const data = await readFile(from);+ return { path, data, sha256: sha256(data) };+ }));+ const known = new Set(files.map((file) => file.path));+ for (const file of files.filter((entry) => entry.path.endsWith('.js'))) {+ for (const target of relativeImportsOf(file.path, file.data.toString('utf8'))) {+ if (!known.has(target)) throw new Error(`Vendored three module ${file.path} imports ${target}, which is not on the allowlist`);+ }+ }+ return { version: pkg.version, files };+}++/**+ * The files a staged directory needs next to its index.html: the vendored+ * modules under `vendor/` plus `dependencies.json` recording each one's hash.+ * @returns {Promise<{ rel: string, data: Buffer }[]>}+ */+export async function threeStagedFiles() {+ const { version, files } = await readThreeVendor();+ const staged = files.map(({ path, data }) => ({ rel: `${THREE_VENDOR_DIRECTORY}/${path}`, data }));+ const manifest = {+ packages: [{ name: 'three', version, files: files.map(({ path, sha256: hash }) => ({ path: `${THREE_VENDOR_DIRECTORY}/${path}`, sha256: hash })) }],+ network: false,+ };+ staged.push({ rel: 'dependencies.json', data: Buffer.from(JSON.stringify(manifest)) });+ return staged;+}++const scriptJson = (value) => JSON.stringify(value).replace(/</g, '\\u003c');+const IMPORT_MAP_TAG = /<script\b[^>]*type\s*=\s*["']?importmap["']?[^>]*>[\s\S]*?<\/script>/gi;+const BARE_THREE_IMPORT = /(?:\bfrom\s*|\bimport\s*\(?\s*)['"]three(?:\/[^'"]*)?['"]/;++/** True when the page's script imports `three` (or one of its addons) by bare name. */+export function importsThree(html) {+ return BARE_THREE_IMPORT.test(String(html || ''));+}++/**+ * Replace any import map the page carries with the host's, inserted as the first+ * element of <head> (an import map only applies to modules loaded after it). The+ * model is told not to write one; the host's is authoritative either way.+ */+export function injectThreeImportMap(html) {+ const stripped = String(html).replace(IMPORT_MAP_TAG, '');+ const tag = `<script type="importmap">${scriptJson(THREE_IMPORT_MAP)}</script>`;+ const head = stripped.match(/<head[^>]*>/i);+ if (!head) return `${tag}${stripped}`;+ const at = head.index + head[0].length;+ return `${stripped.slice(0, at)}${tag}${stripped.slice(at)}`;+}diff --git a/server/services/codeAnimation/threeVendor.test.js b/server/services/codeAnimation/threeVendor.test.jsnew file mode 100644index 0000000000..f156d267a1--- /dev/null+++ b/server/services/codeAnimation/threeVendor.test.js@@ -0,0 +1,49 @@+import { describe, expect, it } from 'vitest';+import { createHash } from 'crypto';+import { THREE_ADDON_ALLOWLIST, THREE_IMPORT_MAP, importsThree, injectThreeImportMap, readThreeVendor, relativeImportsOf, threeStagedFiles } from './threeVendor.js';++describe('three.js vendor set', () => {+ it('ships only the allowlisted addons, and every relative import inside them stays inside the set', async () => {+ const { files } = await readThreeVendor();+ const paths = files.map((file) => file.path);+ expect(paths.filter((path) => path.startsWith('addons/'))).toEqual(THREE_ADDON_ALLOWLIST.map((name) => `addons/${name}`));+ // The loader already fails closed on a stray import; assert the property directly.+ const known = new Set(paths);+ for (const file of files.filter((entry) => entry.path.endsWith('.js'))) {+ for (const target of relativeImportsOf(file.path, file.data.toString('utf8'))) expect(known.has(target)).toBe(true);+ }+ // The graph is not vacuous: EffectComposer pulls CopyShader in from a sibling directory.+ const composer = files.find((file) => file.path === 'addons/postprocessing/EffectComposer.js');+ expect(relativeImportsOf(composer.path, composer.data.toString('utf8'))).toContain('addons/shaders/CopyShader.js');+ });++ it('stages every file under vendor/ with a dependencies.json whose hashes match the bytes', async () => {+ const staged = await threeStagedFiles();+ const manifest = JSON.parse(staged.find((file) => file.rel === 'dependencies.json').data.toString());+ expect(manifest.network).toBe(false);+ expect(manifest.packages[0]).toMatchObject({ name: 'three', version: expect.stringMatching(/^\d+\.\d+\.\d+$/) });+ const byRel = new Map(staged.map((file) => [file.rel, file.data]));+ for (const { path, sha256 } of manifest.packages[0].files) {+ expect(createHash('sha256').update(byRel.get(path)).digest('hex')).toBe(sha256);+ }+ expect(byRel.has('vendor/three.module.js')).toBe(true);+ expect(byRel.has('vendor/three.core.js')).toBe(true);+ });+});++describe('three import map injection', () => {+ it('detects bare three and addon imports but not look-alikes', () => {+ expect(importsThree("<script type=\"module\">import * as THREE from 'three';</script>")).toBe(true);+ expect(importsThree('import { EffectComposer } from "three/addons/postprocessing/EffectComposer.js"')).toBe(true);+ expect(importsThree("import x from './three-helpers.js'; const three = 3;")).toBe(false);+ expect(importsThree('<canvas></canvas>')).toBe(false);+ });++ it("replaces the page's own import map (a CDN one included) with the host's, first in <head>", () => {+ const html = '<html><head><script type="importmap">{"imports":{"three":"https://cdn.example.com/three.js"}}</script><title>x</title></head><body></body></html>';+ const page = injectThreeImportMap(html);+ expect(page).not.toContain('cdn.example.com');+ expect(page.startsWith(`<html><head><script type="importmap">${JSON.stringify(THREE_IMPORT_MAP)}</script>`)).toBe(true);+ expect(page.match(/type="importmap"/g)).toHaveLength(1);+ });+});