3D engine that AI agents drive
Fix the four remaining agent tool errors: asset modules, optional lists, failed create, node IDs
Nguyen Xuan An7c9fd80d09c1
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 2d2320fe..21219064 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,8 @@## Unreleased+- Fix the next agent tool errors (part of issue #66). `scene_review` and `scene_look` with `labels` on an imported asset failed with "needs the mesh code" because asset creation loaded the on-demand scene modules only for mesh edits; it now always does, and a test walks every preview path in a fresh process. `geometries` and `materials` are optional in a recipe. A failed `scene_create` says no scene was created and to call it again. `scene_inspect` on an asset accepts a source-node ID that holds one part and names the parts of one that holds several.+- Fix the most common agent tool errors (part of issue #66). `scene_look` and `scene_review` with `labels` on an imported asset threw `Cannot read properties of undefined (reading 'map')` (an asset recipe has no materials list, and asset mesh reports are keyed by part ID); an engine fault now reaches the agent as one advice message and goes to stderr. A node that names a geometry and no material gets an explicit `default` material instead of an error. `sessionId` is optional on every tool and defaults to the active scene (189,159 to 188,872 schema bytes); an ID that names another scene is still rejected. `scene_apply` names the fix when `set-node` fields are wrapped in `node`. The bench look harness loads the on-demand scene modules, so motion recipes get a look score.- Decide on WebGPU (part of issue #56, no engine change): wait, WebGL2 stays the only backend. Headless Chrome 156 has a WebGPU adapter on the RTX 3060 with no flags, but none under the MCP `cpu` flags (`--use-angle=swiftshader`); the SwiftShader Vulkan adapter needs `--use-webgpu-adapter=swiftshader`. With three.js as a proxy on 3 bench scenes, WebGPU frames were 2.6 to 4.4 times WebGL on the GPU and 1.4 to 3.0 times on SwiftShader, and first frames were slower. Browser support, shader rewrite size (about 1,400 GLSL lines and 450 call sites) and bundle cost are in `docs/webgpu-decision.md`.diff --git a/docs/agent-scene.md b/docs/agent-scene.mdindex 48176115..0e724b60 100644--- a/docs/agent-scene.md+++ b/docs/agent-scene.md@@ -296,7 +296,7 @@ Commands can add or remove nodes and resources.Adding a duplicate ID or removing a missing ID fails.Resource removal can precede rebinding or dependent node removal in the same batch.The final recipe must contain every resource and parent referenced by surviving nodes.-Mesh nodes require both geometry and material IDs in the final recipe. A node in `scene_create` that names a geometry and leaves out the material gets the material `default` (grey, every field at its default), which is added to `materials` when missing, so the exported recipe names it. A node that names a material without a geometry is rejected: name a geometry or drop the material.+Mesh nodes require both geometry and material IDs in the final recipe. A node in `scene_create` that names a geometry and leaves out the material gets the material `default` (grey, every field at its default), which is added to `materials` when missing, so the exported recipe names it. `geometries` and `materials` may be left out of a recipe and read as empty; `nodes` is required. A node that names a material without a geometry is rejected: name a geometry or drop the material.Nonrecursive removal rejects a node that has children at that command's position in the batch.Child removal or reparenting must precede nonrecursive parent removal.diff --git a/docs/mcp.md b/docs/mcp.mdindex 161b38e9..17678853 100644--- a/docs/mcp.md+++ b/docs/mcp.md@@ -124,7 +124,7 @@ Inspect or export the recipe before retrying. Context loss still permits recipe### Tool errors-Every error an agent can reach names what failed and what to do next. `tests/tool-errors.test.js` walks the triggers and fails on a message with no next action. A JavaScript engine fault (a `TypeError` such as reading a field of `undefined`, from a bug in the server) never reaches the agent: the agent gets one advice message (check the scene with `scene_inspect`, retry once, leave out the optional field, report the tool), and the detail goes to the server's stderr. `scene_apply` also names the fix when `set-node` or `set-material` fields are wrapped in a `node` or `material` key.+Every error an agent can reach names what failed and what to do next. `tests/tool-errors.test.js` walks the triggers and fails on a message with no next action. A JavaScript engine fault (a `TypeError` such as reading a field of `undefined`, from a bug in the server) never reaches the agent: the agent gets one advice message (check the scene with `scene_inspect`, retry once, leave out the optional field, report the tool), and the detail goes to the server's stderr. A failed `scene_create` or `scene_create_asset` ends with "No scene was created ... call scene_create again", so the agent retries instead of calling `mesh_inspect` on nothing. `scene_inspect` on an imported asset takes a source-node ID (`node-40`) when the node holds exactly one part, and names the parts when it holds several. `tests/agent-preview-modules.test.js` walks every preview path (look, labels, review, snapshot, frame, GLB export, branches, mesh reports) in a fresh process where the on-demand scene modules start unloaded. `scene_apply` also names the fix when `set-node` or `set-material` fields are wrapped in a `node` or `material` key.### Tool cost and diagnosticsdiff --git a/scripts/agent-preview-browser.js b/scripts/agent-preview-browser.jsindex 01812649..fc9f5d0f 100644--- a/scripts/agent-preview-browser.js+++ b/scripts/agent-preview-browser.js@@ -461,7 +461,8 @@ window.__agentPreview = {}let asset;try {- if (input.recipe?.meshEdits) await loadAllAgentSceneModules();+ // Labels, mesh reports and motion read the on-demand modules on any asset, not only one with mesh edits.+ await loadAllAgentSceneModules();asset = await parseGltf(bytes.buffer, { maxBytes: 16 * 1024 * 1024, maxVertices: 250000, maxParts: 4096, maxTexturePixels: 4194304, maxJoints: 1024 });return createPreview(createAgentAssetScene(asset, input.recipe), input, asset);} catch (error) {diff --git a/scripts/mcp-server.mjs b/scripts/mcp-server.mjsindex da38b834..ee5d4914 100644--- a/scripts/mcp-server.mjs+++ b/scripts/mcp-server.mjs@@ -501,8 +501,8 @@ const armaturesReference = z.array(z.record(z.string(), z.unknown())).max(16).deconst recipe = z.strictObject({format: z.literal('67js.scene'),schemaVersion: z.literal(1),- geometries: z.array(geometry).max(256),- materials: z.array(z.strictObject({ id: identifier, tag: materialTag, ...materialFields })).max(256),+ geometries: z.array(geometry).max(256).optional(),+ materials: z.array(z.strictObject({ id: identifier, tag: materialTag, ...materialFields })).max(256).optional().describe('Omit for none.'),nodes: z.array(nodeRecord).max(4096),armatures: z.array(armature).max(16).optional(),camera: z.strictObject(cameraFields).optional(),@@ -602,6 +602,11 @@ function isEngineFault(message) {return ENGINE_FAULT.test(message);}+// After a failed create no scene exists, so mesh_inspect and the other tools cannot look into the failure. Agents tried+// anyway (5 of 32 errors in one recorded run) and met a second error.+const CREATE_TOOLS = new Set(['scene_create', 'scene_create_asset']);+const SCENE_NOT_CREATED_ADVICE = 'No scene was created, so the other tools have nothing to inspect: fix the recipe as the message says and call scene_create again.';+function jsonResult(value) {return { content: [{ type: 'text', text: JSON.stringify(value) }], structuredContent: value };}@@ -633,7 +638,10 @@ export function createAgentMcpServer(runtime, { version = packageMetadata.versiotry {return await run(withActiveSession(argumentsValue, inputSchema));} catch (error) {- return { isError: true, content: [{ type: 'text', text: `${name} failed: ${readableErrorMessage(error)}` }] };+ const message = readableErrorMessage(error);+ // A refused create because a scene already exists leaves that scene in place: no advice then.+ const sceneMissing = CREATE_TOOLS.has(name) && !message.startsWith('Dispose the current scene');+ return { isError: true, content: [{ type: 'text', text: `${name} failed: ${message}${sceneMissing ? ` ${SCENE_NOT_CREATED_ADVICE}` : ''}` }] };}});}diff --git a/src/agent-asset.js b/src/agent-asset.jsindex 3761e802..c2c73544 100644--- a/src/agent-asset.js+++ b/src/agent-asset.js@@ -341,6 +341,27 @@ export function createAgentAssetScene(asset, inputRecipe) {let editSignature = meshEditSignature(editedParts);let topologyRevision = 0;+ /** A part by its ID (mesh-3), or by the source node that holds exactly that one part; several or none is named in the error. */+ function partRecordFor(id) {+ const record = records.find(value => value.id === id);+ if (record) {+ return record;+ }+ const sourceNode = sourceNodes.get(id);+ if (!sourceNode) {+ throw new RangeError(`Unknown mesh ID: ${id}. Imported mesh IDs look like mesh-0, mesh-1; call scene_inspect without ids to list them, or with kind hierarchy for source nodes.`);+ }+ const partIds = sourceNode.meshIds ?? [];+ if (partIds.length === 0) {+ throw new RangeError(`Source node ${id} has no mesh of its own. Inspect a mesh ID such as mesh-0, or call scene_inspect with kind hierarchy to see which nodes hold parts.`);+ }+ if (partIds.length > 1) {+ const listed = partIds.slice(0, 8).join(', ');+ throw new RangeError(`Source node ${id} holds ${partIds.length} parts: ${listed}${partIds.length > 8 ? ', ...' : ''}. Pass the part IDs you want.`);+ }+ return records.find(value => value.id === partIds[0]);+ }+function geometryOf(record, edited = editedParts) {return edited.get(record.id)?.geometry ?? record.source.geometry;}@@ -844,13 +865,7 @@ export function createAgentAssetScene(asset, inputRecipe) {if (options.ids !== undefined && (!Array.isArray(options.ids) || options.ids.length > records.length)) {throw new RangeError('Inspection IDs must be an array within the decoded part count.');}- const selected = options.ids === undefined ? records : options.ids.map(id => {- const record = records.find(value => value.id === id);- if (!record) {- throw new RangeError(`Unknown mesh ID: ${id}. Imported mesh IDs look like mesh-0, mesh-1; call scene_inspect without ids to list them, or with kind hierarchy for source nodes.`);- }- return record;- });+ const selected = options.ids === undefined ? records : options.ids.map(id => partRecordFor(id));const visible = selected.slice(offset, offset + limit);if (options.includeBounds && visible.reduce((total, record) => total + geometryOf(record).positions.length / 3, 0) > MAX_INSPECTION_VERTICES) {throw new RangeError('Bounds inspection exceeds two million authored base vertices. Select fewer meshes.');diff --git a/src/agent-scene.js b/src/agent-scene.jsindex 02ff8f80..74f860c6 100644--- a/src/agent-scene.js+++ b/src/agent-scene.js@@ -170,7 +170,7 @@ function identifier(value) {function resources(values, maximum, label, validate) {if (!Array.isArray(values) || values.length > maximum) {- throw new RangeError(`${label} exceeds its resource limit or is not an array.`);+ throw new RangeError(`${label} exceeds its resource limit of ${maximum} or is not an array. Pass "${label}": [] for none, or remove some.`);}const seen = new Set();return values.map(value => {@@ -603,6 +603,9 @@ function normalizeRecipe(input, limits) {if (recipe.format !== '67js.scene' || recipe.schemaVersion !== 1) {throw new RangeError('Expected 67js.scene schemaVersion 1.');}+ // A scene with no mesh, or whose nodes all take the default material, has nothing to list: absent means empty.+ recipe.geometries ??= [];+ recipe.materials ??= [];recipe.geometries = resources(recipe.geometries, limits.maxGeometries, 'geometries', value => {geometryEstimate(value);const definition = { id: value.id, type: value.type };diff --git a/tests/agent-asset-mesh.test.js b/tests/agent-asset-mesh.test.jsindex d913003f..c58b5c8f 100644--- a/tests/agent-asset-mesh.test.js+++ b/tests/agent-asset-mesh.test.js@@ -242,3 +242,17 @@ test('imported parts report as polygon meshes with the shared lint', async () =>assert.throws(() => scene.inspectMeshes({ geometries: Array.from({ length: 17 }, (_, index) => `mesh-${index}`) }), /at most/);asset.dispose();});++test('inspect accepts a source-node ID that holds one part and names the parts of one that holds several', async () => {+ const scene = createScene(await loadRobot());+ const nodes = scene.inspect({ kind: 'hierarchy', limit: 256 }).nodes;+ const single = nodes.find(node => node.meshIds.length === 1);+ const several = nodes.find(node => node.meshIds.length > 1);+ const empty = nodes.find(node => node.meshIds.length === 0);+ assert.ok(single && several && empty, 'the robot has leaf, group and mesh-less nodes');+ const byNode = scene.inspect({ ids: [single.id] }).nodes;+ assert.deepEqual(byNode.map(node => node.id), single.meshIds);+ assert.throws(() => scene.inspect({ ids: [several.id] }), error => error.message.includes(several.meshIds[0]) && /holds \d+ parts/.test(error.message));+ assert.throws(() => scene.inspect({ ids: [empty.id] }), /no mesh/);+ assert.throws(() => scene.inspect({ ids: ['nothing-here'] }), /Unknown mesh ID/);+});diff --git a/tests/agent-preview-modules.test.js b/tests/agent-preview-modules.test.jsnew file mode 100644index 00000000..749680ab--- /dev/null+++ b/tests/agent-preview-modules.test.js@@ -0,0 +1,13 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { execFileSync } from 'node:child_process';+import { fileURLToPath } from 'node:url';++for (const kind of ['recipe', 'asset']) {+ test(`every preview path that reads a ${kind} scene works when the on-demand scene modules start unloaded`, () => {+ const script = fileURLToPath(new URL('./support/walk-preview-paths.mjs', import.meta.url));+ const output = execFileSync(process.execPath, [script, kind], { encoding: 'utf8' });+ const failures = JSON.parse(output.trim().split('\n').at(-1));+ assert.deepEqual(failures, []);+ });+}diff --git a/tests/agent-preview.test.js b/tests/agent-preview.test.jsindex 32b0354d..79741901 100644--- a/tests/agent-preview.test.js+++ b/tests/agent-preview.test.js@@ -1,94 +1,7 @@import test from 'node:test';import assert from 'node:assert/strict';-import { readFile } from 'node:fs/promises';-import { Script, createContext } from 'node:vm';-import { mat4 } from 'gl-matrix';-import { createAgentScene, needsMeshBooleans, loadMeshBooleans, meshBooleansLoaded, needsPhysics, loadPhysicsEngine, physicsEngineLoaded, loadAllAgentSceneModules, allAgentSceneModulesLoaded } from '../src/agent-scene.js';-import { applyProjection } from '../src/camera.js';-import { resolveAgentShadow, agentEnvironmentMap } from '../src/agent-look.js';-import { createAgentAssetScene } from '../src/agent-asset.js';-import { parseGltf } from '../src/gltf.js';-import { BRANCH_LIMITS, createBranchStore, printableLabel } from '../src/agent-branches.js';-import { sessionProblem } from '../src/agent-errors.js';import { skinnedStripAsset } from './fixtures/skinned-strip.js';--const source = (await readFile(new URL('../scripts/agent-preview-browser.js', import.meta.url), 'utf8')).replace(/^import .+;\r?$/gm, '');--function previewHarness() {- let renderError = 0;- let lost = false;- let replacementError = false;- let replacementCount = 0;- let currentRenderer;- let currentScene;- const renders = [];- const tiles = [];- const makeCanvas = () => ({ width: 768, height: 512,- replaceWith() {}, toDataURL: () => 'data:image/png;base64,cG5n',- getContext: kind => kind === '2d' ? { fillRect() {}, fillText() {}, strokeText() {},- drawImage: () => tiles.push(renders.at(-1)) } : { getExtension: () => null } });- const canvas = makeCanvas();- class FaultInjectedRenderer {- memoryPlan = { estimatedBytes: 1024 };- capabilities = { hdr: true, samples: 4 };- constructor() { currentRenderer = this; }- context = {- isContextLost: () => lost,- getError: () => renderError,- getExtension: () => null,- getParameter: () => 'Test renderer',- };- resize() {}- updateParts() {}- replaceParts() {- if (replacementError) throw new Error('Injected replacement allocation failure');- replacementCount++;- }- render(camera) {- renders.push({ camera: JSON.parse(JSON.stringify(camera)),- parts: currentScene.parts.map(part => ({ matrix: Array.from(part.matrix),- joints: Array.from(part.skin?.jointMatrices ?? []) })) });- }- dispose() {}- }- const context = createContext({- window: {},- document: { querySelector: () => canvas, createElement: makeCanvas },- // The real browser bundles these functions in one realm. Bridge only the VM realm here.- createAgentScene: input => {- const scene = createAgentScene(JSON.parse(JSON.stringify(input)));- if (scene.parts.length) currentScene = scene;- return scene;- },- createAgentAssetScene: (asset, input) => {- currentScene = createAgentAssetScene(asset, JSON.parse(JSON.stringify(input)));- const scene = currentScene;- const bridgedMethods = new Set(['sampleFrame', 'inspect', 'inspectMeshes']);- return new Proxy({}, { get: (target, field) => bridgedMethods.has(field)- ? value => scene[field](JSON.parse(JSON.stringify(value ?? {}))) : scene[field] });- },- needsMeshBooleans, loadMeshBooleans, meshBooleansLoaded, loadAllAgentSceneModules, allAgentSceneModulesLoaded,- // The harness loads Manifold from node_modules directly, so the preview's served-file loader is ignored.- setManifoldModuleLoader: () => {},- needsPhysics, loadPhysicsEngine, physicsEngineLoaded, setPhysicsModuleLoader: () => {},- parseGltf, Uint8Array, atob, sessionProblem,- applyProjection, mat4, resolveAgentShadow, agentEnvironmentMap, BRANCH_LIMITS, createBranchStore, printableLabel,- Renderer67: FaultInjectedRenderer,- // The optional addons only plug stages into a real renderer; the fault-injected one needs none.- installCameraEffects: renderer => renderer, installRenderPasses: renderer => renderer,- });- // Evaluate only trusted repository adapter code; inject the driver boundary for failure cases.- new Script(source).runInContext(context);- return {- preview: context.window.__agentPreview,- injectError: value => { renderError = value; },- loseContext: () => { lost = true; },- rejectReplacement: value => { replacementError = value; },- replacementCount: () => replacementCount,- disableHdr: () => { currentRenderer.capabilities.hdr = false; },- scene: () => currentScene, renders, tiles,- };-}+import { previewHarness } from './support/preview-harness.mjs';test('HDR fallback rejects enabling or restoring volume fog before canonical publication', () => {const harness = previewHarness();diff --git a/tests/agent-scene.test.js b/tests/agent-scene.test.jsindex 1670055e..d6347da3 100644--- a/tests/agent-scene.test.js+++ b/tests/agent-scene.test.js@@ -625,3 +625,15 @@ test('an existing default material is reused and a node with only a material stiorphan.nodes[1].material = 'finish';assert.throws(() => createAgentScene(orphan), /Name a geometry to draw it, or drop material/);});++test('a recipe without a materials or geometries list reads them as empty, and the export lists them', () => {+ const minimal = { format: '67js.scene', schemaVersion: 1,+ geometries: [{ id: 'box', type: 'box', bevel: 0 }],+ nodes: [{ id: 'part', geometry: 'box' }] };+ const exported = createAgentScene(minimal).exportRecipe();+ assert.deepEqual(exported.materials.map(material => material.id), ['default']);+ const bare = createAgentScene({ format: '67js.scene', schemaVersion: 1, nodes: [{ id: 'group' }] }).exportRecipe();+ assert.deepEqual(bare.geometries, []);+ assert.deepEqual(bare.materials, []);+ assert.throws(() => createAgentScene({ format: '67js.scene', schemaVersion: 1 }), /nodes/);+});diff --git a/tests/mcp-tools.test.js b/tests/mcp-tools.test.jsindex 45697893..8323d3b6 100644--- a/tests/mcp-tools.test.js+++ b/tests/mcp-tools.test.js@@ -467,3 +467,26 @@ test('scene_apply names the fix when the fields of set-node are wrapped in a nodoperations: [{ type: 'set-node', node: { id: 'mesh', translation: [1, 0, 0] } }] } }).catch(error => error);assert.match(String(wrapped.message ?? wrapped.content?.[0]?.text), /Move the fields of node up one level/);});++test('scene_create accepts a recipe with no materials list', async context => {+ const { client } = await connect(context);+ const minimal = recipe();+ delete minimal.materials;+ delete minimal.nodes[0].material;+ const created = await client.callTool({ name: 'scene_create', arguments: { recipe: minimal } });+ assert.equal(created.isError, undefined);+});++test('a failed scene_create says the scene was not created and what to do, so the agent retries instead of inspecting', async context => {+ const { client } = await connect(context);+ const broken = recipe();+ broken.nodes[0].geometry = 'nothing';+ const result = await client.callTool({ name: 'scene_create', arguments: { recipe: broken } });+ assert.equal(result.isError, true);+ const text = result.content[0].text;+ assert.match(text, /No scene was created/);+ assert.match(text, /call scene_create again/);+ const inspected = await client.callTool({ name: 'scene_inspect', arguments: { ids: ['mesh'] } });+ assert.equal(inspected.isError, true);+ assert.doesNotMatch(inspected.content[0].text, /No scene was created/);+});diff --git a/tests/support/preview-harness.mjs b/tests/support/preview-harness.mjsnew file mode 100644index 00000000..fdaa5cd0--- /dev/null+++ b/tests/support/preview-harness.mjs@@ -0,0 +1,89 @@+import { readFile } from 'node:fs/promises';+import { Script, createContext } from 'node:vm';+import { mat4 } from 'gl-matrix';+import { createAgentScene, needsMeshBooleans, loadMeshBooleans, meshBooleansLoaded, needsPhysics, loadPhysicsEngine, physicsEngineLoaded, loadAllAgentSceneModules, allAgentSceneModulesLoaded } from '../../src/agent-scene.js';+import { applyProjection } from '../../src/camera.js';+import { resolveAgentShadow, agentEnvironmentMap } from '../../src/agent-look.js';+import { createAgentAssetScene } from '../../src/agent-asset.js';+import { parseGltf } from '../../src/gltf.js';+import { BRANCH_LIMITS, createBranchStore, printableLabel } from '../../src/agent-branches.js';+import { sessionProblem } from '../../src/agent-errors.js';++// Runs the preview page's adapter code in a VM with a fault-injected renderer, the way the MCP preview runs it in a browser.+const source = (await readFile(new URL('../../scripts/agent-preview-browser.js', import.meta.url), 'utf8')).replace(/^import .+;\r?$/gm, '');++export function previewHarness() {+ let renderError = 0;+ let lost = false;+ let replacementError = false;+ let replacementCount = 0;+ let currentRenderer;+ let currentScene;+ const renders = [];+ const tiles = [];+ const makeCanvas = () => ({ width: 768, height: 512,+ replaceWith() {}, toDataURL: () => 'data:image/png;base64,cG5n',+ getContext: kind => kind === '2d' ? { fillRect() {}, fillText() {}, strokeText() {},+ drawImage: () => tiles.push(renders.at(-1)) } : { getExtension: () => null } });+ const canvas = makeCanvas();+ class FaultInjectedRenderer {+ memoryPlan = { estimatedBytes: 1024 };+ capabilities = { hdr: true, samples: 4 };+ constructor() { currentRenderer = this; }+ context = {+ isContextLost: () => lost,+ getError: () => renderError,+ getExtension: () => null,+ getParameter: () => 'Test renderer',+ };+ resize() {}+ updateParts() {}+ replaceParts() {+ if (replacementError) throw new Error('Injected replacement allocation failure');+ replacementCount++;+ }+ render(camera) {+ renders.push({ camera: JSON.parse(JSON.stringify(camera)),+ parts: currentScene.parts.map(part => ({ matrix: Array.from(part.matrix),+ joints: Array.from(part.skin?.jointMatrices ?? []) })) });+ }+ dispose() {}+ }+ const context = createContext({+ window: {},+ document: { querySelector: () => canvas, createElement: makeCanvas },+ // The real browser bundles these functions in one realm. Bridge only the VM realm here.+ createAgentScene: input => {+ const scene = createAgentScene(JSON.parse(JSON.stringify(input)));+ if (scene.parts.length) currentScene = scene;+ return scene;+ },+ createAgentAssetScene: (asset, input) => {+ currentScene = createAgentAssetScene(asset, JSON.parse(JSON.stringify(input)));+ const scene = currentScene;+ const bridgedMethods = new Set(['sampleFrame', 'inspect', 'inspectMeshes']);+ return new Proxy({}, { get: (target, field) => bridgedMethods.has(field)+ ? value => scene[field](JSON.parse(JSON.stringify(value ?? {}))) : scene[field] });+ },+ needsMeshBooleans, loadMeshBooleans, meshBooleansLoaded, loadAllAgentSceneModules, allAgentSceneModulesLoaded,+ // The harness loads Manifold from node_modules directly, so the preview's served-file loader is ignored.+ setManifoldModuleLoader: () => {},+ needsPhysics, loadPhysicsEngine, physicsEngineLoaded, setPhysicsModuleLoader: () => {},+ parseGltf, Uint8Array, atob, sessionProblem,+ applyProjection, mat4, resolveAgentShadow, agentEnvironmentMap, BRANCH_LIMITS, createBranchStore, printableLabel,+ Renderer67: FaultInjectedRenderer,+ // The optional addons only plug stages into a real renderer; the fault-injected one needs none.+ installCameraEffects: renderer => renderer, installRenderPasses: renderer => renderer,+ });+ // Evaluate only trusted repository adapter code; inject the driver boundary for failure cases.+ new Script(source).runInContext(context);+ return {+ preview: context.window.__agentPreview,+ injectError: value => { renderError = value; },+ loseContext: () => { lost = true; },+ rejectReplacement: value => { replacementError = value; },+ replacementCount: () => replacementCount,+ disableHdr: () => { currentRenderer.capabilities.hdr = false; },+ scene: () => currentScene, renders, tiles,+ };+}diff --git a/tests/support/walk-preview-paths.mjs b/tests/support/walk-preview-paths.mjsnew file mode 100644index 00000000..36e30af5--- /dev/null+++ b/tests/support/walk-preview-paths.mjs@@ -0,0 +1,58 @@+// Runs in a fresh process with NO scene-module preload, so the on-demand modules (mesh, motion, ...) start unloaded, the+// way they do in a new preview page. Walks every preview path that reads a scene and prints the messages of the ones that+// fail with the "loads on demand" error. tests/agent-preview-modules.test.js runs it.+import { previewHarness } from './preview-harness.mjs';+import { skinnedStripAsset } from '../fixtures/skinned-strip.js';++const recipe = {+ format: '67js.scene', schemaVersion: 1,+ geometries: [{ id: 'block', type: 'mesh', base: { type: 'box', bevel: 0 }, stack: [{ op: 'subdivide', levels: 1 }] }],+ materials: [{ id: 'paint', color: [0.4, 0.5, 0.6] }],+ nodes: [{ id: 'part', geometry: 'block', material: 'paint' }],+ motion: { duration: 1, loop: true, tracks: [{ kind: 'node', id: 'part', property: 'translation',+ keyframes: [{ time: 0, value: [0, 0, 0] }, { time: 1, value: [1, 0, 0] }] }] },+};+const assetRecipe = { format: '67js.asset', schemaVersion: 1, assetId: 'ab'.repeat(32) };++async function walk(label, createSession) {+ const harness = previewHarness();+ const sessionId = `walk-${label}`;+ await createSession(harness, sessionId);+ const { preview } = harness;+ const paths = {+ look: () => preview.look({ sessionId }),+ lookWithLabels: () => preview.look({ sessionId, labels: true }),+ review: () => {+ preview.reviewBegin({ sessionId, width: 768, height: 408 });+ return preview.reviewShot({ sessionId, index: 0, width: 384, height: 384, columns: 2, labels: true, shot: { label: 'one', rendererTime: 0 } });+ },+ snapshot: () => preview.snapshot({ sessionId, expectedRevision: 0 }),+ frame: () => preview.frame({ sessionId, rendererTime: 0 }),+ exportGlb: () => preview.exportGlb({ sessionId, maximumBytes: 32 * 1024 * 1024 }),+ inspectMeshes: () => preview.inspectMeshes({ sessionId }),+ exportRecipe: () => preview.exportRecipe({ sessionId }),+ };+ if (label === 'recipe') {+ paths.branchApply = () => preview.branchApply({ sessionId, name: 'warm', expectedRevision: 0,+ operations: [{ type: 'set-material', id: 'paint', color: [1, 0.5, 0.2] }] });+ }+ const failures = [];+ for (const [name, run] of Object.entries(paths)) {+ try {+ await run();+ } catch (error) {+ if (/loads on demand/.test(error.message)) failures.push(`${label}.${name}: ${error.message}`);+ }+ }+ return failures;+}++// The modules stay loaded for the rest of the process, so each scene kind walks in its own process: this one takes the+// kind from the command line.+const kind = process.argv[2];+const sessions = {+ recipe: (harness, sessionId) => harness.preview.create({ recipe, sessionId, backend: 'cpu', memoryBudgetMiB: 64 }),+ asset: (harness, sessionId) => harness.preview.createAsset({ sessionId, recipe: assetRecipe,+ data: Buffer.from(skinnedStripAsset()).toString('base64'), backend: 'cpu', memoryBudgetMiB: 64 }),+};+console.log(JSON.stringify(await walk(kind, sessions[kind])));