3D engine that AI agents drive
Give a bake on a worker 90 s and extend the preview deadline for it
Nguyen Xuan An128108ebe930
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 556a521a..fe88feb7 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,7 +2,7 @@## Unreleased-- Fix the recipe light bake budget, which rejected the demo room at samples 96, bounces 2, texelsPerUnit 3 (11.5 s before the budget) and scaled `standard` there to 16 samples (part of issue #55). The ray work estimate multiplied by every light and so overcounted open scenes by about 4 times. The budget now counts path steps (texels x samples x bounces), which cost about the same per path in a closed 56 part room and in the demo room. A preset scales down to 5 million path steps (the demo room at `standard` keeps about 52 samples, not 16); explicit settings are limited only by a hard bound of 24 million path steps and by the real 20 s limit, which fails the edit with the scene unchanged and names a lower samples and texelsPerUnit to try. `bake.used` and `bake.reduced` are unchanged; the capability limit `maxRayWork` is now `maxPathWork`.+- Fix the recipe light bake budget, which rejected the demo room at samples 96, bounces 2, texelsPerUnit 3 (11.5 s before the budget) and scaled `standard` there to 16 samples (part of issue #55). The ray work estimate multiplied by every light and so overcounted open scenes by about 4 times. The budget now counts path steps (texels x samples x bounces), which cost about the same per path in a closed 56 part room and in the demo room. A preset scales down to 5 million path steps (the demo room at `standard` keeps about 52 samples, not 16); explicit settings are limited only by a hard bound of 24 million path steps and by the real 20 s limit, which fails the edit with the scene unchanged and names a lower samples and texelsPerUnit to try. A bake on a worker has 90 s instead of 20 s (the page's own thread keeps 20 s), and the preview's 30 s call deadline grows by 90 s for a `scene_create` with a `bake` and a `scene_apply` with `set-bake`. `bake.used` and `bake.reduced` are unchanged; the capability limit `maxRayWork` is now `maxPathWork`.- Make room in the npm package without adding a dependency (part of issue #36). The archive fell from 802,581 to 695,041 bytes (353,535 free under 1 MiB; the target was 300,000), and every library and MCP install stays as light as before. Two causes: (1) every one of the 80 built files began with the full `LICENSE` and `THIRD-PARTY-NOTICES.md` text, about 4 KB each; they now carry a one-line notice and the complete texts stay once at the package root, about 61,000 bytes saved; (2) the MCP SDK's Node shim pulls in Ajv (the validator for elicitation answers, about 270 KB before minification) that this server never uses, so `build/mcp/server.mjs` now bundles `scripts/mcp-sdk-shims.mjs` instead, which fails with a clear message if elicitation is ever requested: `server.mjs` fell from 677,484 to 484,111 bytes and the archive by about 47,000 bytes. `build/mcp/LICENSES.md` no longer lists the Ajv family because that code is gone, and its unused copies left `licenses/mcp/`. Measured, and not worth doing: `zod/mini` (zod's classic layer is 30 KB of the server before gzip), source maps (none are shipped), standalone core copies (none in the archive), and docs (every packaged page is linked from the README, `llms.txt`, the MCP guide or the skills). `npm run smoke:package` now loads every `exports` entry in a clean consumer. Film and site code were already outside the archive. Separate lazy-loaded packages were not built: the lazy addons together are about 157 KB gzip, so splitting them out could return at most that much, for the cost of a package, a release pipeline and a version matrix each. `archiveBytes` budget 815,000 to 705,500. Module load of the server is no slower (minimum of 25 runs, 217 and 188 ms against 231 and 209 ms).- Run the heavy scene kernels on a worker in the MCP preview (part of issue #38; edits after creation still run on the main thread). The light bake, the cloth solver, `uv_unwrap` and pattern textures are pure functions of their input, so `runKernel` in the new `src/kernel-offload.js` computes them inline as before, or, inside `buildWithKernels`, throws `KernelDeferred`, lets a module worker (`kernel-worker.js`, a package entry like the path tracer's) compute the result, caches it by a hash of the input bytes and runs the synchronous build again. The preview builds `scene_create` that way when the page has `Worker`; Node and every other caller keep the synchronous path and the same bytes (a test builds one scene cold in a separate process both ways and compares a digest of geometry, textures and the bake report). A worker error comes back with its class and message, a worker that cannot start or dies leaves the job to the inline path, and an `AbortSignal` ends the build and the worker. Measured in Node on the demo recipe: the `uv_unwrap` stack takes 3.6 s, the draft light bake 7.5 s and the standard bake passes the 20 s limit on this machine, cloth at the 10 s limit takes 3.4 s, a 1024 pattern takes 1 to 7 s, a boolean 0.12 s. Measured in headless Chrome on the GPU backend with the demo room recipe (`tests/fixtures/demo-room.recipe.json`, 9 kernels): the longest stretch the page was unresponsive during `scene_create` fell from 11.8 and 11.9 s to 1.6 s with workers (two runs each), while the build took 12.3 and 12.5 s instead of 10.9 and 11.0 s, because the kernels run one after another and the build reruns after each. `scene_inspect` now reports `kernels`: how many kernels a worker served and how many ran inline, each fallback with its reason (also a `67js kernel fallback` line on stderr when a page that has `Worker` falls back), the build time and the longest block; `npm run smoke:kernel-workers` installs the package, runs the demo room and fails unless kernels ran on the worker with no fallback. The `longtask` observer saw nothing in either mode because the browser does not count work run by a remote-debugging call, so the block is measured with a 20 ms timer. `scene_apply` edits still run on the main thread. Core did not grow (`entry:core`, `lit-box` unchanged); the lazy entries rose by about 900 bytes gzip.diff --git a/bench/tool-cost-budgets.json b/bench/tool-cost-budgets.jsonindex a64166d1..52575ce8 100644--- a/bench/tool-cost-budgets.json+++ b/bench/tool-cost-budgets.json@@ -1,5 +1,5 @@{- "measured": "2026-10-31, from scripts/measure-tool-cost.mjs; raised by 800 total and 150 for scene_apply for branch and labels fields (no new tool); raised by 650 total and 80 for scene_apply for clip layers, bone masks and retargeting through MCP; raised by 20 for scene_create and 20 for the scene_capabilities result after merging the expression language with the material graph; was 373388 schema bytes before shared IDs and recipe references; trimmed after the render-passes merge: material graph, depth of field, motion blur and passes details moved to scene_capabilities, budgets set to the measured value plus 0.5% (total 188267, scene_capabilities result 5167); raised by 95 for scene_apply and 690 for the scene_capabilities result for node relations; curve and text geometry entries shortened to a pointer at scene_capabilities curveText, budgets set to the measured value plus 0.5% (total 189468, scene_capabilities result 6399); then six modifier ops (weld, triangulate, edge_split, smooth, simple_deform, cast) added as one compact schema entry with details in scene_capabilities meshModifiers, entry and mesh_stack description shortened: total 190382 (budget unchanged at 190420), mesh_edit 34216 (budget 34220), scene_capabilities result 7042 (budget 7050); mesh_stack 11682 (budget 11690); after merging imported mesh topology with the modifier ops: raised the total to 190480 (measured 190471), mesh_edit to 34300 (measured 34293) and the scene_capabilities result to 7520 (measured 7512) for imported mesh edits; then cloth (recipe cloth, set-cloth, grid geometry) added with the total unchanged at 190480 (measured 189159): physics descriptions shortened and set-physics now takes the same record reference as set-motion, scene_create raised to 62150 and scene_apply lowered to 44130, scene_capabilities result raised to 8190 (measured 8176) for the cloth details; then particles and hair (recipe `particles`, set-particles) added with the total unchanged at 190480 (measured 189642, scene_create raised to 62350 and scene_apply to 44370 for the recipe particles reference and set-particles): the section is one record reference described in scene_capabilities, so the scene_capabilities result rose to 9570 (measured 9523) for the particle and hair fields; after merging the film timeline (recipe timeline, set-timeline) with particles: total 190719 (budget 190730), scene_create 62464, scene_apply 44620, scene_capabilities result 9902; then the path tracer renderer setting (drop z.int bounds, integers still checked by the job validator): total raised to 190830 (measured 190818); after merging the render limits and light bake with the path tracer: measured total 190013, scene_create raised to 62680 (measured 62667), scene_apply to 44860 (measured 44852) and the scene_capabilities result to 10620 (measured 10613) for the bake section and job size limits; then material layers anisotropy and iridescence (issue #51): the 16 layer fields take one short line each in the schema and their ranges and notes moved to scene_capabilities scene.materialLayers, so the scene_capabilities result rose to 12230 (measured 12168); then the sculpt and shrinkwrap mesh edits (issue #47) with the total unchanged at 190830 (measured 190612): the face rule and tag prefix descriptions shortened (the face rule text repeats in every select field), so mesh_edit rose to 33980 (measured 33960) and mesh_stack fell to 11030 (measured 11014), and the scene_capabilities result rose to 13350 (measured 13338) for the meshSculpt notes",+ "measured": "2026-10-31, from scripts/measure-tool-cost.mjs; raised by 800 total and 150 for scene_apply for branch and labels fields (no new tool); raised by 650 total and 80 for scene_apply for clip layers, bone masks and retargeting through MCP; raised by 20 for scene_create and 20 for the scene_capabilities result after merging the expression language with the material graph; was 373388 schema bytes before shared IDs and recipe references; trimmed after the render-passes merge: material graph, depth of field, motion blur and passes details moved to scene_capabilities, budgets set to the measured value plus 0.5% (total 188267, scene_capabilities result 5167); raised by 95 for scene_apply and 690 for the scene_capabilities result for node relations; curve and text geometry entries shortened to a pointer at scene_capabilities curveText, budgets set to the measured value plus 0.5% (total 189468, scene_capabilities result 6399); then six modifier ops (weld, triangulate, edge_split, smooth, simple_deform, cast) added as one compact schema entry with details in scene_capabilities meshModifiers, entry and mesh_stack description shortened: total 190382 (budget unchanged at 190420), mesh_edit 34216 (budget 34220), scene_capabilities result 7042 (budget 7050); mesh_stack 11682 (budget 11690); after merging imported mesh topology with the modifier ops: raised the total to 190480 (measured 190471), mesh_edit to 34300 (measured 34293) and the scene_capabilities result to 7520 (measured 7512) for imported mesh edits; then cloth (recipe cloth, set-cloth, grid geometry) added with the total unchanged at 190480 (measured 189159): physics descriptions shortened and set-physics now takes the same record reference as set-motion, scene_create raised to 62150 and scene_apply lowered to 44130, scene_capabilities result raised to 8190 (measured 8176) for the cloth details; then particles and hair (recipe `particles`, set-particles) added with the total unchanged at 190480 (measured 189642, scene_create raised to 62350 and scene_apply to 44370 for the recipe particles reference and set-particles): the section is one record reference described in scene_capabilities, so the scene_capabilities result rose to 9570 (measured 9523) for the particle and hair fields; after merging the film timeline (recipe timeline, set-timeline) with particles: total 190719 (budget 190730), scene_create 62464, scene_apply 44620, scene_capabilities result 9902; then the path tracer renderer setting (drop z.int bounds, integers still checked by the job validator): total raised to 190830 (measured 190818); after merging the render limits and light bake with the path tracer: measured total 190013, scene_create raised to 62680 (measured 62667), scene_apply to 44860 (measured 44852) and the scene_capabilities result to 10620 (measured 10613) for the bake section and job size limits; then material layers anisotropy and iridescence (issue #51): the 16 layer fields take one short line each in the schema and their ranges and notes moved to scene_capabilities scene.materialLayers, so the scene_capabilities result rose to 12230 (measured 12168); then the worker bake limit added workerMaxSeconds to the bake limits (result 13361, budget raised to 13370); then the sculpt and shrinkwrap mesh edits (issue #47) with the total unchanged at 190830 (measured 190612): the face rule and tag prefix descriptions shortened (the face rule text repeats in every select field), so mesh_edit rose to 33980 (measured 33960) and mesh_stack fell to 11030 (measured 11014), and the scene_capabilities result rose to 13350 (measured 13338) for the meshSculpt notes","schemaTotalBytes": 190830,"schemaToolBytes": {"scene_create": 62930,@@ -10,7 +10,7 @@},"schemaOtherToolBytes": 4000,"resultBytes": {- "scene_capabilities": 13350,+ "scene_capabilities": 13370,"scene_create": 1400,"scene_inspect": 1400,"mesh_inspect": 1200,diff --git a/docs/light-bake.md b/docs/light-bake.mdindex b49eacdf..4b19b0a2 100644--- a/docs/light-bake.md+++ b/docs/light-bake.md@@ -28,14 +28,14 @@ const renderer = new Renderer67(canvas, bakedParts, rendererOptions);| `standard` (default) | 128 | 2 | 6 || `fine` | 192 | 2 | 7 |-Ranges are 1 to 256 samples, 1 to 3 bounces and 1 to 12 texels per unit. The bake lights the rest pose with the recipe's point lights and key light (key colour times `keyIntensity`). It runs when the scene builds and again only when a part, its matrix, a light, a material or the bake fields change: camera edits, effects edits, motion seeks and renders reuse the result. A bake over 20 s fails the edit and leaves the scene as it was. The same recipe gives the same lightmap bytes. `scene_inspect` returns `bake`: the resolved fields, `used` (the samples, bounces and texelsPerUnit that were traced), `reduced`, `texels`, `rayWork`, `seconds` (of the run that made the lightmaps), `bakedParts`, `skipped` (name and reason) and `reused`.+Ranges are 1 to 256 samples, 1 to 3 bounces and 1 to 12 texels per unit. The bake lights the rest pose with the recipe's point lights and key light (key colour times `keyIntensity`). It runs when the scene builds and again only when a part, its matrix, a light, a material or the bake fields change: camera edits, effects edits, motion seeks and renders reuse the result. A bake that passes its time limit fails the edit and leaves the scene as it was. The limit is 90 s when the bake runs on a worker (the MCP preview does this, so it blocks nothing) and 20 s on the page's own thread when there is no Worker. The preview's call deadline grows by the 90 s for a `scene_create` whose recipe has a `bake` and for a `scene_apply` with `set-bake`; other calls keep 30 s. The same recipe gives the same lightmap bytes. `scene_inspect` returns `bake`: the resolved fields, `used` (the samples, bounces and texelsPerUnit that were traced), `reduced`, `texels`, `rayWork`, `seconds` (of the run that made the lightmaps), `bakedParts`, `skipped` (name and reason) and `reused`.### Work budgetThe unwrap gives the texel count before any ray is traced, so the work of a bake is plain arithmetic: path steps, texels x samples x bounces. It reads no clock and does not depend on machine speed, and the same recipe always resolves to the same numbers. Measured on this machine, a path step costs about 1.8 to 3.1 microseconds, in a closed 56 part room and in the 57 node demo room alike (the number of lights did not change it, so it is not counted).-- A preset (all three fields equal to `draft`, `standard` or `fine`) is scaled down until it fits 5 million path steps: samples by a fifth and texelsPerUnit by a tenth, repeatedly (samples not below 16, texelsPerUnit not below 1). That is 9 to 16 s of tracing, under the 20 s limit. `bake.used` shows the result and `bake.reduced` is `true`. The demo room at `standard` runs at about 52 samples and texelsPerUnit 3.94 instead of 16 and 2.32 before. A scene that cannot fit even 16 samples at texelsPerUnit 1 fails with a message to remove parts or lights.-- Explicit `samples`, `bounces` or `texelsPerUnit` (any combination that is not exactly a preset) are never reduced. They are limited by a hard bound of 24 million path steps (about 5 times the demo room at samples 96, bounces 2, texelsPerUnit 3, which bakes in 11 to 17 s), and by the real 20 s limit. Over the bound they fail before any ray is traced and the message names what fits, for example "samples 120 or fewer with texelsPerUnit 12, or texelsPerUnit 8.61 or less with samples 256". Under the bound they run, and one that passes 20 s fails with "The scene is unchanged. Try samples 128, or texelsPerUnit 3.5." (half of what was asked); the clock decides only that failure, never what is traced.+- A preset (all three fields equal to `draft`, `standard` or `fine`) is scaled down until it fits 5 million path steps: samples by a fifth and texelsPerUnit by a tenth, repeatedly (samples not below 16, texelsPerUnit not below 1). That is 9 to 16 s of tracing on an idle machine, under the 20 s inline limit, and a busy machine still finishes inside the 90 s worker limit. `bake.used` shows the result and `bake.reduced` is `true`. The demo room at `standard` runs at about 64 samples instead of 16 and 2.32 before. A scene that cannot fit even 16 samples at texelsPerUnit 1 fails with a message to remove parts or lights.+- Explicit `samples`, `bounces` or `texelsPerUnit` (any combination that is not exactly a preset) are never reduced. They are limited by a hard bound of 24 million path steps (about 5 times the demo room at samples 96, bounces 2, texelsPerUnit 3, which bakes in 11 to 17 s), and by the real time limit (90 s on a worker, 20 s inline). Over the bound they fail before any ray is traced and the message names what fits, for example "samples 120 or fewer with texelsPerUnit 12, or texelsPerUnit 8.61 or less with samples 256". Under the bound they run, and one that passes its limit fails with "The scene is unchanged. Try samples 128, or texelsPerUnit 3.5." (half of what was asked); the clock decides only that failure, never what is traced.A node that hosts cloth is skipped like a hair host: the cloth simulation replaces its geometry every frame, so a lightmap built on the rest geometry would not follow it (and the renderer refuses a light map on geometry without `lightUvs`, which failed every frame after t=0). Baked parts read every other material field live, so motion tracks on colour still work; the lightmap itself is fixed at the rest pose.diff --git a/scripts/agent-runtime.mjs b/scripts/agent-runtime.mjsindex 5aea0b2e..74ea3940 100644--- a/scripts/agent-runtime.mjs+++ b/scripts/agent-runtime.mjs@@ -6,7 +6,7 @@ import { dirname, isAbsolute, join } from 'node:path';import { createRequire } from 'node:module';import { fileURLToPath } from 'node:url';import packageMetadata from '../package.json' with { type: 'json' };-import { AGENT_SCENE_CAPABILITIES, AGENT_SCENE_DEFAULT_LIMITS, RENDER_PASS_NAMES, RENDER_PASS_DEPTH_RANGE, VIDEO_ENCODERS, MAXIMUM_VIDEO_SECONDS, MAXIMUM_JOB_SIDE, MAXIMUM_JOB_PIXELS, MAXIMUM_MEMORY_MIB } from '../src/agent-scene-capabilities.js';+import { AGENT_SCENE_CAPABILITIES, AGENT_SCENE_DEFAULT_LIMITS, RENDER_PASS_NAMES, RENDER_PASS_DEPTH_RANGE, VIDEO_ENCODERS, MAXIMUM_VIDEO_SECONDS, MAXIMUM_JOB_SIDE, MAXIMUM_JOB_PIXELS, MAXIMUM_MEMORY_MIB, BAKE_WORKER_MAXIMUM_SECONDS } from '../src/agent-scene-capabilities.js';import { PATH_TRACER_CAPABILITIES } from '../src/path-tracer-capabilities.js';import { createAgentAssetCatalog } from './agent-asset-catalog.mjs';import { createAgentRenderJobs, EXPORT_DIRECTORY_NAME } from './agent-render-jobs.mjs';@@ -30,6 +30,12 @@ const MAXIMUM_QUEUED_CALLS = 16;const MAXIMUM_GLB_BYTES = 32 * 1024 * 1024;const MAXIMUM_KEPT_GLBS = 8;const EVALUATION_TIMEOUT_MS = 30000;+/** A bake runs on a worker for up to its own limit, so a call that bakes gets that much more than a plain call. */+const BAKE_EVALUATION_TIMEOUT_MS = EVALUATION_TIMEOUT_MS + BAKE_WORKER_MAXIMUM_SECONDS * 1000;++function startsBake(operations) {+ return Array.isArray(operations) && operations.some(operation => operation?.type === 'set-bake' && operation.bake !== null && operation.bake !== undefined);+}// Decoded audio and video lengths of a finished file may differ by the encoder delay; more than this fails the job.const SYNC_TOLERANCE_SECONDS = 0.05;// The preview page imports engine chunks that sit beside the package entries, one folder above preview.js.@@ -256,16 +262,16 @@ export function createAgentRuntime({ kernelWorkers = true, backend = 'gpu', brow}}- async function invoke(method, input) {+ async function invoke(method, input, timeoutMs = EVALUATION_TIMEOUT_MS) {requireSession(input.sessionId);if (!browserInstance?.isConnected() || page.isClosed()) {phase = 'failed';throw new Error('The preview browser disconnected. The scene cannot be recovered from this runtime.');}- return evaluate(method, input);+ return evaluate(method, input, page, timeoutMs);}- async function evaluate(method, input, target = page) {+ async function evaluate(method, input, target = page, timeoutMs = EVALUATION_TIMEOUT_MS) {let timer;let timedOut = false;try {@@ -276,9 +282,9 @@ export function createAgentRuntime({ kernelWorkers = true, backend = 'gpu', browtimedOut = true;if (target === page) phase = 'failed';reject(new Error(target === page- ? 'The preview operation exceeded 30 seconds. This runtime must be closed.'- : 'The private render operation exceeded 30 seconds.'));- }, EVALUATION_TIMEOUT_MS);+ ? `The preview operation exceeded ${timeoutMs / 1000} seconds. This runtime must be closed.`+ : `The private render operation exceeded ${timeoutMs / 1000} seconds.`));+ }, timeoutMs);}),]);} catch (error) {@@ -505,7 +511,7 @@ export function createAgentRuntime({ kernelWorkers = true, backend = 'gpu', brow}await boot();const sessionId = randomUUID();- const result = await evaluate('create', { recipe, sessionId, memoryBudgetMiB: memory, backend });+ const result = await evaluate('create', { recipe, sessionId, memoryBudgetMiB: memory, backend }, page, recipe?.bake ? BAKE_EVALUATION_TIMEOUT_MS : EVALUATION_TIMEOUT_MS);activeSessionId = sessionId;return result;});@@ -549,7 +555,7 @@ export function createAgentRuntime({ kernelWorkers = true, backend = 'gpu', browconst { branch, ...rest } = input;return invoke('branchApply', { ...rest, name: validateBranchName(branch) });}- return invoke('apply', input);+ return invoke('apply', input, startsBake(input.operations) ? BAKE_EVALUATION_TIMEOUT_MS : EVALUATION_TIMEOUT_MS);});},look(input) {diff --git a/scripts/smoke-kernel-workers.mjs b/scripts/smoke-kernel-workers.mjsindex 2cb6086a..116577df 100644--- a/scripts/smoke-kernel-workers.mjs+++ b/scripts/smoke-kernel-workers.mjs@@ -55,7 +55,9 @@ try {assert.deepEqual(kernels.fallbacks, [], `No kernel may fall back to the main thread: ${JSON.stringify(kernels.fallbacks)}`);assert.doesNotMatch(diagnostics, /kernel fallback/);await client.callTool({ name: 'scene_dispose', arguments: { sessionId } }, { timeout: 60000 });- console.log(JSON.stringify({ backend, createMilliseconds, kernels }));+ const { bake } = inspected.structuredContent;+ const bakeSummary = bake ? { used: bake.used, reduced: bake.reduced, seconds: bake.seconds } : undefined;+ console.log(JSON.stringify({ backend, createMilliseconds, bake: bakeSummary, kernels }));} finally {await client.close();}diff --git a/src/agent-bake.js b/src/agent-bake.jsindex cf1ad29a..679840da 100644--- a/src/agent-bake.js+++ b/src/agent-bake.js@@ -1,7 +1,7 @@import { planLightmaps, estimateBake, traceLightmaps } from './light-bake.js';import { runKernel } from './kernel-offload.js';import { knownKeys, finiteNumber } from './agent-recipe-checks.js';-import { BAKE_PRESETS, BAKE_RANGES, BAKE_MAXIMUM_SECONDS, BAKE_PRESET_PATH_WORK, BAKE_EXPLICIT_PATH_WORK_LIMIT } from './agent-scene-capabilities.js';+import { BAKE_PRESETS, BAKE_RANGES, BAKE_MAXIMUM_SECONDS, BAKE_WORKER_MAXIMUM_SECONDS, BAKE_PRESET_PATH_WORK, BAKE_EXPLICIT_PATH_WORK_LIMIT } from './agent-scene-capabilities.js';const PRESET_SAMPLES_FLOOR = 16;@@ -124,6 +124,16 @@ function liveBakedMaterial(liveMaterial, bakedMaterial) {return Object.freeze(output);}+// Inside a worker the bake blocks nothing, so it may run longer; on the page's own thread it must stay short.+function runsOnWorker() {+ return typeof WorkerGlobalScope !== 'undefined' && globalThis instanceof WorkerGlobalScope;+}++/** The seconds a bake may run here: 90 on a worker, 20 on the page's own thread. */+export function bakeSecondsLimit() {+ return runsOnWorker() ? BAKE_WORKER_MAXIMUM_SECONDS : BAKE_MAXIMUM_SECONDS;+}+function traceWithAdvice(plan, used) {try {return traceLightmaps(plan, used);@@ -142,7 +152,7 @@ function traceWithAdvice(plan, used) {* the same RangeError here as it would inline, and the worker sends it back with its message.*/export function bakeChangedParts(snapshots, lighting, settings) {- const plan = planLightmaps(snapshots, lighting, { ...settings, maxSeconds: BAKE_MAXIMUM_SECONDS });+ const plan = planLightmaps(snapshots, lighting, { ...settings, maxSeconds: bakeSecondsLimit() });const { used, reduced } = fitSettingsToBudget(plan, settings);const { parts, report } = traceWithAdvice(plan, used);const changed = [];diff --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.jsindex 8817a7eb..55cb5b14 100644--- a/src/agent-scene-capabilities.js+++ b/src/agent-scene-capabilities.js@@ -88,7 +88,7 @@ export const RENDER_PASS_NAMES = Object.freeze(['albedo', 'normal', 'emission',// extension, no drive or protocol syntax.export const VIDEO_ENCODERS = Object.freeze(['cpu', 'nvenc']);export const MAXIMUM_VIDEO_SECONDS = 60;-/** Recipe bake presets and ranges. A bake over 20 s fails the edit before the 30 s page deadline would close the runtime. */+/** Recipe bake presets and ranges. A bake inline on the page fails the edit after 20 s, before the 30 s page deadline; on a worker it has 90 s. */export const BAKE_PRESETS = Object.freeze({draft: Object.freeze({ samples: 32, bounces: 1, texelsPerUnit: 3 }),standard: Object.freeze({ samples: 128, bounces: 2, texelsPerUnit: 6 }),@@ -96,6 +96,8 @@ export const BAKE_PRESETS = Object.freeze({});export const BAKE_RANGES = Object.freeze({ samples: [1, 256], bounces: [1, 3], texelsPerUnit: [1, 12] });export const BAKE_MAXIMUM_SECONDS = 20;+/** The limit when the bake runs on a worker, which does not block the page: a busy machine still finishes a preset. */+export const BAKE_WORKER_MAXIMUM_SECONDS = 90;/*** Path steps (texels x samples x bounces) a preset is scaled down to. Measured at 1.8 to 3.1* microseconds per path step on a closed 56 part room and the 57 node demo room, so this is 9 to 16 s, under the 20 s limit. The two rooms cost@@ -239,7 +241,7 @@ export const AGENT_SCENE_CAPABILITIES = Object.freeze({fields: 'preset, or samples (1-256), bounces (1-3), texelsPerUnit (1-12) over it. Same recipe, same bytes.',presets: BAKE_PRESETS,notes: 'Bounced light from point, spot, area and key lights. Reruns when parts, lights, materials or bake change. Skips alpha, skin, morph, hair, cloth (bake.skipped). A preset shrinks to fit (bake.used, bake.reduced); explicit settings fail over maxPathWork or past maxSeconds. No environment map or specular.',- limits: Object.freeze({ maxSeconds: BAKE_MAXIMUM_SECONDS, maxPathWork: BAKE_EXPLICIT_PATH_WORK_LIMIT, maxPointLights: 8 }),+ limits: Object.freeze({ maxSeconds: BAKE_MAXIMUM_SECONDS, workerMaxSeconds: BAKE_WORKER_MAXIMUM_SECONDS, maxPathWork: BAKE_EXPLICIT_PATH_WORK_LIMIT, maxPointLights: 8 }),}),motionLimits: Object.freeze({ maxTracks: 128, maxKeyframesPerTrack: 64, maxKeyframes: 2048, maxDuration: 30 }),});diff --git a/tests/agent-bake.test.js b/tests/agent-bake.test.jsindex 52dedf79..a13b42e1 100644--- a/tests/agent-bake.test.js+++ b/tests/agent-bake.test.js@@ -1,8 +1,8 @@import assert from 'node:assert/strict';import test from 'node:test';import { createAgentScene } from '../src/agent-scene.js';-import { normalizeAgentBake } from '../src/agent-bake.js';-import { BAKE_PRESETS, BAKE_PRESET_PATH_WORK, BAKE_EXPLICIT_PATH_WORK_LIMIT, BAKE_MAXIMUM_SECONDS } from '../src/agent-scene-capabilities.js';+import { normalizeAgentBake, bakeSecondsLimit } from '../src/agent-bake.js';+import { BAKE_PRESETS, BAKE_PRESET_PATH_WORK, BAKE_EXPLICIT_PATH_WORK_LIMIT, BAKE_MAXIMUM_SECONDS, BAKE_WORKER_MAXIMUM_SECONDS } from '../src/agent-scene-capabilities.js';function closedRoom(extra = {}) {const box = (id, translation, scale, material) => ({ id, geometry: 'box', material, translation, scale });@@ -237,6 +237,16 @@ test('an explicit bake that passes maxSeconds fails cleanly with a lower settingassert.throws(() => createAgentScene(largeRoom(slow)), error => /maxSeconds/.test(error.message) && /Try samples 128/.test(error.message));});+test('the bake kernel carries 20 s on the page thread and 90 s inside a worker', () => {+ assert.equal(bakeSecondsLimit(), BAKE_MAXIMUM_SECONDS);+ globalThis.WorkerGlobalScope = Object;+ try {+ assert.equal(bakeSecondsLimit(), BAKE_WORKER_MAXIMUM_SECONDS);+ } finally {+ delete globalThis.WorkerGlobalScope;+ }+});+function clothRoom() {const recipe = closedRoom({ cloth: { duration: 2, sheets: [{ node: 'flag', pin: ['top'] }] } });recipe.geometries.push({ id: 'sheet', type: 'grid', segments: 8 });diff --git a/tests/agent-runtime.test.js b/tests/agent-runtime.test.jsindex bac7cbfb..ce91654b 100644--- a/tests/agent-runtime.test.js+++ b/tests/agent-runtime.test.js@@ -6,7 +6,7 @@ import { readFile } from 'node:fs/promises';import { createServer } from 'node:http';import { randomUUID } from 'node:crypto';import { createContext, Script } from 'node:vm';-import { AGENT_SCENE_CAPABILITIES, AGENT_SCENE_DEFAULT_LIMITS, RENDER_PASS_NAMES, RENDER_PASS_DEPTH_RANGE, VIDEO_ENCODERS, MAXIMUM_VIDEO_SECONDS, MAXIMUM_JOB_SIDE, MAXIMUM_JOB_PIXELS, MAXIMUM_MEMORY_MIB } from '../src/agent-scene-capabilities.js';+import { AGENT_SCENE_CAPABILITIES, AGENT_SCENE_DEFAULT_LIMITS, RENDER_PASS_NAMES, RENDER_PASS_DEPTH_RANGE, VIDEO_ENCODERS, MAXIMUM_VIDEO_SECONDS, MAXIMUM_JOB_SIDE, MAXIMUM_JOB_PIXELS, MAXIMUM_MEMORY_MIB, BAKE_WORKER_MAXIMUM_SECONDS } from '../src/agent-scene-capabilities.js';import { PATH_TRACER_CAPABILITIES } from '../src/path-tracer-capabilities.js';import { audioInputArguments, createAudioLibrary, measureStreamSeconds } from '../scripts/job-audio.mjs';import { filmTimelineDuration, filmTimelineShotStarts, sampleFilmTimeline } from '../src/film-timeline.js';@@ -100,7 +100,7 @@ async function reviewRuntimeHarness({ failShot, blockShot = false, oversize = faconst context = createContext({ createServer, randomUUID, existsSync: () => true,readFile: async () => '', packageMetadata: { version: 'test' },createRequire: () => ({ resolve: () => { throw new Error('no peer in tests'); } }),- AGENT_SCENE_CAPABILITIES, AGENT_SCENE_DEFAULT_LIMITS, RENDER_PASS_NAMES, RENDER_PASS_DEPTH_RANGE, VIDEO_ENCODERS, MAXIMUM_VIDEO_SECONDS, MAXIMUM_JOB_SIDE, MAXIMUM_JOB_PIXELS, MAXIMUM_MEMORY_MIB, PATH_TRACER_CAPABILITIES,+ AGENT_SCENE_CAPABILITIES, AGENT_SCENE_DEFAULT_LIMITS, RENDER_PASS_NAMES, RENDER_PASS_DEPTH_RANGE, VIDEO_ENCODERS, MAXIMUM_VIDEO_SECONDS, MAXIMUM_JOB_SIDE, MAXIMUM_JOB_PIXELS, MAXIMUM_MEMORY_MIB, BAKE_WORKER_MAXIMUM_SECONDS, PATH_TRACER_CAPABILITIES,audioInputArguments, createAudioLibrary, measureStreamSeconds, filmTimelineDuration, filmTimelineShotStarts, sampleFilmTimeline, normalizeReview, REVIEW_LIMITS, isPreviewHost, BRANCH_LIMITS, validateBranchName,chromium: { launch: async () => browser }, URL, Buffer, process, performance, setTimeout, clearTimeout,});