Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat(code-animation): add checked Blender production adapter (Refs #9390)
[._.]/ Adam Eivye64dcce90b1a
diff --git a/client/src/components/codeAnimation/ProductionContainment.jsx b/client/src/components/codeAnimation/ProductionContainment.jsxindex c7b1395a0b..04f29866b7 100644--- a/client/src/components/codeAnimation/ProductionContainment.jsx+++ b/client/src/components/codeAnimation/ProductionContainment.jsx@@ -10,42 +10,63 @@ export default function ProductionContainment() {const [execution, setExecution] = useState(null);const [blenderPath, setBlenderPath] = useState('');const [savedPath, setSavedPath] = useState('');+ const [mode, setMode] = useState('contained');+ const [engine, setEngine] = useState('CYCLES');+ const [acknowledged, setAcknowledged] = useState(false);const apply = (next) => {if (!next) return;setExecution(next);const path = next.tools.blender.executable || '';setSavedPath(path);setBlenderPath(path);+ setMode(next.executionMode || 'contained');+ setEngine(next.tools.blender.engine || 'CYCLES');+ setAcknowledged(next.executionMode === 'trusted-local');};useEffect(() => {let active = true;getCodeAnimationExecution({ silent: true }).then(next => { if (active) apply(next); }, () => {});return () => { active = false; };}, []);- const [save, saving] = useAsyncAction(async () => apply(await updateCodeAnimationExecutionTools({ blender: { executable: blenderPath.trim() || null } }, { silent: true })));+ const [save, saving] = useAsyncAction(async () => apply(await updateCodeAnimationExecutionTools({ blender: { executable: blenderPath.trim() || null, executionMode: mode, engine, acknowledgeHostAccess: acknowledged } }, { silent: true })));const [probe, probing] = useAsyncAction(async () => apply(await probeCodeAnimationExecution({ silent: true })));if (!execution) return null;const { mechanism, lanes, probe: result } = execution;- const dirty = blenderPath.trim() !== savedPath;+ const dirty = blenderPath.trim() !== savedPath || mode !== (execution.executionMode || 'contained') || engine !== (execution.tools.blender.engine || 'CYCLES') || acknowledged !== (execution.executionMode === 'trusted-local');return <section className="space-y-3 rounded-xl border border-port-border bg-port-card p-4">- <h2 className="text-base font-semibold">Contained execution</h2>- <p className="text-sm text-gray-400">Production code runs only inside an enforced sandbox with no network, credentials, host APIs or access outside its workspace. Without one, execution is refused.</p>+ <h2 className="text-base font-semibold">Blender execution</h2>+ <p className="text-sm text-gray-400">Contained mode is the default and refuses execution when its sandbox cannot run Blender. Trusted-local mode requires your explicit acknowledgement and runs only source you trust. No automatic fallback occurs.</p><div className="grid grid-cols-1 gap-2 text-sm md:grid-cols-3"><p>Sandbox: {mechanism.supported ? mechanism.id : <span className="text-port-warning">{mechanism.reason}</span>}</p><p>Browser lane: {lanes.browser.mechanism}</p>- <p>Blender lane: {lanes.blender.ready ? 'Test scene rendered (production adapter pending)' : <span className="text-port-warning">{lanes.blender.reason}</span>}</p>+ <p>Blender lane: {lanes.blender.ready ? 'Ready for production rendering' : <span className="text-port-warning">{lanes.blender.reason}</span>}</p></div>+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">+ <div><label htmlFor="cap-blender-mode" className="mb-1 block text-sm">Execution mode</label>+ <select id="cap-blender-mode" value={mode} disabled={saving || probing} onChange={event => { setMode(event.target.value); setAcknowledged(false); }} className="w-full rounded border border-port-border bg-port-bg p-2 text-sm">+ <option value="contained">Contained (default)</option><option value="trusted-local">Trusted local (host access)</option>+ </select></div>+ <div><label htmlFor="cap-blender-engine" className="mb-1 block text-sm">Render engine</label>+ <select id="cap-blender-engine" value={engine} disabled={saving || probing} onChange={event => setEngine(event.target.value)} className="w-full rounded border border-port-border bg-port-bg p-2 text-sm">+ <option value="CYCLES">Cycles CPU</option><option value="BLENDER_EEVEE_NEXT">EEVEE GPU</option>+ </select></div>+ </div>+ {mode === 'trusted-local' && <div className="space-y-2 rounded border border-port-warning p-3 text-sm">+ <p>{execution.trustedLocalWarning || 'Trusted-local Blender can access this account’s host filesystem, network and processes. Environment scrubbing and process supervision are not containment.'}</p>+ <label htmlFor="cap-blender-ack" className="flex items-start gap-2"><input id="cap-blender-ack" type="checkbox" checked={acknowledged} disabled={saving || probing} onChange={event => setAcknowledged(event.target.checked)} />I understand the host access and trust the source I will run.</label>+ </div>}+ <p className="text-xs text-gray-400">Cycles CPU can take substantial time for a full sequence. EEVEE needs a successful GPU check and disables motion blur to preserve stepped holds. Project version and engine must match the checked runtime.</p><div className="flex flex-wrap items-end gap-2"><div className="min-w-0 flex-1 basis-72"><label htmlFor="cap-blender-path" className="mb-1 block text-sm">Blender executable (operator-owned)</label>- <input id="cap-blender-path" value={blenderPath} onChange={event => setBlenderPath(event.target.value)} placeholder="/Applications/Blender.app/Contents/MacOS/Blender" className="w-full min-w-0 rounded border border-port-border bg-port-bg px-3 py-2 text-sm" />+ <input id="cap-blender-path" disabled={saving || probing} value={blenderPath} onChange={event => setBlenderPath(event.target.value)} placeholder="/Applications/Blender.app/Contents/MacOS/Blender" className="w-full min-w-0 rounded border border-port-border bg-port-bg px-3 py-2 text-sm" /></div>- <button type="button" className={buttonClass} disabled={!dirty || saving || probing} onClick={save}>{saving ? 'Saving…' : 'Save tool'}</button>- <button type="button" className={buttonClass} disabled={dirty || saving || probing || !mechanism.supported} onClick={probe}>{probing ? 'Checking containment…' : 'Run containment check'}</button>+ <button type="button" className={buttonClass} disabled={!dirty || saving || probing || (mode === 'trusted-local' && !acknowledged)} onClick={save}>{saving ? 'Saving…' : 'Save tool'}</button>+ <button type="button" className={buttonClass} disabled={dirty || saving || probing || (mode === 'contained' && !mechanism.supported)} onClick={probe}>{probing ? 'Checking execution…' : 'Run execution check'}</button></div>{execution.tools.blender.problem && savedPath && <p className="text-sm text-port-warning">{execution.tools.blender.problem}</p>}{result && <div role="status" className="space-y-1 text-sm">- <p>{result.refused || `${result.passed ? 'Containment proven' : 'Containment check failed'}: ${formatCount(result.checks.filter(check => check.passed).length)} of ${formatCount(result.checks.length)} checks`}</p>+ <p>{result.refused || `${result.passed ? (result.contained === false ? 'Trusted-local supervision checked' : 'Containment proven') : 'Execution check failed'}: ${formatCount(result.checks.filter(check => check.passed).length)} of ${formatCount(result.checks.length)} checks`}</p><ul className="space-y-1">{result.checks.map(check => <li key={check.id} className={check.passed ? 'text-gray-400' : 'text-port-error'}>{check.passed ? 'Pass' : 'Fail'} · {check.detail}</li>)}{result.tools?.blender && <li className={result.tools.blender.passed ? 'text-gray-400' : 'text-port-warning'}>{result.tools.blender.detail}</li>}diff --git a/client/src/components/codeAnimation/ProductionProjectForm.jsx b/client/src/components/codeAnimation/ProductionProjectForm.jsxindex b821d7a009..44f83a8ae4 100644--- a/client/src/components/codeAnimation/ProductionProjectForm.jsx+++ b/client/src/components/codeAnimation/ProductionProjectForm.jsx@@ -50,10 +50,16 @@ export default function ProductionProjectForm({ project, onSave, busy, onDirtyCh<div className="grid grid-cols-1 gap-3 sm:grid-cols-2"><div><label htmlFor="cap-renderer" className="mb-1 block text-xs text-gray-400">Renderer</label>- <select id="cap-renderer" className={inputClass} value={manifest.renderer.kind} onChange={event => setManifest(previous => ({ ...previous, renderer: { ...previous.renderer, kind: event.target.value } }))}>+ <select id="cap-renderer" className={inputClass} value={manifest.renderer.kind} onChange={event => setManifest(previous => ({ ...previous, renderer: { kind: event.target.value, version: event.target.value === 'blender' ? '4.2.0' : 'code-animation-html-v1', engine: event.target.value === 'blender' ? 'CYCLES' : null } }))}><option value="browser">Browser</option><option value="blender">Blender</option></select></div>+ {manifest.renderer.kind === 'blender' && <div>+ <label htmlFor="cap-project-engine" className="mb-1 block text-xs text-gray-400">Blender engine</label>+ <select id="cap-project-engine" className={inputClass} value={manifest.renderer.engine || 'CYCLES'} onChange={event => setManifest(previous => ({ ...previous, renderer: { ...previous.renderer, engine: event.target.value } }))}>+ <option value="CYCLES">Cycles CPU</option><option value="BLENDER_EEVEE_NEXT">EEVEE GPU</option>+ </select>+ </div>}{field('version', 'Renderer version', manifest.renderer.version, version => setManifest(previous => ({ ...previous, renderer: { ...previous.renderer, version } })), 'text', { required: true, maxLength: 128 })}{Object.entries({ width: 'Width (pixels)', height: 'Height (pixels)', fps: 'Frames per second', durationSeconds: 'Duration (seconds)' }).map(([name, label]) =>field(name, label, manifest.format[name], value => setManifest(previous => ({ ...previous, format: { ...previous.format, [name]: value } })), 'number', { required: true, min: name === 'width' || name === 'height' ? 2 : 1, step: name === 'width' || name === 'height' ? 2 : 1 }))}@@ -79,7 +85,7 @@ export default function ProductionProjectForm({ project, onSave, busy, onDirtyCh<p className="text-xs text-gray-400">Saved on this machine. Renderer selection does not change the authoring agent. Reasoning effort is independent of the budgets below.</p><h3 className="text-sm font-medium">Independent budgets</h3><div className="grid grid-cols-1 gap-3 sm:grid-cols-2">- {Object.entries({ iterations: 'Iterations', timeSeconds: 'Elapsed time (seconds)', tokens: 'Tokens', renderSeconds: 'Render time (seconds)', diskBytes: 'Retained source disk (bytes)' }).map(([name, label]) =>+ {Object.entries({ iterations: 'Iterations', timeSeconds: 'Elapsed time (seconds)', tokens: 'Tokens', renderSeconds: 'Render time (seconds)', diskBytes: 'Retained source and render disk (bytes)' }).map(([name, label]) =>field(name, label, limits[name], value => setLimits(previous => ({ ...previous, [name]: value })), 'number', { required: true, min: 1, step: 1 }))}</div><button type="submit" className="rounded bg-port-accent px-3 py-2 text-sm text-white disabled:opacity-50">{busy ? 'Saving…' : project ? 'Save project settings' : 'Create Production project'}</button>diff --git a/client/src/components/codeAnimation/ProductionProjects.jsx b/client/src/components/codeAnimation/ProductionProjects.jsxindex 408eef8ef5..3c5d034822 100644--- a/client/src/components/codeAnimation/ProductionProjects.jsx+++ b/client/src/components/codeAnimation/ProductionProjects.jsx@@ -6,7 +6,7 @@ import { useSocketSubscription } from '../../hooks/useSocketSubscription';import { usePagedCollection } from '../../hooks/usePagedCollection';import socket from '../../services/socket';import {- listCodeAnimationProjects, createCodeAnimationProject, getCodeAnimationProject,+ listCodeAnimationProjects, createCodeAnimationProject, getCodeAnimationProject, getCodeAnimationBlenderStarter,updateCodeAnimationProject, importCodeAnimationPackage, acceptCodeAnimationSource,getCodeAnimationProjectBrief, getCodeAnimationRevisionPackage, listCodeAnimationProjectHistory,} from '../../services/apiCodeAnimation';@@ -59,6 +59,14 @@ export default function ProductionProjects() {if (!projectId) navigate(`/code-animation/production/${project.id}`);return project;});+ const createBlenderStarter = () => act(async () => {+ const pkg = await getCodeAnimationBlenderStarter({ silent: true });+ const created = await createCodeAnimationProject({ manifest: pkg.manifest, budgets: { timeSeconds: 14400, renderSeconds: 14000, diskBytes: 4000000000 } }, { silent: true });+ applyProject(created);+ navigate(`/code-animation/production/${created.id}`);+ const imported = await importCodeAnimationPackage(created.id, pkg, { silent: true });+ applyProject(imported.project);+ });const importFile = event => {const file = event.target.files?.[0];event.target.value = '';@@ -88,6 +96,8 @@ export default function ProductionProjects() {<Link to="/code-animation/production" className={buttonClass}>New Production project</Link></div><p className="text-sm text-gray-400">Keep a film brief, independent budgets and immutable source revisions. Import and source acceptance stage files; rendering and evidence review are separate production stages.</p>+ <button type="button" className={buttonClass} disabled={busy} onClick={createBlenderStarter}>Create painterly Blender starter</button>+ <p className="text-xs text-gray-400">Creates original scene source at 1080p, 24 fps, 10 seconds. Importing starts no render or AI call. Check Blender execution before starting production.</p><div className="grid grid-cols-1 gap-2 sm:grid-cols-2 xl:grid-cols-3">{projects.items.map(item => <Link key={item.id} to={`/code-animation/production/${item.id}`} className="min-w-0 rounded border border-port-border p-3 hover:border-port-accent" aria-current={item.id === projectId ? 'page' : undefined}><span className="block truncate font-medium">{item.title || 'Untitled production'}</span>diff --git a/client/src/components/codeAnimation/ProductionProjects.test.jsx b/client/src/components/codeAnimation/ProductionProjects.test.jsxindex 68a6013b0f..e714ee7c1b 100644--- a/client/src/components/codeAnimation/ProductionProjects.test.jsx+++ b/client/src/components/codeAnimation/ProductionProjects.test.jsx@@ -6,7 +6,7 @@ import { MemoryRouter, Route, Routes } from 'react-router';vi.mock('../../hooks/useProviderModels', () => ({ default: () => ({ providers: [{ id: 'example-provider', name: 'Example agent', type: 'cli', command: 'claude', models: ['example-model'] }] }) }));vi.mock('../../services/socket', () => ({ default: { on: vi.fn(), off: vi.fn(), emit: vi.fn() } }));vi.mock('../../services/apiCodeAnimation', () => ({- preflightCodeAnimationProject: vi.fn(),+ preflightCodeAnimationProject: vi.fn(), getCodeAnimationBlenderStarter: vi.fn(),getCodeAnimationExecution: vi.fn(), updateCodeAnimationExecutionTools: vi.fn(), probeCodeAnimationExecution: vi.fn(),listCodeAnimationProjects: vi.fn(), createCodeAnimationProject: vi.fn(), getCodeAnimationProject: vi.fn(),updateCodeAnimationProject: vi.fn(), importCodeAnimationPackage: vi.fn(), acceptCodeAnimationSource: vi.fn(),@@ -178,30 +178,45 @@ describe('Production project rendered interactions', () => {expect(api.getCodeAnimationProject).toHaveBeenCalledWith(project.id, expect.objectContaining({ silent: true }));});+ it('requires host-access acknowledgement and saving before a trusted-local check', async () => {+ const user = userEvent.setup();+ api.getCodeAnimationExecution.mockResolvedValue(execution({ mechanism: { supported: false, reason: 'Unavailable' } }));+ renderPage('/code-animation/production');+ await screen.findByLabelText('Execution mode');+ expect(screen.getByRole('button', { name: 'Run execution check' })).toBeDisabled();+ await user.selectOptions(screen.getByLabelText('Execution mode'), 'trusted-local');+ expect(screen.getByRole('button', { name: 'Save tool' })).toBeDisabled();+ expect(screen.getByText(/Environment scrubbing and process supervision are not containment/)).toBeInTheDocument();+ await user.click(screen.getByLabelText(/I understand the host access/));+ expect(screen.getByRole('button', { name: 'Save tool' })).toBeEnabled();+ expect(screen.getByRole('button', { name: 'Run execution check' })).toBeDisabled();+ expect(api.probeCodeAnimationExecution).not.toHaveBeenCalled();+ });+it('reports refused containment and checks only a saved operator tool path', async () => {const user = userEvent.setup();renderPage('/code-animation/production');expect(await screen.findByText('Blender: Not configured.')).toBeInTheDocument();const path = '/Applications/Example.app/Contents/MacOS/Blender';await user.type(screen.getByLabelText('Blender executable (operator-owned)'), path);- expect(screen.getByRole('button', { name: 'Run containment check' })).toBeDisabled();+ expect(screen.getByRole('button', { name: 'Run execution check' })).toBeDisabled();const saved = execution({ tools: { blender: { executable: path, problem: null } }, lanes: { browser: { mechanism: 'chromium-cdp-sandbox' }, blender: { ready: false, reason: 'Run the containment check.' } } });api.updateCodeAnimationExecutionTools.mockResolvedValue(saved);await user.click(screen.getByRole('button', { name: 'Save tool' }));- await waitFor(() => expect(screen.getByRole('button', { name: 'Run containment check' })).toBeEnabled());- expect(api.updateCodeAnimationExecutionTools).toHaveBeenCalledWith({ blender: { executable: path } }, { silent: true });+ await waitFor(() => expect(screen.getByRole('button', { name: 'Run execution check' })).toBeEnabled());+ expect(api.updateCodeAnimationExecutionTools).toHaveBeenCalledWith({ blender: { executable: path, executionMode: 'contained', engine: 'CYCLES', acknowledgeHostAccess: false } }, { silent: true });api.probeCodeAnimationExecution.mockResolvedValue({ ...saved,probe: { passed: true, refused: null, checks: [{ id: 'network', passed: true, detail: 'Outbound network was refused by the sandbox.' }],tools: { blender: { passed: false, detail: 'Blender did not start under containment (failed: exit).' } } },lanes: { ...saved.lanes, blender: { ready: false, reason: 'Blender did not start under containment.' } } });- await user.click(screen.getByRole('button', { name: 'Run containment check' }));+ await user.click(screen.getByRole('button', { name: 'Run execution check' }));expect(await screen.findByText(/Containment proven: 1 of 1 checks/)).toBeInTheDocument();expect(screen.getByText('Blender did not start under containment.')).toBeInTheDocument();api.probeCodeAnimationExecution.mockResolvedValue({ ...saved,probe: { passed: true, refused: null, checks: [], tools: { blender: { passed: true, detail: 'Cycles / CPU test scene rendered.' } } },lanes: { ...saved.lanes, blender: { ready: true, reason: null } } });- await user.click(screen.getByRole('button', { name: 'Run containment check' }));- expect(await screen.findByText(/Test scene rendered \(production adapter pending\)/)).toBeInTheDocument();+ await user.click(screen.getByRole('button', { name: 'Run execution check' }));+ expect(await screen.findByText(/Ready for production rendering/)).toBeInTheDocument();expect(screen.getByText('Cycles / CPU test scene rendered.')).toBeInTheDocument();});});diff --git a/client/src/components/codeAnimation/ProductionStageRuns.jsx b/client/src/components/codeAnimation/ProductionStageRuns.jsxindex 40fe572778..9027cd42ac 100644--- a/client/src/components/codeAnimation/ProductionStageRuns.jsx+++ b/client/src/components/codeAnimation/ProductionStageRuns.jsx@@ -40,6 +40,9 @@ function StageRun({ run, busy, resumeDisabled, onResume, onCancel, currentRevisi</li>)}</ol>{reviewer && <p className="text-xs text-gray-400">Reviewed by {reviewer.providerId} · {reviewer.model || 'default model'}</p>}+ {data.renderer && <p className="text-xs text-gray-400">Blender {data.renderer.version} · {data.renderer.engine} · {data.renderer.device} · {data.renderer.executionMode}{data.renderer.contained === false ? ' — host access is not contained' : ''}</p>}+ {data.stages.filter(stage => stage.sequence?.artifact).map(stage => <a key={stage.stageRunId} href={`/data/${stage.sequence.artifact.relativePath}`} target="_blank" rel="noreferrer" className="block text-xs underline">Open rendered {stage.key} sequence</a>)}+ {data.stages.filter(stage => stage.key === 'final').flatMap(stage => stage.artifacts || []).filter(artifact => artifact.name === 'scene.blend').map(artifact => <a key={artifact.relativePath} href={`/data/${artifact.relativePath}`} download className="block text-xs underline">Download baked Blender scene and packed textures</a>)}<Verdict verdict={data.verdict} verified={inspect?.verified} />{data.findings?.length > 0 && <ul className="space-y-1 text-xs" aria-label="Findings">{data.findings.map((finding, index) => <li key={index} className={finding.severity === 'error' ? 'text-port-error' : 'text-port-warning'}>diff --git a/client/src/services/apiCodeAnimation.js b/client/src/services/apiCodeAnimation.jsindex 2ac008684c..c8daae43ca 100644--- a/client/src/services/apiCodeAnimation.js+++ b/client/src/services/apiCodeAnimation.js@@ -72,3 +72,5 @@ export const updateCodeAnimationExecutionTools = (tools, options) => request('/cexport const probeCodeAnimationExecution = (options) => request('/code-animation/execution/probe', { method: 'POST', ...options });// Explicit production workflows. Preview and final use the stored soundtrack artifact.++export const getCodeAnimationBlenderStarter = options => request('/code-animation/packages/starter/blender', options);diff --git a/docs/CODE_ANIMATION_PACKAGES.md b/docs/CODE_ANIMATION_PACKAGES.mdindex 28e5b4fd18..8082a9c382 100644--- a/docs/CODE_ANIMATION_PACKAGES.md+++ b/docs/CODE_ANIMATION_PACKAGES.md@@ -95,11 +95,17 @@ import remain available for external authoring.## Contained production execution-A job directory is not a boundary. Production package code (a Blender scene-script, a generated renderer) runs only through the contained worker in+A job directory is not a boundary. Production package code defaults to the contained worker in`server/services/codeAnimation/containedWorker.js`, under an enforced OSmechanism. Where no mechanism is available the worker refuses with 503-`CODE_ANIMATION_CONTAINMENT_UNAVAILABLE`; there is no uncontained fallback.+`CODE_ANIMATION_CONTAINMENT_UNAVAILABLE`; there is no automatic fallback.+An operator may instead explicitly select **Trusted local**, acknowledge host+access, save the setting, and pass a new execution check. This opt-in mode is+available on macOS and Linux. It runs trusted scene code with the account's+host filesystem, network and process access: environment scrubbing and process+supervision are **not containment**. Source can escape the supervised group or+write outside its workspace. Only run source you trust in that mode. Packages,+imports, project manifests and stage-run request bodies cannot grant this authority.Authoring stays outside the worker: provider transport, credentials and anyresearch access belong to the authoring route, never to execution.@@ -124,7 +130,7 @@ private `home/`. The Seatbelt profile allows:Everything else is denied, including all network (loopback and Unix socketstoo, so PortOS's API and local services are unreachable), Mach/XPC services(keychain, pasteboard, launchd) and IPC. The environment is built from scratch-(paths only), so no `PORTOS_API_TOKEN`, provider key, cloud credential or proxy+(worker paths and a synthetic worker identity only), so no `PORTOS_API_TOKEN`, provider key, cloud credential or proxysetting is inherited. The process runs in its own process group: cancellationand every limit `SIGKILL` the group, and the result reports whether the groupwas verified empty. Limits: wall time, total bytes and file count of the@@ -161,13 +167,16 @@ when it lives in a `bin/` directory, or otherwise its own directory — and noneof those may contain PortOS data or the home directory.- `GET /api/code-animation/execution` reports the platform mechanism, the- configured tools, the last containment check and each lane's readiness.- Readiness fails closed: the Blender lane is ready only after a containment- check has passed in this server process with the currently configured- executable, and its fixed test scene has rendered successfully. This is a- runtime probe, not readiness of the pending Blender production-stage adapter.-- `PUT /api/code-animation/execution/tools` sets `{ blender: { executable } }`- (`null` clears it). Host control: it chooses what a worker runs.+ configured tools, selected execution mode, last check and each lane's readiness.+ Readiness fails closed: the Blender lane is ready only after the selected+ mode's check has passed in this server process for the configured executable+ and engine, and its fixed test scene has rendered successfully. Every save+ revokes the check. Stage evidence binds its executable fingerprint, version,+ engine, mode and check timestamp; changing readiness prevents reuse.+- `PUT /api/code-animation/execution/tools` sets `{ blender: { executable,+ executionMode, engine, acknowledgeHostAccess } }`. Defaults preserve+ `contained` / `CYCLES`; `trusted-local` requires acknowledgement. `null`+ clears the executable. This remains an operator-only host-control route.- `POST /api/code-animation/execution/probe` runs the containment check ondemand (host control; never at boot; no provider call). PortOS's own Nodeinterpreter runs synthetic hostile scripts through the same staging, profile,@@ -179,30 +188,83 @@ of those may contain PortOS data or the home directory.or to the network. Positive control: the worker must still write its report.Separate runs must be terminated by the wall-time, disk, memory andcancellation limits with an empty process group. A configured Blender is then- asked to build and render a fixed 64 × 64 cube scene under containment using+ asked to build and render a fixed 64 × 64 cube scene in the saved mode using`--background --factory-startup --disable-autoexec --python-exit-code 1`.The baseline is Blender 4.2.0, matching the existing pinned rigging runtime,- with Cycles / CPU, eight samples and seed zero. Other versions remain+ with the selected Cycles / CPU or EEVEE / GPU engine, eight samples and seed zero. Other versions remainunverified and fail this probe. The check decodes the PNG, requires the exactdimensions and nonblank pixels, validates the runtime/engine/device report,and records its image SHA-256 and elapsed time. A version banner, successfulexit or `bpy` import alone cannot pass. No generated project code runs here;no dependency installation is attempted.-Known limits: Blender is granted CPU rendering only — no GPU/Metal device or-window-server access — and has not been verified under this profile on a-machine with Blender installed; a Blender that cannot render the fixed scene-contained keeps its lane refused. CPU rendering can be substantially slower-than GPU rendering; this check does not measure final-film render cost.-EEVEE/GPU profiles, production scene building, pilot/final sequences, cadence,-artifacts and the independently authored painterly starter remain tracked in-#9390. Actual repeatable 10–15 second 1080p/24fps acceptance is still required;-synthetic protocol tests are not renderer acceptance. Seatbelt (`sandbox-exec`) is deprecated by Apple but remains the-mechanism Chromium and the private security assessment harness use. A host-that already runs PortOS inside another sandbox may be unable to apply a nested-profile; the check then fails and execution stays refused. Memory and total-disk are watchdog-enforced (1 s interval in production), so a worker can-briefly exceed them before it is killed.+In trusted-local mode the check runs wall-time, workspace-disk, memory and+cancellation controls plus the fixed Blender scene; it does **not** report the+host-access adversarial checks as passing. Contained mode still requires all+adversarial checks. Cycles CPU can be substantially slower than GPU rendering.+EEVEE availability must be established by its own actual render; no engine or+execution mode is substituted silently. Seatbelt is deprecated by Apple and a+host or Blender build may not work inside its profile; that lane stays refused.+Memory and disk limits are watchdog-enforced, so brief overshoots are possible.++## Blender production adapter++**Create painterly Blender starter** creates a data-only package containing the+original `build_scene(config)` Python source for *Lantern in a Painted Garden*:+a deterministic pigment atlas, faceted paper forms, a subject animated on twos,+baked sparks on threes, and a continuously keyed camera. No external assets,+downloads, add-ons, provider calls or rendering occur on import. The default+format is 10 seconds at 1920 × 1080 / 24 fps, Blender 4.2.0 / Cycles CPU. The+project's authoring provider remains independent from its renderer.++After an explicit production start, the existing stage controller runs native+style frames, a complete low-sample pilot, evidence inspection, optional repair+through the saved authoring route, soundtrack, and final render. Preview uses+four samples; final uses sixteen. Both use a fixed seed and two CPU threads.+PortOS owns the Blender driver and loads the package's scene entrypoint; it+forces the requested format, renderer and quality settings. The driver rejects+live physics/particle simulations, requires constant subject/FX keys on the+declared cadence, measures evaluated transforms across every frame, and checks+that camera transforms vary continuously. Cycles excludes held subjects and+their children from motion blur; EEVEE disables blur to preserve the holds.+These are transform/cadence checks, not a claim that arbitrary mesh deformation+or semantic visual quality was independently reviewed.++The baked `.blend` packs original textures. Scene, report, every decoded PNG,+pilot MP4 and final sequence are immutable run artifacts, separate from accepted+source revisions. Missing frames, malformed output, unsupported runtime/engine,+revoked readiness, worker failure and cancellation cannot pass. PNG geometry+and complete decoding are checked before shared ffmpeg encoding; the result is+probed for geometry and frame count. Final output uses the existing media+history and soundtrack mux flow. Run records display engine/device/mode and+link the pilot, final movie and baked scene. Project time/render/disk budgets+apply throughout; cancellation keeps earlier accepted artifacts. Failed native+workers never fall back to browser rendering or a different engine.++Runtime/format/cadence fixtures test these contracts but do not constitute real+Blender acceptance. A bounded native run on 2026-10-01 rendered frames 25, 121+and 217 (seconds 1, 5 and 9) from package+`e9cb67e74f33291ea444cfa79dc8648120b7359596a95cf4d8b7149a7958febf`+at 1920 × 1080 / 24 fps in explicit trusted-local mode: Blender 4.2.0,+Cycles CPU, four samples, seed 17, two threads. It took 68.12 seconds end to+end (67.42 seconds in the worker), retained 11,883,500 artifact bytes, decoded+all three PNGs and saved a packed `.blend`. The driver measured all 240+frames' object/camera transforms; **only three images were rendered**.++Decoded RGBA SHA-256 values:++| Frame | SHA-256 |+|---|---|+| 25 | `fe18b712637f3bcb8259a46383ef8058cbe4d59aa70a3a29c9da233f2bbdd930` |+| 121 | `61a864e4cb370d9dd1e00135c75c8f9271ffb2b24865c876289e988da74c10a6` |+| 217 | `bfe102954770c5dc0b1a2a145c23f36dbfe466a31a8fa5d52532462babbc2e1c` |++The native stills are a rough, faceted and noisy study, **not polished painterly+acceptance**. #9390 remains open for the full 10–15 second 1080p/24fps pilot+and final sequence, repeated sampled-frame comparison, actual EEVEE/GPU+validation, and visual-quality refinement/review. The measured CPU cost did+not justify silently starting a long full-sequence run during this bounded+validation. No synthetic fixture substitutes for those remaining checks.The browser lane does not use this worker. It reuses the HTML-compositionrenderer sandbox (`server/services/htmlComposition/browser.js`): an in-memorydiff --git a/server/lib/codeAnimationContainment.js b/server/lib/codeAnimationContainment.jsindex 72982d6762..551bca4bac 100644--- a/server/lib/codeAnimationContainment.js+++ b/server/lib/codeAnimationContainment.js@@ -2,8 +2,9 @@* Containment contract for Code Animation production workers (#9388).** A job directory is not a boundary. Generated or imported package code runs- * only under an enforced OS mechanism; when none is available execution is- * refused, never downgraded to an uncontained spawn. The supported mechanism+ * under an enforced OS mechanism by default; unavailable containment never+ * automatically falls back. An explicit operator-owned trusted-local Blender+ * mode is supervised but is not a security boundary. The supported mechanism* is macOS Seatbelt or Linux bubblewrap with a process-denying seccomp* filter. Windows and hosts missing the prerequisites refuse.*@@ -33,7 +34,11 @@ export const codeAnimationWorkerLimitsSchema = z.object({export const codeAnimationExecutionToolsSchema = z.object({blender: z.object({executable: z.string().trim().max(4096).nullable(),- }).strict(),+ executionMode: z.enum(['contained', 'trusted-local']).default('contained'),+ engine: z.enum(['CYCLES', 'BLENDER_EEVEE_NEXT']).default('CYCLES'),+ acknowledgeHostAccess: z.boolean().default(false),+ }).strict().refine(value => value.executionMode !== 'trusted-local' || value.acknowledgeHostAccess,+ 'Trusted-local Blender requires explicit acknowledgement of host filesystem, network and process access.'),}).strict();/**@@ -134,10 +139,13 @@ export function codeAnimationWorkerEnv(workspace) {return {PATH: '/usr/bin:/bin', HOME: home, TMPDIR: tmp, TMP: tmp, TEMP: tmp,LANG: 'en_US.UTF-8', LC_ALL: 'en_US.UTF-8',+ // Fixed synthetic identity: Blender's glog startup otherwise queries the+ // host account database. This never inherits the operator's username.+ USER: 'worker', LOGNAME: 'worker',XDG_CONFIG_HOME: posix.join(home, 'config'), XDG_CACHE_HOME: posix.join(home, 'cache'), XDG_DATA_HOME: posix.join(home, 'data'),// Blender reads user add-ons/startup files from here; keep them private and empty.BLENDER_USER_RESOURCES: posix.join(home, 'blender'),- // Workers have no network; an OpenSSL build's config outside the sandbox is not needed.+ // Do not load the host OpenSSL configuration, including in trusted-local mode.OPENSSL_CONF: '/dev/null',PORTOS_WORKER_INPUT: posix.join(workspace, 'input'),PORTOS_WORKER_OUTPUT: posix.join(workspace, 'output'),diff --git a/server/routes/codeAnimation.js b/server/routes/codeAnimation.jsindex fd0339590a..c43fcda37a 100644--- a/server/routes/codeAnimation.js+++ b/server/routes/codeAnimation.js@@ -33,6 +33,7 @@ import {startCodeAnimationGeneration,} from '../services/codeAnimation/index.js';import { startCodeAnimationExport } from '../services/codeAnimation/export.js';+import { getBlenderStarterPackage } from '../services/codeAnimation/blenderStarter.js';import { exportCodeAnimationPackage } from '../services/codeAnimation/package.js';import { codeAnimationPackageSchema, summarizeCodeAnimationPackage } from '../lib/codeAnimationPackage.js';import { codeAnimationProjectSchema, codeAnimationProjectPatchSchema, codeAnimationStageRunSchema } from '../lib/codeAnimationProjects.js';@@ -244,6 +245,8 @@ router.get('/projects/:id/revisions/:revisionId/package', asyncHandler(async (re// External harness handoff is data-only. Validation grants no execution and// neither stages imported files nor changes a saved/accepted animation.+router.get('/packages/starter/blender', asyncHandler(async (_req, res) => res.json(await getBlenderStarterPackage())));+router.post('/packages/validate', (req, res) => {const pkg = validateRequest(codeAnimationPackageSchema, req.body);res.json(summarizeCodeAnimationPackage(pkg));diff --git a/server/routes/codeAnimation.test.js b/server/routes/codeAnimation.test.jsindex a8395d0e46..adb83264d4 100644--- a/server/routes/codeAnimation.test.js+++ b/server/routes/codeAnimation.test.js@@ -183,6 +183,19 @@ describe('Code Animation portable packages', () => {};const validate = (value) => request(makeApp()).post('/api/code-animation/packages/validate').send(value);+ it('serves the original Blender starter as an unchanged data-only package', async () => {+ const response = await request(makeApp()).get('/api/code-animation/packages/starter/blender');+ expect(response.status).toBe(200);+ expect(response.body.manifest).toMatchObject({ renderer: { kind: 'blender', version: '4.2.0', engine: 'CYCLES' }, format: { width: 1920, height: 1080, fps: 24, durationSeconds: 10 } });+ expect((await validate(response.body)).body.executed).toBe(false);+ expect(response.body.files[0].content).toContain('def build_scene(config):');+ expect(runPromptThroughProvider).not.toHaveBeenCalled();+ expect(enqueueJob).not.toHaveBeenCalled();+ const foreignAuthority = structuredClone(response.body);+ foreignAuthority.manifest.renderer.executionMode = 'trusted-local';+ expect((await validate(rehash(foreignAuthority))).status).toBe(400);+ });+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/routes/codeAnimationExecution.test.js b/server/routes/codeAnimationExecution.test.jsindex a93f25fc2a..4d0c150634 100644--- a/server/routes/codeAnimationExecution.test.js+++ b/server/routes/codeAnimationExecution.test.js@@ -69,12 +69,12 @@ describe('Code Animation execution capability', () => {const tool = await executableAt(join(dir, 'Blender.app', 'Contents', 'MacOS'));const { status, body } = await put(tool);expect(status).toBe(200);- expect(settings.current.codeAnimationExecution).toEqual({ blender: { executable: await realpath(tool) } });+ expect(settings.current.codeAnimationExecution).toEqual({ blender: { executable: await realpath(tool), executionMode: 'contained', engine: 'CYCLES', acknowledgeHostAccess: false } });expect(body.tools.blender).toMatchObject({ executable: await realpath(tool), problem: null });expect(body.lanes.blender.ready).toBe(false);await put(null);- expect(settings.current.codeAnimationExecution).toEqual({ blender: { executable: null } });+ expect(settings.current.codeAnimationExecution).toEqual({ blender: { executable: null, executionMode: 'contained', engine: 'CYCLES', acknowledgeHostAccess: false } });});it.skipIf(supported)('refuses the containment check where no enforced mechanism exists', async () => {@@ -102,7 +102,7 @@ describe('Code Animation execution capability', () => {});expect(body.probe.passed).toBe(true);expect(body.probe.tools.blender).toMatchObject({ passed: false, version: null });- expect(body.lanes.blender).toEqual({ ready: false, reason: 'Blender did not render the supported test scene under containment.' });+ expect(body.lanes.blender).toEqual({ ready: false, reason: 'Blender did not render the supported test scene in contained mode.' });// Every owned workspace was removed, including the terminated ones.expect(await readdir(join(PATHS.data, 'code-animation-workspaces'))).toEqual([]);}, 60_000);diff --git a/server/services/codeAnimation/blenderDriver.js b/server/services/codeAnimation/blenderDriver.jsnew file mode 100644index 0000000000..7108437139--- /dev/null+++ b/server/services/codeAnimation/blenderDriver.js@@ -0,0 +1,100 @@+/** Owned Blender driver. Package source only supplies build_scene(config). */+export const BLENDER_DRIVER = String.raw`import bpy, json, os, runpy, math+root = os.environ['PORTOS_WORKER_INPUT']+out = os.environ['PORTOS_WORKER_OUTPUT']+with open(os.path.join(root, 'portos-render.json')) as handle:+ config = json.load(handle)+if bpy.app.version_string != config['version']:+ raise RuntimeError('Blender version does not match checked runtime')+bpy.ops.wm.read_factory_settings(use_empty=True)+namespace = runpy.run_path(os.path.join(root, config['entrypoint']))+if not callable(namespace.get('build_scene')):+ raise RuntimeError('Scene entrypoint must define build_scene(config)')+namespace['build_scene'](config)+scene = bpy.context.scene+if not scene.camera:+ raise RuntimeError('Scene needs a camera')+# No live simulations: portable revisions must bake simulation/FX into keys.+for obj in scene.objects:+ if obj.particle_systems or obj.rigid_body or any(m.type in ('CLOTH', 'FLUID', 'SOFT_BODY', 'DYNAMIC_PAINT') for m in obj.modifiers):+ raise RuntimeError('Bake simulations and remove live physics before rendering')+for group in bpy.data.node_groups:+ if any(node.bl_idname.startswith('GeometryNodeSimulation') for node in group.nodes):+ raise RuntimeError('Bake Geometry Nodes simulations into immutable geometry/keyframes')+scene.render.engine = config['engine']+scene.cycles.device = 'CPU'+scene.cycles.samples = config['samples']+scene.cycles.seed = config['seed']+scene.cycles.use_animated_seed = False+scene.cycles.use_denoising = False+scene.eevee.taa_render_samples = config['samples']+scene.render.resolution_x = config['width']+scene.render.resolution_y = config['height']+scene.render.resolution_percentage = 100+scene.render.fps = config['fps']+scene.render.fps_base = 1+scene.frame_start = 1+scene.frame_end = config['frameCount']+scene.render.image_settings.file_format = 'PNG'+scene.render.image_settings.color_mode = 'RGBA'+scene.render.image_settings.color_depth = '8'+scene.render.use_file_extension = True+scene.render.use_motion_blur = True+scene.render.motion_blur_shutter = 0.35+scene.render.threads_mode = 'FIXED'+scene.render.threads = 2+subjects = [o for o in scene.objects if o.get('portos_cadence') in (2, 3)]+if not subjects:+ raise RuntimeError('Tag at least one baked subject/FX object with portos_cadence=2 or 3')+for obj in subjects:+ step = int(obj['portos_cadence'])+ curves = obj.animation_data.action.fcurves if obj.animation_data and obj.animation_data.action else []+ if not curves or any(p.interpolation != 'CONSTANT' or (round(p.co.x) - 1) % step != 0 for c in curves for p in c.keyframe_points):+ raise RuntimeError('Stepped subjects/FX need constant keys on their declared cadence')+ # Cycles excludes held subjects from shutter interpolation. EEVEE motion+ # blur is disabled because it cannot independently exclude held objects.+ obj.cycles.use_motion_blur = False+ for child in obj.children_recursive:+ child.cycles.use_motion_blur = False+if config['engine'] != 'CYCLES':+ scene.render.use_motion_blur = False+camera_curves = scene.camera.animation_data.action.fcurves if scene.camera.animation_data and scene.camera.animation_data.action else []+if not camera_curves or any(p.interpolation == 'CONSTANT' for c in camera_curves for p in c.keyframe_points):+ raise RuntimeError('Camera needs continuous, non-constant baked keyframes')+# Measure evaluated transforms across EVERY frame, rather than trusting tags.+transforms = {o.name: [] for o in subjects}+camera_transforms = []+for frame in range(1, config['frameCount'] + 1):+ scene.frame_set(frame)+ depsgraph = bpy.context.evaluated_depsgraph_get()+ for obj in subjects:+ transforms[obj.name].append([round(v, 6) for row in obj.evaluated_get(depsgraph).matrix_world for v in row])+ camera_transforms.append([round(v, 6) for row in scene.camera.evaluated_get(depsgraph).matrix_world for v in row])+for obj in subjects:+ values = transforms[obj.name]+ step = int(obj['portos_cadence'])+ if any(values[i] != values[i - i % step] for i in range(len(values))):+ raise RuntimeError('Evaluated subject/FX transforms violate stepped holds')+if any(a == b for a, b in zip(camera_transforms, camera_transforms[1:])):+ raise RuntimeError('Camera movement is not continuous across the sequence')+# Pack original textures into the immutable scene artifact; no live caches.+for image in bpy.data.images:+ if image.source in ('FILE', 'GENERATED') and image.has_data:+ image.pack()+bpy.ops.wm.save_as_mainfile(filepath=os.path.join(out, 'scene.blend'))+for frame in config['frames']:+ scene.frame_set(frame)+ scene.render.filepath = os.path.join(out, 'frame-%06d.png' % frame)+ bpy.ops.render.render(write_still=True)+device, backend = 'CPU', 'CPU'+if config['engine'] != 'CYCLES':+ import gpu+ device, backend = 'GPU', gpu.platform.backend_type_get()+report = dict(version=bpy.app.version_string, engine=scene.render.engine, device=device, backend=backend,+ width=scene.render.resolution_x, height=scene.render.resolution_y, fps=scene.render.fps,+ frames=config['frames'], frameCount=config['frameCount'], samples=config['samples'], seed=scene.cycles.seed,+ cadence=[dict(name=o.name, step=int(o['portos_cadence']), holdsVerified=True, motionBlur=False) for o in subjects],+ cameraSmooth=True, motionBlur=scene.render.use_motion_blur, baked=True)+with open(os.path.join(out, 'report.json'), 'w') as handle:+ json.dump(report, handle)+`;diff --git a/server/services/codeAnimation/blenderProbe.js b/server/services/codeAnimation/blenderProbe.jsindex d99152d648..b06458c9a4 100644--- a/server/services/codeAnimation/blenderProbe.js+++ b/server/services/codeAnimation/blenderProbe.js@@ -9,24 +9,25 @@ import { runContainedWorker } from './containedWorker.js';// Match the existing supported bpy baseline; this is not a claim that an import// or a newer Blender version proves render compatibility.const VERSION = RIGGING_RUNTIME.moduleVersion;-const reportSchema = z.object({- version: z.literal(VERSION), engine: z.literal('CYCLES'), device: z.literal('CPU'),- backend: z.literal('CPU'), width: z.literal(64), height: z.literal(64),+const reportSchema = engine => z.object({+ version: z.literal(VERSION), engine: z.literal(engine), device: z.literal(engine === 'CYCLES' ? 'CPU' : 'GPU'),+ backend: engine === 'CYCLES' ? z.literal('CPU') : z.enum(['OPENGL', 'METAL', 'VULKAN']), width: z.literal(64), height: z.literal(64),seed: z.literal(0), samples: z.literal(8), frame: z.literal(1),}).strict();-const SCENE = `import bpy, json, os+const sceneSource = engine => `import bpy, json, osfrom mathutils import Vectorif bpy.app.version_string != ${JSON.stringify(VERSION)}:raise RuntimeError("Unsupported Blender version; expected ${VERSION}")bpy.ops.wm.read_factory_settings(use_empty=True)scene = bpy.context.scene-scene.render.engine = 'CYCLES'+scene.render.engine = ${JSON.stringify(engine)}scene.cycles.device = 'CPU'scene.cycles.samples = 8scene.cycles.seed = 0scene.cycles.use_animated_seed = Falsescene.cycles.use_denoising = False+scene.eevee.taa_render_samples = 8scene.render.resolution_x = 64scene.render.resolution_y = 64scene.render.resolution_percentage = 100@@ -46,9 +47,13 @@ bpy.context.object.data.size = 4out = os.environ['PORTOS_WORKER_OUTPUT']scene.render.filepath = os.path.join(out, 'probe.png')bpy.ops.render.render(write_still=True)+device, backend = 'CPU', 'CPU'+if scene.render.engine != 'CYCLES':+ import gpu+ device, backend = 'GPU', gpu.platform.backend_type_get()with open(os.path.join(out, 'report.json'), 'w') as handle:json.dump(dict(version=bpy.app.version_string, engine=scene.render.engine,- device=scene.cycles.device, backend='CPU', width=scene.render.resolution_x,+ device=device, backend=backend, width=scene.render.resolution_x,height=scene.render.resolution_y, seed=scene.cycles.seed,samples=scene.cycles.samples, frame=scene.frame_current), handle)`;@@ -56,23 +61,24 @@ with open(os.path.join(out, 'report.json'), 'w') as handle:/*** A successful exit/version banner is insufficient: require a decoded,* nonuniform 64px PNG and exact runtime/engine evidence from the fixed script.- * Only CPU Cycles is probed: EEVEE/GPU access is not granted by containment.+ * Probe the operator-selected engine in the explicitly selected worker mode.+ * Failed EEVEE/GPU access never silently substitutes CPU Cycles or another mode.* Injection covers failure contracts on CI; fixtures are not renderer proof.*/-export async function probeBlenderRender({ executable, fingerprint }, workspaceRoot, { worker = runContainedWorker, signal } = {}) {+export async function probeBlenderRender({ executable, fingerprint }, workspaceRoot, { worker = runContainedWorker, signal, engine = 'CYCLES', executionMode = 'contained' } = {}) {if (!executable) return null;let evidence = null;let invalidOutput = false;const run = await worker({- tool: { executable, argv: entry => ['--background', '--factory-startup', '--disable-autoexec', '--python-exit-code', '1', '--python', entry] },- workspaceRoot, entrypoint: 'probe.py', files: [{ path: 'probe.py', content: SCENE }], signal,+ tool: { executable, argv: entry => ['--background', '--factory-startup', '--disable-autoexec', '--threads', '2', '--python-exit-code', '1', '--python', entry] },+ workspaceRoot, entrypoint: 'probe.py', files: [{ path: 'probe.py', content: sceneSource(engine) }], signal,limits: { wallSeconds: 120, diskBytes: 64 * 1024 * 1024, maxFiles: 1000 },onOutput: async (directory, outputs) => {const report = outputs.find(file => file.path === 'report.json');const png = outputs.find(file => file.path === 'probe.png');if (!report || report.bytes > 16_384 || !png || png.bytes > 1024 * 1024) { invalidOutput = true; return; }// Decode under a strict pixel cap as well as the worker's file-size cap.- const parsed = reportSchema.safeParse(JSON.parse(await readFile(join(directory, 'report.json'), 'utf8')));+ const parsed = reportSchema(engine).safeParse(JSON.parse(await readFile(join(directory, 'report.json'), 'utf8')));if (!parsed.success) { invalidOutput = true; return; }const bytes = await readFile(join(directory, 'probe.png'));const { default: sharp } = await import('sharp');@@ -91,11 +97,11 @@ export async function probeBlenderRender({ executable, fingerprint }, workspaceR}).catch(() => ({ status: 'failed', reason: 'probe-or-output-failed', processGroupClear: false }));const passed = run.status === 'completed' && run.processGroupClear === true && !invalidOutput && Boolean(evidence);return {- executable, fingerprint, passed, version: passed ? evidence.version : null,+ executable, fingerprint, executionMode, contained: executionMode === 'contained', engine, passed, version: passed ? evidence.version : null,render: passed ? evidence : null,durationMs: run.durationMs ?? null,detail: passed- ? `Blender ${VERSION} rendered a 64 × 64 scene with Cycles / CPU under containment. CPU rendering may be slow; EEVEE, GPU rendering and production-sequence acceptance remain unverified.`- : `Blender render check failed: expected ${VERSION}, Cycles / CPU and a valid nonblank 64 × 64 PNG inside containment. A version banner or bpy import is insufficient.`,+ ? `Blender ${VERSION} rendered a 64 × 64 scene with ${engine} / ${evidence.device} / ${evidence.backend} in ${executionMode} mode. ${executionMode === 'trusted-local' ? 'Host access is not contained. ' : ''}This proves fixed-scene readiness; production-sequence acceptance remains separate. CPU Cycles may be slow.`+ : `Blender render check failed: expected ${VERSION}, ${engine} and a valid nonblank 64 × 64 PNG in ${executionMode} mode. A version banner or bpy import is insufficient; no fallback was attempted.`,};}diff --git a/server/services/codeAnimation/blenderProbe.test.js b/server/services/codeAnimation/blenderProbe.test.jsindex 1e6e5738aa..4eac952615 100644--- a/server/services/codeAnimation/blenderProbe.test.js+++ b/server/services/codeAnimation/blenderProbe.test.js@@ -32,9 +32,9 @@ describe('Blender render readiness (synthetic worker evidence, not real Blenderexpect(result).toMatchObject({ passed: true, version: '4.2.0', render: { ...report, imageSha256: expect.stringMatching(/^[a-f0-9]{64}$/) }, durationMs: 12 });const options = worker.mock.calls[0][0];expect(options).toMatchObject({ entrypoint: 'probe.py', workspaceRoot: '/example/workspaces', signal: controller.signal });- expect(options.tool.argv('/example/probe.py')).toEqual(['--background', '--factory-startup', '--disable-autoexec', '--python-exit-code', '1', '--python', '/example/probe.py']);+ expect(options.tool.argv('/example/probe.py')).toEqual(['--background', '--factory-startup', '--disable-autoexec', '--threads', '2', '--python-exit-code', '1', '--python', '/example/probe.py']);expect(options.files[0].content).toContain('bpy.ops.render.render(write_still=True)');- expect(result.detail).toContain('production-sequence acceptance remain unverified');+ expect(result.detail).toContain('production-sequence acceptance remains separate');});// These uniquely guard the native-renderer/API boundary: a successful exitdiff --git a/server/services/codeAnimation/blenderRender.js b/server/services/codeAnimation/blenderRender.jsnew file mode 100644index 0000000000..1f14e2b165--- /dev/null+++ b/server/services/codeAnimation/blenderRender.js@@ -0,0 +1,147 @@+/** Native sequence adapter; authority comes only from checked machine settings. */+import { randomUUID, createHash } from 'node:crypto';+import { readFile, mkdir, copyFile, rm, stat } from 'node:fs/promises';+import { join } from 'node:path';+import { constants } from 'node:fs';+import { PATHS } from '../../lib/paths.js';+import { ServerError } from '../../lib/errorHandler.js';+import { findFfmpeg, runFfmpegProcess, H264_ENCODE_ARGS, BT709_CONTAINER_ARGS, bt709TagFilter,+ probeVideoGeometry, probeFrameCount, generateThumbnail } from '../../lib/ffmpeg.js';+import { mutateVideoHistory } from '../videoGen/history.js';+import { writeRunArtifact } from './projectFiles.js';+import { resolveBlenderExecution } from './execution.js';+import { BLENDER_DRIVER } from './blenderDriver.js';++const fail = message => new ServerError(message, { status: 422, code: 'CODE_ANIMATION_BLENDER_RENDER_FAILED' });+const hash = bytes => createHash('sha256').update(bytes).digest('hex');+const frameName = frame => `frame-${String(frame).padStart(6, '0')}.png`;++/** Validate every image and persist the baked scene, report and real sequence. */+export async function renderBlenderSequence({ revision, runtime, projectId, runId, signal, reserve, phase, times = [], captureTimes = [], diskBytes, wallSeconds }, {+ resolveRuntime = resolveBlenderExecution, retain = writeRunArtifact,+} = {}) {+ const checked = await resolveRuntime(revision.manifest.renderer, runtime);+ signal?.throwIfAborted();+ const source = revision.files.find(file => file.path === revision.entryPath);+ if (!source || source.encoding !== 'utf8' || !revision.entryPath.endsWith('.py')) throw fail('Blender scene entrypoint must be a UTF-8 Python file defining build_scene(config)');+ const format = revision.manifest.format;+ const count = Math.round(format.durationSeconds * format.fps);+ if (!count || Math.abs(count / format.fps - format.durationSeconds) > 1e-8) throw fail('Duration must land on the frame grid');+ const frames = phase === 'style' ? [...new Set(captureTimes.map(t => Math.min(count, 1 + Math.round(t * format.fps))))] : Array.from({ length: count }, (_, i) => i + 1);+ const config = { ...format, version: checked.provenance.version, engine: checked.provenance.engine,+ frameCount: count, frames, seed: revision.manifest.seed ?? 0, samples: phase === 'final' ? 16 : 4,+ entrypoint: revision.entryPath };+ if (revision.files.some(file => ['portos-driver.py', 'portos-render.json'].includes(file.path))) throw fail('Package uses a reserved driver filename');+ const id = randomUUID();+ const artifacts = [];+ const samples = [];+ const captures = [];+ let report;+ let encoded = null;+ const persist = async (name, bytes) => {+ await reserve(bytes.length);+ const artifact = await retain(projectId, runId, `${phase}-${id}-${name}`, bytes);+ artifacts.push({ name, ...artifact });+ return artifact;+ };+ const run = await checked.worker({+ tool: { executable: checked.executable, argv: entry => ['--background', '--factory-startup', '--disable-autoexec', '--threads', '2', '--python-exit-code', '1', '--python', entry] },+ workspaceRoot: join(PATHS.data, 'code-animation-workspaces'), entrypoint: 'portos-driver.py', signal,+ files: [...revision.files, { path: 'portos-driver.py', content: BLENDER_DRIVER }, { path: 'portos-render.json', content: JSON.stringify(config) }],+ limits: { wallSeconds: Math.max(1, Math.min(86400, Math.ceil(wallSeconds))), diskBytes: Math.max(1024, diskBytes) },+ onOutput: async (directory, outputs) => {+ signal?.throwIfAborted();+ const metadata = outputs.find(file => file.path === 'report.json');+ if (!metadata || metadata.bytes > 128 * 1024) throw fail('Missing or oversized Blender report');+ report = JSON.parse(await readFile(join(directory, 'report.json'), 'utf8'));+ if (report.version !== config.version || report.engine !== config.engine || report.device !== checked.provenance.device+ || report.backend !== checked.provenance.backend || report.width !== format.width || report.height !== format.height+ || report.fps !== format.fps || report.frameCount !== count || report.samples !== config.samples || report.seed !== config.seed+ || JSON.stringify(report.frames) !== JSON.stringify(frames) || !report.baked || !report.cameraSmooth+ || !Array.isArray(report.cadence) || !report.cadence.length+ || report.cadence.some(item => ![2, 3].includes(item.step) || item.holdsVerified !== true || item.motionBlur !== false)) throw fail('Blender output does not match the requested runtime, cadence or format');+ const expected = new Set(['report.json', 'scene.blend', ...frames.map(frameName)]);+ if (outputs.length !== expected.size || outputs.some(file => !expected.has(file.path))) throw fail('Blender output files do not match the requested sequence');+ const { default: sharp } = await import('sharp');+ for (const frame of frames) {+ signal?.throwIfAborted();+ const bytes = await readFile(join(directory, frameName(frame)));+ const image = sharp(bytes, { limitInputPixels: format.width * format.height });+ const meta = await image.metadata();+ if (meta.format !== 'png' || meta.width !== format.width || meta.height !== format.height) throw fail('Blender frame geometry is invalid');+ // Full decode catches truncated payloads; hash pixels for repeatability.+ const pixels = await image.ensureAlpha().raw().toBuffer();+ const small = await sharp(pixels, { raw: { width: format.width, height: format.height, channels: 4 } }).resize(16, 9).greyscale().raw().toBuffer();+ const mean = small.reduce((sum, value) => sum + value, 0) / small.length;+ const deviation = Math.sqrt(small.reduce((sum, value) => sum + (value - mean) ** 2, 0) / small.length);+ const t = (frame - 1) / format.fps;+ if (phase !== 'style' || times.some(time => Math.round(time * format.fps) === frame - 1)) samples.push({ t, renderHash: hash(pixels), mean, deviation });+ for (const requested of captureTimes.filter(time => Math.round(time * format.fps) === frame - 1)) captures.push({ t: requested, bytes });+ await persist(frameName(frame), bytes);+ }+ const blend = await readFile(join(directory, 'scene.blend'));+ if (blend.subarray(0, 7).toString() !== 'BLENDER') throw fail('Baked scene artifact is invalid');+ await persist('scene.blend', blend);+ await persist('report.json', Buffer.from(JSON.stringify(report)));+ if (phase !== 'style') {+ const ffmpeg = await findFfmpeg();+ if (!ffmpeg) throw fail('ffmpeg is required for the Blender sequence');+ const video = join(directory, 'sequence.mp4');+ const tag = await bt709TagFilter();+ signal?.throwIfAborted();+ const result = await runFfmpegProcess({ bin: ffmpeg, signal, args: ['-hide_banner', '-loglevel', 'error', '-framerate', String(format.fps),+ '-start_number', '1', '-i', join(directory, 'frame-%06d.png'), '-frames:v', String(count),+ '-vf', ['scale=in_range=pc:out_range=tv:out_color_matrix=bt709', tag].filter(Boolean).join(','),+ ...H264_ENCODE_ARGS, ...BT709_CONTAINER_ARGS, '-movflags', '+faststart', '-n', video] });+ signal?.throwIfAborted();+ if (!result.ok) throw fail(`Sequence encoding failed: ${result.reason}`);+ const geometry = await probeVideoGeometry(video);+ const frameCount = await probeFrameCount(video);+ if (!geometry || geometry.width !== format.width || geometry.height !== format.height || geometry.fps !== format.fps || geometry.numFrames !== count || frameCount !== count || Math.abs(geometry.durationSec - count / format.fps) > 1 / format.fps) throw fail('Encoded Blender sequence failed frame validation');+ const videoBytes = await readFile(video);+ const artifact = await persist('sequence.mp4', videoBytes);+ encoded = { artifact, geometry };+ }+ },+ });+ signal?.throwIfAborted();+ if (run.status !== 'completed' || !run.processGroupClear || !report) throw fail(`Blender worker ${run.reason || run.status}; no render accepted`);+ // A save during native execution revokes publication as well as the next+ // spawn. Retained artifacts remain evidence from the old binding only.+ await resolveRuntime(revision.manifest.renderer, runtime);+ signal?.throwIfAborted();+ return { contract: { width: format.width, height: format.height, fps: format.fps, durationSec: count / format.fps },+ samples, frames: captures, artifacts, sequence: encoded, renderer: { ...report, ...checked.provenance, durationMs: run.durationMs } };+}++export async function publishBlenderVideo(sequence, { revision, signal, reserve }) {+ const id = randomUUID();+ const filename = `blender-${id}.mp4`;+ const destination = join(PATHS.videos, filename);+ const source = join(PATHS.data, sequence.sequence.artifact.relativePath);+ let success = false;+ let thumbnail = null;+ await mkdir(PATHS.videos, { recursive: true });+ try {+ signal?.throwIfAborted();+ await reserve((await stat(source)).size);+ await copyFile(source, destination, constants.COPYFILE_EXCL);+ thumbnail = await generateThumbnail(destination, id);+ if (!thumbnail) throw fail('Blender thumbnail generation failed');+ signal?.throwIfAborted();+ const commit = () => mutateVideoHistory(history => {+ history.unshift({ id, filename, thumbnail, modelId: 'code-animation-blender', prompt: revision.manifest.title,+ ...sequence.sequence.geometry, seed: revision.manifest.seed ?? 0, createdAt: new Date().toISOString(),+ codeAnimation: { revisionId: revision.id, sourceHash: revision.sourceHash, renderer: sequence.renderer } });+ return history;+ });+ success = true;+ return { id, filename, thumbnail, path: `/data/videos/${filename}`, renderer: sequence.renderer, artifacts: sequence.artifacts,+ commit, cleanup: async () => { await rm(destination, { force: true }); await rm(join(PATHS.videoThumbnails, thumbnail), { force: true }); } };+ } finally {+ if (!success) {+ await rm(destination, { force: true });+ if (thumbnail) await rm(join(PATHS.videoThumbnails, thumbnail), { force: true });+ }+ }+}diff --git a/server/services/codeAnimation/blenderRender.test.js b/server/services/codeAnimation/blenderRender.test.jsnew file mode 100644index 0000000000..131a859504--- /dev/null+++ b/server/services/codeAnimation/blenderRender.test.js@@ -0,0 +1,76 @@+/** Boundary fixtures validate rejection/retention; real Blender proof is separate. */+import { afterAll, describe, expect, it, vi } from 'vitest';+import { mkdtemp, writeFile, rm } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import sharp from 'sharp';+import { renderBlenderSequence } from './blenderRender.js';+import { getBlenderStarterPackage } from './blenderStarter.js';++const roots = [];+afterAll(async () => { await Promise.all(roots.map(root => rm(root, { recursive: true, force: true }))); });+const provenance = { binding: 'checked-runtime', version: '4.2.0', engine: 'CYCLES', device: 'CPU', backend: 'CPU', executionMode: 'trusted-local', contained: false };+async function fixture(change = {}) {+ const directory = await mkdtemp(join(tmpdir(), 'blender-sequence-test-'));+ roots.push(directory);+ const pkg = await getBlenderStarterPackage();+ pkg.manifest.format = { width: 64, height: 64, fps: 24, durationSeconds: 1 };+ const pixels = Buffer.alloc(64 * 64 * 3, 20);+ pixels.fill(200, pixels.length / 2);+ const png = await sharp(pixels, { raw: { width: 64, height: 64, channels: 3 } }).png().toBuffer();+ const report = { version: '4.2.0', engine: 'CYCLES', device: 'CPU', backend: 'CPU', width: 64, height: 64, fps: 24,+ frames: [1], frameCount: 24, samples: 4, seed: 17, baked: true, cameraSmooth: true,+ cadence: [{ name: 'Synthetic subject', step: 2, holdsVerified: true, motionBlur: false }], ...change.report };+ const output = { 'frame-000001.png': change.corrupt ? Buffer.from('broken') : png, 'scene.blend': Buffer.from('BLENDER-fixture'), 'report.json': Buffer.from(JSON.stringify(report)) };+ for (const [name, bytes] of Object.entries(output)) await writeFile(join(directory, name), bytes);+ const worker = vi.fn(async options => {+ if (change.canceled) { options.signal.throwIfAborted(); }+ if (!change.failed) await options.onOutput(directory, Object.entries(output).filter(([name]) => name !== change.missing).map(([path, bytes]) => ({ path, bytes: bytes.length })));+ return { status: change.failed ? 'failed' : 'completed', processGroupClear: !change.failed, durationMs: 10 };+ });+ const resolveRuntime = vi.fn(async () => ({ executable: '/example/Blender', worker, provenance }));+ const retain = vi.fn(async (_project, _run, name, bytes) => ({ relativePath: name, bytes: bytes.length, sha256: 'synthetic' }));+ const reserve = vi.fn(async () => {});+ const options = { revision: { manifest: pkg.manifest, files: pkg.files, entryPath: 'scene.py' }, runtime: provenance,+ projectId: 'synthetic-project', runId: 'synthetic-run', signal: new AbortController().signal,+ reserve, phase: 'style', captureTimes: [0], diskBytes: 1024 * 1024, wallSeconds: 30 };+ return { options, deps: { resolveRuntime, retain }, worker, reserve };+}++describe('Blender production artifact boundary', () => {+ it('binds runtime authority, decodes frames, and retains source-derived scene/evidence outside the revision', async () => {+ const { options, deps, worker, reserve } = await fixture();+ const result = await renderBlenderSequence(options, deps);+ expect(deps.resolveRuntime).toHaveBeenCalledWith(options.revision.manifest.renderer, provenance);+ expect(result).toMatchObject({ contract: { width: 64, height: 64, fps: 24, durationSec: 1 }, renderer: { executionMode: 'trusted-local', contained: false } });+ expect(result.frames[0].bytes).toBeInstanceOf(Buffer);+ expect(result.artifacts.map(file => file.name)).toEqual(['frame-000001.png', 'scene.blend', 'report.json']);+ expect(reserve).toHaveBeenCalledTimes(3);+ expect(worker.mock.calls[0][0].files.find(file => file.path === 'scene.py').content).toBe(options.revision.files[0].content);+ });+ it.each([+ ['missing frame', { missing: 'frame-000001.png' }], ['corrupt image', { corrupt: true }],+ ['wrong runtime', { report: { version: '4.3.0' } }], ['failed worker', { failed: true }],+ ['unverified holds', { report: { cadence: [{ step: 2, holdsVerified: false, motionBlur: false }] } }],+ ])('refuses %s without accepting a sequence', async (_name, change) => {+ const { options, deps } = await fixture(change);+ await expect(renderBlenderSequence(options, deps)).rejects.toThrow();+ expect(deps.retain).not.toHaveBeenCalled();+ });+ it('retains old-bound artifacts but refuses acceptance if settings change during the worker', async () => {+ const { options, deps, worker } = await fixture();+ const runtime = await deps.resolveRuntime();+ deps.resolveRuntime.mockReset().mockResolvedValueOnce(runtime).mockRejectedValueOnce(new Error('readiness changed during render'));+ await expect(renderBlenderSequence(options, deps)).rejects.toThrow('readiness changed during render');+ expect(worker).toHaveBeenCalledTimes(1);+ expect(deps.retain).toHaveBeenCalledTimes(3);+ });+ it('refuses revoked runtime authority and pre-canceled runs before starting source', async () => {+ const { options, deps, worker } = await fixture();+ deps.resolveRuntime.mockRejectedValueOnce(new Error('readiness changed'));+ await expect(renderBlenderSequence(options, deps)).rejects.toThrow('readiness changed');+ const controller = new AbortController(); controller.abort();+ await expect(renderBlenderSequence({ ...options, signal: controller.signal }, deps)).rejects.toThrow();+ expect(worker).not.toHaveBeenCalled();+ });+});diff --git a/server/services/codeAnimation/blenderStarter.js b/server/services/codeAnimation/blenderStarter.jsnew file mode 100644index 0000000000..207610923a--- /dev/null+++ b/server/services/codeAnimation/blenderStarter.js@@ -0,0 +1,16 @@+/** Data-only original starter; fetching it never runs code or calls a provider. */+import { readFile } from 'node:fs/promises';+import { createCodeAnimationPackage } from '../../lib/codeAnimationPackage.js';++export async function getBlenderStarterPackage() {+ return createCodeAnimationPackage({+ title: 'Lantern in a Painted Garden',+ brief: { concept: 'A glowing paper lantern crosses an indigo garden under an ivory moon, trailing hand-painted sparks.', cast: 'One vermilion paper lantern', onScreenText: '' },+ styleGuide: 'Original procedural pigment atlas, faceted paper shapes, warm coral and gold against cool indigo and teal. Subject on twos, baked sparks on threes, smooth camera.',+ renderer: { kind: 'blender', version: '4.2.0', engine: 'CYCLES' },+ format: { width: 1920, height: 1080, fps: 24, durationSeconds: 10 }, seed: 17,+ entrypoints: [{ role: 'scene', path: 'scene.py' }], assets: [],+ shots: [{ label: 'Lantern crossing', startSeconds: 0, endSeconds: 10 }], events: [],+ audio: { kind: 'silence' }, execution: { requested: null, effective: null },+ }, [{ path: 'scene.py', content: await readFile(new URL('./blenderStarter.py', import.meta.url), 'utf8') }]);+}diff --git a/server/services/codeAnimation/blenderStarter.py b/server/services/codeAnimation/blenderStarter.pynew file mode 100644index 0000000000..f10758657f--- /dev/null+++ b/server/services/codeAnimation/blenderStarter.py@@ -0,0 +1,121 @@+"""Original procedural scene: a paper lantern crossing a painted night garden.+No downloads, add-ons, external assets or live simulation. All motion is baked.+"""+import bpy+import math+import random+from mathutils import Vector+++def build_scene(config):+ rng = random.Random(config['seed'])+ scene = bpy.context.scene+ if scene.world is None:+ scene.world = bpy.data.worlds.new('Painted night')+ scene.world.color = (0.025, 0.04, 0.09)+ scene.view_settings.view_transform = 'Standard'+ # Original pigment atlas: layered irregular brush marks, packed by driver.+ size = 128+ image = bpy.data.images.new('Original pigment brush atlas', width=size, height=size)+ pixels = []+ for y in range(size):+ for x in range(size):+ pigment = 0.62 + 0.18 * math.sin(x * .19 + math.sin(y * .11) * 3) + rng.uniform(-.13, .13)+ pixels.extend((pigment, pigment, pigment, 1))+ image.pixels = pixels+ image.pack()++ def material(name, color, glow=0):+ mat = bpy.data.materials.new(name)+ mat.diffuse_color = (*color, 1)+ mat.use_nodes = True+ nodes = mat.node_tree.nodes+ bsdf = nodes.get('Principled BSDF')+ tex = nodes.new('ShaderNodeTexImage')+ tex.image = image+ tex.projection = 'BOX'+ tex.projection_blend = .25+ coordinate = nodes.new('ShaderNodeTexCoord')+ mat.node_tree.links.new(coordinate.outputs['Generated'], tex.inputs['Vector'])+ mix = nodes.new('ShaderNodeMixRGB')+ mix.blend_type = 'MULTIPLY'+ mix.inputs[0].default_value = .75+ mix.inputs[1].default_value = (*color, 1)+ mat.node_tree.links.new(tex.outputs['Color'], mix.inputs[2])+ mat.node_tree.links.new(mix.outputs[0], bsdf.inputs['Base Color'])+ bsdf.inputs['Roughness'].default_value = .92+ bsdf.inputs['Emission Color'].default_value = (*color, 1)+ bsdf.inputs['Emission Strength'].default_value = glow+ return mat++ indigo = material('Ultramarine pigment', (.055, .09, .22), .25)+ teal = material('Viridian pigment', (.05, .32, .33), .25)+ coral = material('Vermilion paper', (.95, .25, .12), .3)+ gold = material('Warm lantern light', (1, .63, .2), 1.4)+ cream = material('Ivory dry brush', (.94, .83, .59), .3)++ def sphere(name, location, scale, mat, subdivisions=1):+ bpy.ops.mesh.primitive_ico_sphere_add(subdivisions=subdivisions, radius=1, location=location)+ obj = bpy.context.object+ obj.name = name+ obj.scale = scale+ obj.data.materials.append(mat)+ return obj++ # Scenic layers overlap like torn paper, with broad low-poly brush facets.+ sphere('Midnight cyclorama', (0, 5, 2), (18, .2, 12), indigo, 2)+ for i in range(16):+ x = -10 + i * 1.3+ sphere('Painted garden leaf %02d' % i, (x, 2 + rng.random(), -.8 + rng.random()),+ (.55 + rng.random() * .6, .15, 1.6 + rng.random() * 2), teal, 1)+ sphere('Golden moon', (4.8, 4, 4), (1.5, .2, 1.5), cream, 2)+ for i in range(48):+ sphere('Dry brush star %02d' % i, (rng.uniform(-9, 9), 3.7, rng.uniform(1, 7)),+ (.025, .018, .06), cream)+ lantern = sphere('Lantern - animation on twos', (0, 0, 1), (.7, .55, 1), coral, 2)+ lantern['portos_cadence'] = 2+ heart = sphere('Lantern glow', (0, -.47, 1), (.4, .12, .55), gold, 2)+ # Parent glow follows the exact baked subject keys without another track.+ heart.parent = lantern+ heart.location = (0, -.7, 0)+ sparks = []+ for i in range(9):+ obj = sphere('Baked brush spark %02d' % i, (0, 0, 0), (.045, .035, .12), gold)+ obj['portos_cadence'] = 3+ sparks.append(obj)+ count = config['frameCount']+ fps = config['fps']+ for frame in range(1, count + 1, 2):+ t = (frame - 1) / fps+ lantern.location = (-3.5 + 7 * t / (count / fps), 0, 1.6 + .45 * math.sin(t * 1.2))+ lantern.rotation_euler = (.04 * math.sin(t), .13 * math.sin(t * 1.7), .1 * math.sin(t * .8))+ lantern.keyframe_insert('location', frame=frame)+ lantern.keyframe_insert('rotation_euler', frame=frame)+ for i, obj in enumerate(sparks):+ for frame in range(1, count + 1, 3):+ t = (frame - 1) / fps+ obj.location = (-3.5 + 7 * t / (count / fps) - .2 * i, -.2, .8 + (t * .45 + i * .27) % 2)+ obj.rotation_euler = (0, .35 * math.sin(t + i), 0)+ obj.keyframe_insert('location', frame=frame)+ obj.keyframe_insert('rotation_euler', frame=frame)+ for obj in [lantern, *sparks]:+ for curve in obj.animation_data.action.fcurves:+ for point in curve.keyframe_points:+ point.interpolation = 'CONSTANT'+ bpy.ops.object.camera_add(location=(0, -18, 5))+ camera = bpy.context.object+ camera.name = 'Smooth camera - continuous track'+ camera.data.type = 'ORTHO'+ camera.data.ortho_scale = 12+ scene.camera = camera+ for frame in (1, count):+ camera.location = (-.45 + .9 * (frame - 1) / max(1, count - 1), -18, 4.3)+ camera.rotation_euler = (Vector((0, 0, 2.2)) - camera.location).to_track_quat('-Z', 'Y').to_euler()+ camera.keyframe_insert('location', frame=frame)+ camera.keyframe_insert('rotation_euler', frame=frame)+ for curve in camera.animation_data.action.fcurves:+ for point in curve.keyframe_points:+ point.interpolation = 'LINEAR'+ bpy.ops.object.light_add(type='AREA', location=(-3, -5, 8))+ bpy.context.object.data.energy = 900+ bpy.context.object.data.size = 8diff --git a/server/services/codeAnimation/containedWorker.js b/server/services/codeAnimation/containedWorker.jsindex 2e7f6993d0..39e68b1783 100644--- a/server/services/codeAnimation/containedWorker.js+++ b/server/services/codeAnimation/containedWorker.js@@ -3,7 +3,9 @@* workspace, run one operator-configured executable under the enforced OS* sandbox with a from-scratch environment, enforce wall-time / disk / file /* memory limits, own the process group through cancellation, and validate- * what the worker left behind. No uncontained fallback exists.+ * what the worker left behind. No uncontained fallback exists. The separate+ * trusted-local entry point requires explicit server-side operator authorization;+ * it reuses supervision but provides no host filesystem/network boundary.*/import { constants } from 'node:fs';import { access, lstat, mkdir, open, readFile, readdir, realpath, rm } from 'node:fs/promises';@@ -111,7 +113,7 @@ async function measure(dirs, { maxFiles }) {return { bytes, files, outputs, invalid };}-async function residentBytes(pid) {+async function residentBytes(pid, processGroup = false) {if (process.platform === 'linux') {// bwrap supervises a separate PID namespace; its own RSS is not the tool's.// Walk host-visible descendants, including the namespace init and worker.@@ -126,6 +128,13 @@ async function residentBytes(pid) {const descendants = await Promise.all(children.trim().split(/\s+/).filter(Boolean).map((child) => residentBytes(Number(child))));return own + descendants.reduce((sum, bytes) => sum + bytes, 0);}+ if (processGroup) {+ const { stdout } = await execFileAsync('/bin/ps', ['-axo', 'pgid=,rss=']);+ return stdout.trim().split('\n').reduce((sum, line) => {+ const [group, rss] = line.trim().split(/\s+/).map(Number);+ return sum + (group === pid && Number.isFinite(rss) ? rss * 1024 : 0);+ }, 0);+ }const { stdout } = await execFileAsync('/bin/ps', ['-o', 'rss=', '-p', String(pid)]).catch(() => ({ stdout: '' }));const kib = Number.parseInt(stdout.trim(), 10);return Number.isFinite(kib) ? kib * 1024 : 0;@@ -148,14 +157,30 @@ const tail = () => {* completed, valid result, before the workspace is removed. Resolves with the* run's evidence; refuses (503) when no enforced mechanism is available.*/-export async function runContainedWorker({- tool, files = [], entrypoint = null, limits: requested = {}, signal, workspaceRoot,- onOutput, tickMs = 1000, seatbeltPath = CODE_ANIMATION_SEATBELT, bubblewrapPath = CODE_ANIMATION_BUBBLEWRAP,-}) {- const mechanism = await currentContainmentMechanism(seatbeltPath, bubblewrapPath);+export async function runContainedWorker(options) {+ const mechanism = await currentContainmentMechanism(options.seatbeltPath, options.bubblewrapPath);if (!mechanism.supported) {throw new ServerError(`Contained execution refused: ${mechanism.reason}`, { status: 503, code: 'CODE_ANIMATION_CONTAINMENT_UNAVAILABLE' });}+ return runOwnedWorker(options, mechanism);+}++/**+ * Explicit trusted-local entry point. Only execution.js selects it after checking+ * machine-local operator configuration. This is NOT containment: trusted code+ * can access the host, network and subprocesses, including outside supervision.+ */+export async function runTrustedLocalWorker(options) {+ if (!['darwin', 'linux'].includes(process.platform)) {+ throw new ServerError('Trusted-local worker process supervision requires macOS or Linux', { status: 503, code: 'CODE_ANIMATION_WORKER_UNSUPPORTED' });+ }+ return runOwnedWorker(options, { id: 'trusted-local', supported: true });+}++async function runOwnedWorker({+ tool, files = [], entrypoint = null, limits: requested = {}, signal, workspaceRoot,+ onOutput, tickMs = 1000, seatbeltPath = CODE_ANIMATION_SEATBELT, bubblewrapPath = CODE_ANIMATION_BUBBLEWRAP,+}, mechanism) {const limits = codeAnimationWorkerLimitsSchema.parse(requested);if (entrypoint !== null && !files.some((file) => file.path === entrypoint)) {throw new ServerError('The worker entrypoint is not a staged file', { status: 400, code: 'CODE_ANIMATION_STAGE_PATH' });@@ -178,12 +203,13 @@ export async function runContainedWorker({const sandboxWorkspace = linux ? '/workspace' : workspace;const argv = tool.argv(entrypoint === null ? null : join(sandboxWorkspace, 'input', entrypoint), sandboxWorkspace);const config = { executable, toolRoots: codeAnimationToolRoots(executable), workspace, sandboxWorkspace, argv };- const wrapper = linux- ? [bubblewrapPath, ...codeAnimationBubblewrapArgs(config)]- : [seatbeltPath, '-p', codeAnimationSeatbeltProfile(config), executable, ...argv];+ const trustedLocal = mechanism.id === 'trusted-local';+ const wrapper = trustedLocal ? [executable, ...argv]+ : linux ? [bubblewrapPath, ...codeAnimationBubblewrapArgs(config)]+ : [seatbeltPath, '-p', codeAnimationSeatbeltProfile(config), executable, ...argv];// Explicit bash on Linux avoids /bin/sh's distro-dependent ulimit units.// Both this bash invocation and macOS sh count KiB; limits survive exec.- const child = spawn(linux ? '/bin/bash' : '/bin/sh', ['-c', 'ulimit -c 0 && ulimit -n "$1" && ulimit -f "$2" && shift 2 && exec "$@"',+ const child = spawn(process.platform === 'linux' ? '/bin/bash' : '/bin/sh', ['-c', 'ulimit -c 0 && ulimit -n "$1" && ulimit -f "$2" && shift 2 && exec "$@"','portos-contained-worker', String(limits.openFiles), String(Math.max(1, Math.floor(limits.diskBytes / 1024))),...wrapper], {cwd: join(workspace, 'tmp'), env: withSpawnCwdEnv(codeAnimationWorkerEnv(workspace), join(workspace, 'tmp')),@@ -218,7 +244,7 @@ export async function runContainedWorker({const usage = await measure(writable, limits);if (usage.bytes > limits.diskBytes) kill('disk');else if (usage.files > limits.maxFiles) kill('files');- else if (await residentBytes(child.pid) > limits.memoryBytes) kill('memory');+ else if (await residentBytes(child.pid, trustedLocal) > limits.memoryBytes) kill('memory');} catch (error) {console.error(`❌ Code Animation worker watchdog failed: ${error.message}`);kill('watchdog');@@ -231,9 +257,10 @@ export async function runContainedWorker({clearTimeout(timer);clearInterval(watchdog);signal?.removeEventListener('abort', onAbort);- // The worker cannot fork; bwrap also owns its PID namespace and uses+ // Contained workers cannot fork; bwrap also owns its PID namespace and uses// die-with-parent. The outer group is still verified empty, and any- // straggler is killed before the run is reported.+ // straggler is killed before the run is reported. Trusted-local code can+ // escape its group; supervision is not a hostile-code security guarantee.// --new-session moves the namespace child out of the outer process group.// bwrap's info fd names that host PID before allowing it to run; verify it// too, so an empty launcher group cannot masquerade as completed teardown.@@ -256,7 +283,7 @@ export async function runContainedWorker({else if (usage.invalid.length) { status = 'failed'; reason = 'output-invalid'; }else if (!processGroupClear || (linux && !namespacePid)) { status = 'failed'; reason = 'containment-status'; }const result = {- status, reason, mechanism: mechanism.id, exitCode: exit.code, signal: exit.signal,+ status, reason, mechanism: mechanism.id, contained: !trustedLocal, exitCode: exit.code, signal: exit.signal,processGroupClear, durationMs: Date.now() - started, limits,usage: { bytes: usage.bytes, files: usage.files },outputs: status === 'completed' ? usage.outputs : [], invalidOutputs: usage.invalid,diff --git a/server/services/codeAnimation/containedWorker.test.js b/server/services/codeAnimation/containedWorker.test.jsindex ed4d180e80..2ad8fa47c9 100644--- a/server/services/codeAnimation/containedWorker.test.js+++ b/server/services/codeAnimation/containedWorker.test.js@@ -1,8 +1,8 @@-import { afterAll, describe, expect, it } from 'vitest';+import { afterAll, afterEach, describe, expect, it, vi } from 'vitest';import { mkdtemp, readdir, readFile, rm } from 'node:fs/promises';import { tmpdir } from 'node:os';import { join } from 'node:path';-import { currentContainmentMechanism, runContainedWorker } from './containedWorker.js';+import { currentContainmentMechanism, runContainedWorker, runTrustedLocalWorker } from './containedWorker.js';// Real-mechanism suite: these run only where the enforced sandbox exists. The// adversarial boundary and limit checks run end to end through the probe route@@ -13,6 +13,7 @@ if (process.env.PORTOS_REQUIRE_LINUX_CONTAINMENT === '1' && mechanism.id !== 'lithrow new Error(`Real Linux containment is required by this test job: ${mechanism.reason}`);}const roots = [];+afterEach(() => vi.unstubAllEnvs());const workspaceRoot = async () => {const root = await mkdtemp(join(tmpdir(), 'portos-contained-worker-'));roots.push(root);@@ -108,3 +109,40 @@ worker.on('error', () => process.exit(1));expect(await readdir(root)).toEqual([]);});});+++describe.skipIf(!['darwin', 'linux'].includes(process.platform))('explicit trusted-local worker supervision', () => {+ it('scrubs credentials and kills the owned parent and child group on cancel', async () => {+ vi.stubEnv('PORTOS_API_TOKEN', 'synthetic-worker-token');+ const root = await workspaceRoot();+ const controller = new AbortController();+ // The source announces its child, then requests cancellation through an+ // output marker observed by this test; no timing assumption about startup.+ const pending = runTrustedLocalWorker({+ tool: node(), workspaceRoot: root, entrypoint: 'main.cjs', signal: controller.signal,+ files: [{ path: 'main.cjs', content: `+const fs = require('fs');+const child = require('child_process').spawn(process.execPath, ['-e', 'setInterval(() => {}, 1000)']);+console.log(JSON.stringify({ child: child.pid, token: !!process.env.PORTOS_API_TOKEN }));+fs.writeFileSync(process.env.PORTOS_WORKER_OUTPUT + '/ready', 'ready');+setInterval(() => {}, 1000);+` }], limits: { wallSeconds: 15 },+ });+ let ready = false;+ for (let attempt = 0; attempt < 150 && !ready; attempt += 1) {+ for (const directory of await readdir(root)) {+ ready ||= await readFile(join(root, directory, 'output', 'ready'), 'utf8').then(() => true, () => false);+ }+ if (!ready) await new Promise(resolve => setTimeout(resolve, 50));+ }+ controller.abort();+ const result = await pending;+ expect(ready).toBe(true);+ expect(result).toMatchObject({ status: 'terminated', reason: 'canceled', contained: false, mechanism: 'trusted-local', processGroupClear: true });+ const evidence = JSON.parse(result.stdout.trim());+ expect(evidence.child).toBeGreaterThan(0);+ expect(evidence.token).toBe(false);+ expect(() => process.kill(evidence.child, 0)).toThrow();+ expect(await readdir(root)).toEqual([]);+ }, 20000);+});diff --git a/server/services/codeAnimation/execution.js b/server/services/codeAnimation/execution.jsindex 5031fe9375..09be40f077 100644--- a/server/services/codeAnimation/execution.js+++ b/server/services/codeAnimation/execution.js@@ -5,6 +5,7 @@* at boot or calls a provider.*/import { createServer } from 'node:net';+import { createHash } from 'node:crypto';import { constants } from 'node:fs';import { access, lstat, mkdtemp, readFile, realpath, rm, writeFile } from 'node:fs/promises';import { homedir, tmpdir } from 'node:os';@@ -17,7 +18,7 @@ import {} from '../../lib/codeAnimationContainment.js';import { getSettings, updateSettings } from '../settings.js';import { cdpRequest } from '../browserService.js';-import { currentContainmentMechanism, runContainedWorker } from './containedWorker.js';+import { currentContainmentMechanism, runContainedWorker, runTrustedLocalWorker } from './containedWorker.js';import { probeBlenderRender } from './blenderProbe.js';const SETTINGS_KEY = 'codeAnimationExecution';@@ -43,6 +44,7 @@ const BROWSER_LANE = {let lastProbe = null;let probing = null;+let configurationGeneration = 0;const inside = (root, path) => {const rel = relative(root, path);@@ -51,7 +53,7 @@ const inside = (root, path) => {/*** Validate an operator-supplied executable: `{ executable: realpath, fingerprint, problem: null }`- * or a problem. The fingerprint ties containment evidence to these exact bytes on disk.+ * or a problem. The fingerprint ties checks to the file identity and modification metadata.*/async function inspectExecutable(path) {if (!path) return { executable: null, problem: 'Not configured.' };@@ -73,26 +75,33 @@ async function inspectExecutable(path) {async function configuredTools() {const parsed = codeAnimationExecutionToolsSchema.safeParse((await getSettings())?.[SETTINGS_KEY]);- return parsed.success ? parsed.data : { blender: { executable: null } };+ return parsed.success ? parsed.data : codeAnimationExecutionToolsSchema.parse({ blender: { executable: null } });}function blenderLane(mechanism, blender) {- if (!mechanism.supported) return { ready: false, reason: mechanism.reason };+ if (blender.executionMode === 'contained' && !mechanism.supported) return { ready: false, reason: mechanism.reason };+ if (blender.executionMode === 'trusted-local' && !['darwin', 'linux'].includes(process.platform)) {+ return { ready: false, reason: 'Trusted-local worker process supervision requires macOS or Linux.' };+ }if (!blender.executable) return { ready: false, reason: `Blender: ${blender.problem}` };const evidence = lastProbe?.tools?.blender;- if (!lastProbe?.passed) return { ready: false, reason: 'Run the containment check; execution stays refused until it passes on this server process.' };- if (!evidence || evidence.executable !== blender.executable || evidence.fingerprint !== blender.fingerprint) {- return { ready: false, reason: 'The configured Blender changed since the last containment check.' };+ if (!lastProbe?.passed) return { ready: false, reason: 'Run the execution check; execution stays refused until it passes on this server process.' };+ if (!evidence || evidence.executable !== blender.executable || evidence.fingerprint !== blender.fingerprint+ || evidence.executionMode !== blender.executionMode || evidence.engine !== blender.engine) {+ return { ready: false, reason: 'The Blender executable, engine or execution mode changed since the last check.' };}- if (!evidence.passed) return { ready: false, reason: 'Blender did not render the supported test scene under containment.' };+ if (!evidence.passed) return { ready: false, reason: `Blender did not render the supported test scene in ${blender.executionMode} mode.` };return { ready: true, reason: null };}export async function getCodeAnimationExecution() {const mechanism = await currentContainmentMechanism();- const blender = await inspectExecutable((await configuredTools()).blender.executable);+ const configuration = (await configuredTools()).blender;+ const blender = { ...await inspectExecutable(configuration.executable), executionMode: configuration.executionMode, engine: configuration.engine };return {- platform: process.platform, mechanism, probe: lastProbe,+ platform: process.platform, mechanism, probe: lastProbe, executionMode: blender.executionMode,+ contained: blender.executionMode === 'contained',+ trustedLocalWarning: 'Trusted-local Blender runs with this account’s host filesystem, network and process access. Only run source you trust. Environment scrubbing and process/resource supervision are not containment; code can act outside the supervised workspace or escape its process group.',tools: { blender },lanes: { browser: BROWSER_LANE, blender: blenderLane(mechanism, blender) },defaultLimits: codeAnimationWorkerLimitsSchema.parse({}),@@ -107,7 +116,9 @@ export async function setCodeAnimationExecutionTools(input) {if (inspected.problem) throw new ServerError(inspected.problem, { status: 400, code: 'CODE_ANIMATION_TOOL_INVALID' });executable = inspected.executable;}- await updateSettings({ [SETTINGS_KEY]: { blender: { executable } } });+ await updateSettings({ [SETTINGS_KEY]: { blender: { ...tools.blender, executable } } });+ configurationGeneration += 1;+ lastProbe = null;return getCodeAnimationExecution();}@@ -195,11 +206,11 @@ async function probeBoundary(workspaceRoot) {}}-async function probeLimit(workspaceRoot, kind, limits, expected) {+async function probeLimit(workspaceRoot, kind, limits, expected, worker = runContainedWorker) {const controller = new AbortController();const timer = kind === 'cancel' ? setTimeout(() => controller.abort(), 300) : null;try {- const run = await runContainedWorker({+ const run = await worker({tool: probeTool(), workspaceRoot, entrypoint: 'limit.cjs', tickMs: 100, signal: controller.signal,files: [{ path: 'limit.cjs', content: LIMIT_SCRIPTS[kind] }],limits: { wallSeconds: 20, diskBytes: 1024 * 1024, maxFiles: 10_000, memoryBytes: 1024 * 1024 * 1024, openFiles: 256, ...limits },@@ -213,29 +224,39 @@ async function probeLimit(workspaceRoot, kind, limits, expected) {async function runProbe() {const started = Date.now();+ const generation = configurationGeneration;+ const configuration = (await configuredTools()).blender;+ const trustedLocal = configuration.executionMode === 'trusted-local';+ const worker = trustedLocal ? runTrustedLocalWorker : runContainedWorker;// Fail closed while checking, and if the check itself errors.lastProbe = null;const mechanism = await currentContainmentMechanism();- if (!mechanism.supported) {+ if (!trustedLocal && !mechanism.supported) {lastProbe = { probedAt: new Date().toISOString(), mechanism: null, passed: false, refused: mechanism.reason, checks: [], tools: {}, browser: null, durationMs: 0 };return lastProbe;}const workspaceRoot = join(PATHS.data, WORKSPACE_DIR);const checks = [- ...await probeBoundary(workspaceRoot),- await probeLimit(workspaceRoot, 'time', { wallSeconds: 1 }, 'time'),- await probeLimit(workspaceRoot, 'disk', {}, 'disk'),- await probeLimit(workspaceRoot, 'memory', { memoryBytes: 128 * 1024 * 1024 }, 'memory'),- await probeLimit(workspaceRoot, 'cancel', {}, 'canceled'),+ ...trustedLocal ? [] : await probeBoundary(workspaceRoot),+ await probeLimit(workspaceRoot, 'time', { wallSeconds: 1 }, 'time', worker),+ await probeLimit(workspaceRoot, 'disk', {}, 'disk', worker),+ await probeLimit(workspaceRoot, 'memory', { memoryBytes: 128 * 1024 * 1024 }, 'memory', worker),+ await probeLimit(workspaceRoot, 'cancel', {}, 'canceled', worker),];- const blender = await probeBlenderRender(await inspectExecutable((await configuredTools()).blender.executable), workspaceRoot);+ const blender = await probeBlenderRender(await inspectExecutable(configuration.executable), workspaceRoot, {+ worker, engine: configuration.engine, executionMode: configuration.executionMode,+ });const browser = await cdpRequest('/json/version', { timeout: 2000 }).then((response) => response.ok, () => false);+ // A save during a probe revokes its authority, even if the operator later+ // switches back to the same path. Only the next explicit check can arm it.+ if (generation !== configurationGeneration) return null;lastProbe = {- probedAt: new Date().toISOString(), mechanism: mechanism.id, passed: checks.every((check) => check.passed),+ probedAt: new Date().toISOString(), executionMode: configuration.executionMode, contained: !trustedLocal,+ mechanism: trustedLocal ? 'trusted-local' : mechanism.id, passed: checks.every((check) => check.passed),refused: null, checks, tools: blender ? { blender } : {}, browser: { available: browser }, durationMs: Date.now() - started,};const log = lastProbe.passed ? console.log : console.error;- log(`${lastProbe.passed ? '🛡️' : '❌'} Code Animation containment check ${lastProbe.passed ? 'passed' : 'FAILED'} (${checks.filter((check) => check.passed).length}/${checks.length})`);+ log(`${lastProbe.passed ? '🛡️' : '❌'} Code Animation ${configuration.executionMode} check ${lastProbe.passed ? 'passed' : 'FAILED'} (${checks.filter((check) => check.passed).length}/${checks.length})`);return lastProbe;}@@ -245,3 +266,28 @@ export async function probeCodeAnimationExecution() {await probing;return getCodeAnimationExecution();}++/** Resolve only saved operator authority; packages cannot select a worker mode. */+export async function resolveBlenderExecution(renderer, expected = null) {+ const execution = await getCodeAnimationExecution();+ if (!execution.lanes.blender.ready) {+ throw new ServerError(execution.lanes.blender.reason, { status: 409, code: 'CODE_ANIMATION_BLENDER_NOT_READY' });+ }+ const tool = execution.tools.blender;+ const evidence = execution.probe.tools.blender;+ if (renderer.version !== evidence.version || (renderer.engine || 'CYCLES') !== tool.engine) {+ throw new ServerError('The project Blender version and engine must match the successful execution check', { status: 409, code: 'CODE_ANIMATION_BLENDER_RUNTIME_MISMATCH' });+ }+ const executableFingerprint = createHash('sha256').update(tool.fingerprint).digest('hex');+ const binding = createHash('sha256').update(JSON.stringify([executableFingerprint, tool.executionMode, tool.engine, evidence.version, execution.probe.probedAt])).digest('hex');+ if (expected && expected.binding !== binding) {+ throw new ServerError('Blender readiness changed during this run. Start a new run after checking the selected executable and mode.', { status: 409, code: 'CODE_ANIMATION_BLENDER_READINESS_CHANGED' });+ }+ return {+ executable: tool.executable,+ worker: tool.executionMode === 'trusted-local' ? runTrustedLocalWorker : runContainedWorker,+ provenance: { binding, executableFingerprint, executionMode: tool.executionMode, contained: tool.executionMode === 'contained',+ version: evidence.version, engine: evidence.render.engine, device: evidence.render.device, backend: evidence.render.backend,+ mechanism: execution.probe.mechanism, probedAt: execution.probe.probedAt },+ };+}diff --git a/server/services/codeAnimation/executionAuthority.test.js b/server/services/codeAnimation/executionAuthority.test.jsnew file mode 100644index 0000000000..67ba885f2a--- /dev/null+++ b/server/services/codeAnimation/executionAuthority.test.js@@ -0,0 +1,53 @@+import { afterAll, describe, expect, it, vi } from 'vitest';+import { mkdtemp, mkdir, writeFile, chmod, rm } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import express from 'express';+import { request } from '../../lib/testHelper.js';+import { errorMiddleware } from '../../lib/errorHandler.js';+const state = vi.hoisted(() => ({ settings: {}, workers: [] }));+vi.mock('../settings.js', () => ({ getSettings: async () => state.settings, updateSettings: async patch => { state.settings = { ...state.settings, ...patch }; } }));+vi.mock('../browserService.js', () => ({ cdpRequest: async () => ({ ok: false }) }));+vi.mock('./containedWorker.js', () => ({+ currentContainmentMechanism: async () => ({ supported: false, reason: 'Synthetic unavailable sandbox' }),+ runContainedWorker: vi.fn(() => { throw new Error('No contained fallback'); }),+ runTrustedLocalWorker: vi.fn(async options => {+ state.workers.push(options);+ const source = options.files[0].content;+ const reason = source.includes('Buffer.alloc(512') ? 'memory' : source.includes('setInterval') ? 'disk' : options.limits.wallSeconds === 1 ? 'time' : 'canceled';+ return { status: 'terminated', reason, processGroupClear: true };+ }),+}));+vi.mock('./blenderProbe.js', () => ({ probeBlenderRender: async (tool, _root, options) => ({ ...tool, executionMode: options.executionMode, engine: options.engine,+ passed: true, version: '4.2.0', render: { engine: options.engine, device: 'CPU', backend: 'CPU' } }) }));+import router from '../../routes/codeAnimationExecution.js';+import { resolveBlenderExecution } from './execution.js';+const app = express(); app.use(express.json()); app.use('/execution', router); app.use(errorMiddleware);+const root = await mkdtemp(join(tmpdir(), 'blender-authority-test-'));+afterAll(() => rm(root, { recursive: true, force: true }));++describe.skipIf(!['darwin', 'linux'].includes(process.platform))('machine-owned Blender execution authority', () => {+ it('defaults closed, requires acknowledgement, binds successful checks, and revokes them on save', async () => {+ const directory = join(root, 'Example.app', 'Contents', 'MacOS');+ await mkdir(directory, { recursive: true });+ const executable = join(directory, 'Blender');+ await writeFile(executable, 'synthetic runtime'); await chmod(executable, 0o755);+ const put = blender => request(app).put('/execution/tools').send({ blender });+ expect((await put({ executable })).body.executionMode).toBe('contained');+ expect((await request(app).post('/execution/probe')).body.lanes.blender.ready).toBe(false);+ expect(state.workers).toHaveLength(0);+ expect((await put({ executable, executionMode: 'trusted-local' })).status).toBe(400);+ expect(state.settings.codeAnimationExecution.blender.executionMode).toBe('contained');+ expect((await put({ executable, executionMode: 'trusted-local', acknowledgeHostAccess: true })).status).toBe(200);+ const ready = (await request(app).post('/execution/probe')).body;+ expect(ready).toMatchObject({ contained: false, executionMode: 'trusted-local', lanes: { blender: { ready: true } } });+ expect(state.workers).toHaveLength(4);+ const renderer = { kind: 'blender', version: '4.2.0', engine: 'CYCLES' };+ const bound = await resolveBlenderExecution(renderer);+ expect(bound.provenance).toMatchObject({ executionMode: 'trusted-local', contained: false });+ await expect(resolveBlenderExecution({ ...renderer, version: '4.3.0' })).rejects.toMatchObject({ code: 'CODE_ANIMATION_BLENDER_RUNTIME_MISMATCH' });+ await expect(resolveBlenderExecution(renderer, { binding: 'old-check' })).rejects.toMatchObject({ code: 'CODE_ANIMATION_BLENDER_READINESS_CHANGED' });+ await put({ executable, executionMode: 'trusted-local', acknowledgeHostAccess: true });+ await expect(resolveBlenderExecution(renderer, bound.provenance)).rejects.toMatchObject({ code: 'CODE_ANIMATION_BLENDER_NOT_READY' });+ });+});diff --git a/server/services/codeAnimation/stages.db.test.js b/server/services/codeAnimation/stages.db.test.jsindex be4bb8d4ad..6a75e6a250 100644--- a/server/services/codeAnimation/stages.db.test.js+++ b/server/services/codeAnimation/stages.db.test.js@@ -209,6 +209,45 @@ describe.skipIf(!ready)('Production stage runs', () => {expect((await patchProductionProject(slow.id, { budgets: { renderSeconds: 60 } })).budgets.renderSeconds).toBe(60);}, 20000);+ it('runs Blender stages from immutable Python and rerenders resumed evidence after runtime authority changes', async () => {+ const blenderManifest = { ...manifest(), renderer: { kind: 'blender', version: '4.2.0', engine: 'CYCLES' }, entrypoints: [{ role: 'scene', path: 'scene.py' }] };+ const created = await createProductionProject({ manifest: blenderManifest });+ ids.push(created.id);+ const imported = createCodeAnimationPackage(blenderManifest, [{ path: 'scene.py', content: 'def build_scene(config): pass' }]);+ const { revision } = await importProductionPackage(created.id, imported);+ let binding = 'first-check';+ const resolveBlender = vi.fn(async () => ({ provenance: { binding, version: '4.2.0', engine: 'CYCLES', device: 'CPU', executionMode: 'trusted-local', contained: false } }));+ const blender = vi.fn(async options => {+ expect(options.runtime.binding).toBe(binding);+ expect(options.revision.entryPath).toBe('scene.py');+ expect(options.revision.files[0].content).toBe(imported.files[0].content);+ expect(options.revision.staged).toContain('/revisions/');+ return { contract: { durationSec: 4, fps: 12, width: 1280, height: 720 },+ frames: (options.captureTimes || []).map(t => ({ t, bytes: Buffer.from(`synthetic-${t}`) })),+ samples: Array.from({ length: 48 }, (_, i) => ({ t: i / 12, renderHash: String(i), mean: 80, deviation: 20 })),+ renderer: options.runtime, artifacts: [] };+ });+ const browser = vi.fn();+ const commit = vi.fn().mockRejectedValueOnce(new Error('Synthetic history failure')).mockResolvedValue(undefined);+ const cleanup = vi.fn();+ const publishBlender = vi.fn().mockResolvedValue({ id: 'synthetic-video', filename: 'synthetic.mp4', commit, cleanup });+ const deps = { resolveBlender, blender, publishBlender, sample: browser, render: browser };+ await expect(startProductionStageRun(created.id, { executionMode: 'trusted-local' }, deps)).rejects.toThrow();+ const first = await startProductionStageRun(created.id, {}, deps);+ expect(await first.done).toBe('failed');+ binding = 'second-check';+ const second = await startProductionStageRun(created.id, { resumeFromRunId: first.run.id }, deps);+ expect(await second.done).toBe('completed');+ expect(blender.mock.calls.map(([options]) => options.phase)).toEqual(['style', 'pilot', 'final', 'style', 'pilot', 'final']);+ expect(browser).not.toHaveBeenCalled();+ expect(commit).toHaveBeenCalledTimes(2);+ expect(cleanup).toHaveBeenCalledTimes(1);+ const saved = (await getProductionHistory(created.id, { limit: 5, offset: 0 })).items.find(item => item.id === second.run.id);+ expect(saved.data.renderer).toMatchObject({ binding: 'second-check', contained: false });+ expect(saved.data.stages.every(stage => !stage.reusedFrom && stage.rendererBinding === 'second-check')).toBe(true);+ expect((await exportProductionPackage(created.id, revision.id)).revisionHash).toBe(imported.revisionHash);+ });+it('marks a stranded run interrupted on restart and never calls a provider or render for it', async () => {const { id, revision } = await project();await query("INSERT INTO code_animation_project_runs (id, project_id, revision_id, status, data) VALUES ($1, $2, $3, 'running', $4)",diff --git a/server/services/codeAnimation/stages.js b/server/services/codeAnimation/stages.jsindex a0dfbde0e0..274d4a952f 100644--- a/server/services/codeAnimation/stages.js+++ b/server/services/codeAnimation/stages.js@@ -25,6 +25,8 @@ import * as store from './projectStore.js';import { readProjectFiles, sourceHashOf, stageProjectFiles, stageRenderSource, writeRunArtifact } from './projectFiles.js';import { checkSoundConsent, produceSoundtrack, muxSoundtrack } from './sound.js';import { renderViaMediaQueue, sampleFilm } from './stageRender.js';+import { resolveBlenderExecution } from './execution.js';+import { renderBlenderSequence, publishBlenderVideo } from './blenderRender.js';export const STAGE_RUN_KIND = 'production-stages';const STYLE_POINTS = [0.1, 0.5, 0.9];@@ -98,7 +100,7 @@ async function reserve(ctx, bytes) {*/async function runStage(ctx, key, revision, body, { renders = false } = {}) {checkBudget(ctx);- const entry = { key, stageRunId: randomUUID(), revisionId: revision.id, sourceHash: revision.sourceHash, packageHash: revision.packageHash, status: 'running', startedAt: iso() };+ const entry = { key, rendererBinding: ctx.state.renderer?.binding ?? null, stageRunId: randomUUID(), revisionId: revision.id, sourceHash: revision.sourceHash, packageHash: revision.packageHash, status: 'running', startedAt: iso() };ctx.state.stages.push(entry);await persist(ctx);const { ms, dimension } = remainingMs(ctx);@@ -121,33 +123,44 @@ async function runStage(ctx, key, revision, body, { renders = false } = {}) {}const reusable = (ctx, key, revision) => ctx.prior.find(stage => stage.key === key && stage.revisionId === revision.id- && stage.sourceHash === revision.sourceHash && stage.packageHash === revision.packageHash && stage.status === 'completed');+ && stage.sourceHash === revision.sourceHash && stage.packageHash === revision.packageHash && stage.status === 'completed'+ && (stage.rendererBinding ?? null) === (ctx.state.renderer?.binding ?? null));-/** Build the immutable, staged browser copy of a revision once per run. */+/** Read verified revision bytes; only browser source needs an HTML staging shim. */async function stageRevision(ctx, revision) {const files = await readProjectFiles(ctx.projectId, revision.id, revision.files);await reserve(ctx, revision.totalBytes);- const entryPath = entryOf(revision.manifest).path;+ const entryPath = (revision.manifest.renderer.kind === 'blender'+ ? revision.manifest.entrypoints.find(item => item.role === 'scene') || entryOf(revision.manifest) : entryOf(revision.manifest)).path;+ if (ctx.state.renderer) return { ...revision, files, staged: revision.storage.relativePath, entryPath };const staged = await stageRenderSource(ctx.projectId, ctx.runId, revision.id, files, entryPath, prepareEntry(revision.manifest));return { ...revision, files, staged: staged.directory, entryPath };}+async function blenderSequence(ctx, revision, signal, phase, options = {}) {+ return ctx.deps.blender({ revision, runtime: ctx.state.renderer, projectId: ctx.projectId, runId: ctx.runId, signal, phase,+ reserve: bytes => reserve(ctx, bytes), wallSeconds: remainingMs(ctx).ms / 1000,+ diskBytes: Math.max(1024, ctx.state.budgets.diskBytes - ctx.state.spent.diskBytes), ...options });+}+async function styleFrameStage(ctx, revision) {const prior = reusable(ctx, 'style-frame', revision);if (prior) { ctx.state.stages.push({ ...prior, reusedFrom: ctx.resumedFrom }); return prior; }return runStage(ctx, 'style-frame', revision, async ({ signal }) => {const times = styleTimes(revision.manifest.format);try {- const { frames, contract } = await ctx.deps.sample(revision.staged, { times: [], captureTimes: times, signal });+ const measured = ctx.state.renderer ? await blenderSequence(ctx, revision, signal, 'style', { captureTimes: times })+ : await ctx.deps.sample(revision.staged, { times: [], captureTimes: times, signal });+ const { frames, contract } = measured;const artifacts = [];for (const frame of frames) {await reserve(ctx, frame.bytes.length);const written = await writeRunArtifact(ctx.projectId, ctx.runId, `style-${revision.id.slice(0, 8)}-${String(frame.t).replace('.', '_')}.png`, frame.bytes);artifacts.push({ atSeconds: frame.t, ...written });}- return { contract, artifacts };+ return { contract, artifacts, ...(measured.renderer ? { renderer: measured.renderer, sceneArtifacts: measured.artifacts } : {}) };} catch (error) {- if (signal.aborted || error.code === 'CODE_ANIMATION_UNSAFE_STORAGE' || error.code === BUDGET_CODE) throw error;+ if (signal.aborted || error.code === 'CODE_ANIMATION_UNSAFE_STORAGE' || error.code === BUDGET_CODE || ['CODE_ANIMATION_BLENDER_NOT_READY', 'CODE_ANIMATION_BLENDER_READINESS_CHANGED', 'CODE_ANIMATION_BLENDER_RUNTIME_MISMATCH'].includes(error.code)) throw error;return { artifacts: [], filmError: String(error.message).slice(0, 500) };}}, { renders: true });@@ -160,15 +173,17 @@ async function pilotStage(ctx, revision, style) {return runStage(ctx, 'pilot', revision, async () => ({ samples: [], skipped: 'The film did not run, so no pilot was measured.' }));}const { fps } = revision.manifest.format;- const pilotFps = Math.min(PILOT_MAX_FPS, fps);+ const pilotFps = ctx.state.renderer ? fps : Math.min(PILOT_MAX_FPS, fps);return runStage(ctx, 'pilot', revision, async ({ signal }) => {- const { samples, contract } = await ctx.deps.sample(revision.staged, { times: sampleTimes(revision.manifest.format, pilotFps), signal });- return { pilotFps, contract, samples, capturedAt: iso() };+ const measured = ctx.state.renderer ? await blenderSequence(ctx, revision, signal, 'pilot')+ : await ctx.deps.sample(revision.staged, { times: sampleTimes(revision.manifest.format, pilotFps), signal });+ const { samples, contract } = measured;+ return { pilotFps, contract, samples, capturedAt: iso(), ...(measured.renderer ? { renderer: measured.renderer, artifacts: measured.artifacts, sequence: measured.sequence } : {}) };}, { renders: true });}const reviewPrompt = ({ manifest, artifacts }) => [- 'You review still frames of a generated browser animation against its brief. Judge style fit and composition only; do not suggest code.',+ 'You review still frames of a generated animation against its brief. Judge style fit and composition only; do not suggest code.',`Brief: ${manifest.brief.concept}`,`Style guide: ${manifest.styleGuide || 'unspecified'}`,`Frames, in order, are at seconds: ${artifacts.map(item => item.atSeconds).join(', ')}.`,@@ -238,6 +253,9 @@ function inspectStage(ctx, revision, style, pilot, review = null) {analysis = { findings: [{ kind: 'film-error', severity: 'error', detail: `The film did not run: ${style.filmError}`, measured: { error: style.filmError } }], verified: [], unverified: [{ dimension: 'visual-motion', reason: 'The film did not render.' }] };} else {analysis = analyzeEvidence({ manifest: revision.manifest, pilot, contract: pilot.contract, review });+ if (ctx.state.renderer && pilot.renderer?.baked && pilot.renderer.cameraSmooth && pilot.renderer.cadence?.length) {+ analysis.verified.push('renderer-runtime', 'stepped-transform-cadence', 'continuous-camera', 'baked-scene');+ }// The final render must be accepted by the same contract the renderer enforces; find that now, not at the end.const accepted = htmlCompositionContractSchema.safeParse(pilot.contract);if (!accepted.success) {@@ -254,8 +272,9 @@ function inspectStage(ctx, revision, style, pilot, review = null) {}const repairPrompt = ({ manifest, files, entryPath, findings }) => [- 'You repair a browser animation. Return the complete corrected HTML document only, in one ```html fence.',- 'Keep window.ANIMATION_META and window.renderFrame(t): the film must stay a pure function of t on a single <canvas>. No network, fetch or timers for animation.',+ manifest.renderer.kind === 'blender'+ ? 'Repair a Blender scene. Return the complete Python source in one ```python fence. Keep build_scene(config), deterministic baked constant subject/FX keys with portos_cadence 2 or 3, and smooth keyed camera. No live physics, external downloads or installers.'+ : 'Repair a browser animation. Return complete HTML in one ```html fence. Keep window.ANIMATION_META and window.renderFrame(t), pure time-based canvas rendering, no network or animation timers.',`Brief: ${manifest.brief.concept}`,`Format: ${manifest.format.width}x${manifest.format.height}, ${manifest.format.fps}fps, ${manifest.format.durationSeconds}s.`,'Measured findings to fix:',@@ -283,9 +302,9 @@ async function repairViaAuthoringRoute({ project, manifest, files, entryPath, fisource: 'code-animation-repair', cwd: PATHS.data, allowFallback: preflight.allowFallback,});const route = _recordEffectiveRoute(preflight.resolved, project.localSettings, result);- const html = extractAnimationHtml(result.text);- if (!html) throw new ServerError('The model response did not contain an HTML document', { status: 422, code: 'CODE_ANIMATION_REPAIR_INVALID' });- return { files: [{ path: entryPath, content: html, encoding: 'utf8' }], tokens: Math.ceil((prompt.length + result.text.length) / 4), effective: route };+ const source = manifest.renderer.kind === 'blender' ? result.text.match(/```(?:python|py)\s*\n([\s\S]*?)```/)?.[1] : extractAnimationHtml(result.text);+ if (!source) throw new ServerError('The model response did not contain the required source document', { status: 422, code: 'CODE_ANIMATION_REPAIR_INVALID' });+ return { files: [{ path: entryPath, content: source, encoding: 'utf8' }], tokens: Math.ceil((prompt.length + result.text.length) / 4), effective: route };}async function repairStage(ctx, revision, findings) {@@ -331,10 +350,23 @@ async function finalStage(ctx, revision, verdictStage, soundtrack) {const verdict = evaluateVerdict({ evidence: verdictStage.evidence, packageHash: revision.packageHash, sourceHash: revision.sourceHash, findings: verdictStage.findings, unverified: verdictStage.verdict.unverified });if (verdict.status !== 'pass') throw new ServerError(`The final render needs passing evidence (${verdict.status})`, { status: 409, code: 'CODE_ANIMATION_EVIDENCE_NOT_PASSING' });const stage = await runStage(ctx, 'final', revision, async ({ signal }) => {- const result = await ctx.deps.render({ directory: revision.staged, signal });- signal.throwIfAborted();- const audioEvidence = await ctx.deps.mux({ projectId: ctx.projectId, revision, soundtrack, result, signal, reserve: bytes => reserve(ctx, bytes) });- return { audioEvidence, output: { packageHash: revision.packageHash, audioHash: soundtrack.artifact?.sha256 ?? null, jobId: result.jobId ?? null, videoId: result.id ?? null, filename: result.filename ?? null, path: result.path ?? null, revisionId: revision.id, sourceHash: revision.sourceHash } };+ const result = ctx.state.renderer+ ? await ctx.deps.publishBlender(await blenderSequence(ctx, revision, signal, 'final'), { revision, signal, reserve: bytes => reserve(ctx, bytes) })+ : await ctx.deps.render({ directory: revision.staged, signal });+ let published = false;+ try {+ signal.throwIfAborted();+ const audioEvidence = await ctx.deps.mux({ projectId: ctx.projectId, revision, soundtrack, result, signal, reserve: bytes => reserve(ctx, bytes) });+ signal.throwIfAborted();+ if (result.commit) {+ // Publishing is the commit point: don't accept a cancellation halfway+ // through a shared history write after the soundtrack passed.+ activeRuns.get(ctx.runId).committing = true;+ await result.commit();+ }+ published = true;+ return { audioEvidence, ...(result.renderer ? { renderer: result.renderer, artifacts: result.artifacts } : {}), output: { packageHash: revision.packageHash, audioHash: soundtrack.artifact?.sha256 ?? null, jobId: result.jobId ?? null, videoId: result.id ?? null, filename: result.filename ?? null, path: result.path ?? null, revisionId: revision.id, sourceHash: revision.sourceHash } };+ } finally { if (!published) await result.cleanup?.(); }}, { renders: true });ctx.state.output = { ...stage.output, stageRunId: stage.stageRunId, audioEvidence: stage.audioEvidence, soundtrack, verifiedDimensions: [...verdictStage.verified.filter(key => key !== 'audio'), ...stage.audioEvidence.verified], unverified: [...verdict.unverified.filter(item => item.dimension !== 'audio'), ...soundtrack.unverified] };}@@ -384,7 +416,7 @@ async function finish(ctx, run) {return status;}-const defaultDeps = { sound: produceSoundtrack, mux: muxSoundtrack, sample: sampleFilm, render: renderViaMediaQueue, repair: repairViaAuthoringRoute, review: reviewViaAuthoringRoute };+const defaultDeps = { resolveBlender: resolveBlenderExecution, blender: renderBlenderSequence, publishBlender: publishBlenderVideo, sound: produceSoundtrack, mux: muxSoundtrack, sample: sampleFilm, render: renderViaMediaQueue, repair: repairViaAuthoringRoute, review: reviewViaAuthoringRoute };/*** Start a user-requested production run. Resolves with the persisted run once@@ -404,15 +436,14 @@ export async function startProductionStageRun(projectId, input, deps = {}) {const revisionId = prior ? prior.data.currentRevisionId : request.revisionId || project.candidateRevisionId || project.acceptedRevisionId;const record = revisionId ? await store.getRevisionRecord(projectId, revisionId) : null;if (!record) throw new ServerError('Import a source revision before running production stages', { status: 409, code: 'CODE_ANIMATION_NO_REVISION' });- if (record.manifest.renderer.kind !== 'browser') {- throw new ServerError('Only browser-rendered projects can run these stages', { status: 409, code: 'CODE_ANIMATION_RENDERER_UNSUPPORTED' });- }+ const resolvedBlender = record.manifest.renderer.kind === 'blender'+ ? await (deps.resolveBlender || resolveBlenderExecution)(record.manifest.renderer) : null;checkSoundConsent(record.manifest.audio, request);const revision = { ...record };const runId = randomUUID();const priorSpent = prior?.data.spent;const state = {- kind: STAGE_RUN_KIND, sourceRevisionId: revision.id, currentRevisionId: revision.id, sourceHash: revision.sourceHash,+ kind: STAGE_RUN_KIND, renderer: resolvedBlender?.provenance ?? null, sourceRevisionId: revision.id, currentRevisionId: revision.id, sourceHash: revision.sourceHash,budgets: project.budgets, requested: project.localSettings, effective: null, reservedBytes: 0,spent: { iterations: priorSpent?.iterations ?? 0, tokens: priorSpent?.tokens ?? 0, renderMs: priorSpent?.renderMs ?? 0, diskBytes: 0, elapsedMs: 0, priorElapsedMs: priorSpent?.elapsedMs ?? 0 },visualReview: request.visualReview ?? prior?.data.visualReview ?? false,@@ -440,6 +471,7 @@ export async function startProductionStageRun(projectId, input, deps = {}) {export function cancelProductionStageRun(projectId, runId) {const active = activeRuns.get(runId);if (!active || active.projectId !== projectId) throw new ServerError('That run is not active', { status: 409, code: 'CODE_ANIMATION_RUN_NOT_ACTIVE' });+ if (active.committing) throw new ServerError('The completed render is being published and can no longer be canceled', { status: 409, code: 'CODE_ANIMATION_RUN_COMMITTING' });active.controller.abort(canceledError());return { id: runId, canceling: true };}