Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Fix the top agent tool errors: labels on assets, default material, optional sessionId

Nguyen Xuan Anaadbf037726d
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ac2d3096..35478019 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,8 @@
## Unreleased
+- 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.
+
- Add `67js/addons/light-bake` (part of issue #55; recipes, MCP, GLB export and reflection probes are not done). `bakeLightmaps(parts, lights, options)` traces cosine-weighted paths on the CPU against a triangle BVH and returns new parts that carry the light that bounces between surfaces (point lights and the sun, shadowed) as a lightmap texture drawn through the emissive map, with lightmap UVs from the `uv_unwrap` unwrap. The renderer and its shaders are untouched, so a scene without a bake renders as before and core size is unchanged. Bounded and deterministic: `samples`, `bounces`, `texelsPerUnit`, `maxResolution` and `maxSeconds` are range checked, texel, triangle, light and ray-work totals are checked before any ray is traced, and the same input gives the same bytes. Parts with their own maps, pattern, emission, skin or transparency are skipped and listed in the report. `npm run reference -- --bake lit-interior` takes `lit-interior` from 0.5055 to 0.1444 against Cycles (6 s bake); no other scene moved by more than 0.002. The package archive grows by 3,525 bytes (717,978 to 721,503). See `docs/light-bake.md`.
- Add recipe cloth (part of issue #62, no new tool). A `cloth` section records sheets with a position-based solver (`src/cloth.js`, loaded on demand with the new `cloth` module, no peer dependency): pinned edges, gravity, steady wind, ball and box colliders, thickness and friction, 60 frames a second, bounded by particle, frame and solver-operation limits. A seek blends two recorded frames, so the same time gives the same positions and a seek backwards repeats them (`npm run smoke:agent-cloth` repeats the PNG bytes through the MCP preview). New `grid` geometry (a flat sheet, 1 to 64 segments), `set-cloth` operation and a `cloth` report in `scene_inspect`. The tool schemas stay within the total budget: `set-physics` now takes the same record reference as `set-motion`, and the physics descriptions are shorter. A hanging sheet matches a Blender cloth bake (`scripts/blender-cloth.py`) to 0.08 percent of its height; a sheet dropped on a ball does not match, and no parity is claimed. No self collision and no soft bodies yet.
diff --git a/bench/agent-modeling/look-harness.js b/bench/agent-modeling/look-harness.js
index f3bb64f8..8f623a51 100644
--- a/bench/agent-modeling/look-harness.js
+++ b/bench/agent-modeling/look-harness.js
@@ -1,9 +1,10 @@
// Runs in the page: draws a recipe from each fixed camera, the way the MCP preview draws a scene.
-import { createAgentScene, loadMeshBooleans, needsMeshBooleans } from '/src/agent-scene.js';
+import { createAgentScene, loadAllAgentSceneModules, loadMeshBooleans, needsMeshBooleans } from '/src/agent-scene.js';
import { resolveAgentShadow } from '/src/agent-look.js';
import { Renderer67 } from '/src/renderer.js';
async function renderLookViews(recipe, views) {
+ await loadAllAgentSceneModules();
if (needsMeshBooleans(recipe)) await loadMeshBooleans();
const scene = createAgentScene(recipe);
if (recipe.motion) scene.sampleMotion(0);
diff --git a/bench/agent-modeling/look.mjs b/bench/agent-modeling/look.mjs
index 65bedb8c..7eb6b9d3 100644
--- a/bench/agent-modeling/look.mjs
+++ b/bench/agent-modeling/look.mjs
@@ -10,7 +10,7 @@
import { mkdir, readFile, writeFile } from 'node:fs/promises';
import { join, relative, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
-import { createAgentScene, loadMeshBooleans, needsMeshBooleans } from '../../src/agent-scene.js';
+import { createAgentScene, loadAllAgentSceneModules, loadMeshBooleans, needsMeshBooleans } from '../../src/agent-scene.js';
import { boundsOfGeometries, lookCameras } from './look-cameras.mjs';
import { worldGeometry } from './measure.mjs';
import { REFERENCES } from './references.mjs';
@@ -33,6 +33,7 @@ function withoutPhysics(recipe) {
/** World-space triangles of every drawn node, with motion sampled at time zero. Asset recipes have none here. */
export async function worldGeometriesOf(recipe) {
if (recipe.format === '67js.asset') return null;
+ await loadAllAgentSceneModules();
if (needsMeshBooleans(recipe)) await loadMeshBooleans();
const scene = createAgentScene(withoutPhysics(recipe));
if (recipe.motion) scene.sampleMotion(0);
diff --git a/docs/agent-scene.md b/docs/agent-scene.md
index b2053082..48176115 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.
+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.
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.md
index 0207dbb2..161b38e9 100644
--- a/docs/mcp.md
+++ b/docs/mcp.md
@@ -120,6 +120,12 @@ Inspect or export the recipe before retrying. Context loss still permits recipe
| `scene_render_result` | `jobId` | Completed output paths, hashes and metrics |
| `scene_render_release` | `jobId` | Confirmation that owned job files were removed |
+`sessionId` is optional on every tool that lists it: one scene exists at a time, so a call that leaves it out means the active scene. An ID that names another scene (an invented one, or one from a disposed scene) is still rejected with the active ID in the message, because acting on a scene the caller did not name could edit the wrong one.
+
+### 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.
+
### Tool cost and diagnostics
Every tool schema is read on every turn, so `node scripts/measure-tool-cost.mjs` reports the bytes and estimated tokens of each schema and of each typical result, and `tests/tool-cost.test.js` fails when one passes `bench/tool-cost-budgets.json`. The schemas total 173,216 bytes (about 49,500 tokens). To save space, a mesh geometry's `edits` and `stack` in a recipe, and `motion` in `scene_apply` and asset recipes, are advertised as plain objects: the full field list is in `mesh_edit`, `mesh_stack` and `scene_create`, and the backend still validates every field and names the valid choices when one is wrong. A small mesh change is far cheaper as `mesh_edit` (187 bytes in the measured case) than as a whole recipe rewrite (1,254 bytes with the dispose).
diff --git a/scripts/agent-preview-browser.js b/scripts/agent-preview-browser.js
index 7a57d134..01812649 100644
--- a/scripts/agent-preview-browser.js
+++ b/scripts/agent-preview-browser.js
@@ -317,19 +317,23 @@ function meshProblemsByGeometry(scene, geometryIds) {
}
/** Name, material tag, face tags and lint problems of the visible parts, with the pixel they project to. */
-function collectLabels(scene, camera, width, height) {
+function collectLabels(record, camera, width, height) {
+ const { scene } = record;
+ // Mesh reports of an imported asset are keyed by part ID (mesh-0); a recipe's are keyed by geometry ID.
+ const meshKeyOf = node => record.asset ? node.id : node.geometry;
const nodes = scene.inspect({ includeBounds: true }).nodes.filter(node => node.bounds);
- const materialTags = new Map(scene.exportRecipe().materials.map(material => [material.id, material.tag]));
+ // An imported asset's recipe has no materials list: its parts carry no tags.
+ const materialTags = new Map((scene.exportRecipe().materials ?? []).map(material => [material.id, material.tag]));
const view = mat4.lookAt(mat4.create(), camera.eye, camera.target, camera.up);
const matrix = mat4.multiply(mat4.create(), applyProjection(mat4.create(), camera, width / height), view);
- const geometryIds = [...new Set(nodes.map(node => node.geometry))];
+ const geometryIds = [...new Set(nodes.map(meshKeyOf))];
const meshInfo = meshProblemsByGeometry(scene, geometryIds);
const labels = [];
for (const node of nodes) {
const center = [0, 1, 2].map(axis => (node.bounds.min[axis] + node.bounds.max[axis]) / 2);
const position = projectToScreen(matrix, center, width, height);
if (!position || labels.length >= BRANCH_LIMITS.maximumLabels) continue;
- const mesh = meshInfo.get(node.geometry);
+ const mesh = meshInfo.get(meshKeyOf(node));
labels.push({ id: node.id, name: printableLabel(node.label), tag: materialTags.get(node.material) ?? null,
faceTags: mesh?.faceTags ?? [], problems: mesh?.problems ?? [], x: position.x, y: position.y });
}
@@ -386,7 +390,7 @@ window.__agentPreview = {
context.font = '12px sans-serif';
context.textBaseline = 'middle';
context.fillText(shot.label.replace(/[\r\n\t]/g, ' '), x + 8, y + 12, width - 16);
- const labels = withLabels ? collectLabels(record.scene, camera, width, height) : undefined;
+ const labels = withLabels ? collectLabels(record, camera, width, height) : undefined;
if (labels) paintLabels(context, labels, x, y + 24);
return { label: shot.label, camera, animation: record.asset ? animation : null,
motionTime: record.scene.motionTime ?? null, rendererTime: shot.rendererTime,
@@ -527,7 +531,7 @@ window.__agentPreview = {
draw(record);
const render = renderInfo(record.renderer);
record.lastRender = render;
- const labels = withLabels ? collectLabels(record.scene, record.scene.camera, canvas.width, canvas.height) : undefined;
+ const labels = withLabels ? collectLabels(record, record.scene.camera, canvas.width, canvas.height) : undefined;
return {
data: labeledPng(labels),
mimeType: 'image/png',
diff --git a/scripts/agent-runtime.mjs b/scripts/agent-runtime.mjs
index f4b82d59..9059f847 100644
--- a/scripts/agent-runtime.mjs
+++ b/scripts/agent-runtime.mjs
@@ -715,6 +715,10 @@ export function createAgentRuntime({ backend = 'gpu', browser: browserPath, memo
async releaseJob({ jobId }) {
return (await jobs()).release(jobId);
},
+ /** The ID of the one scene that exists, or null. Tools that take a sessionId default to it. */
+ activeSessionId() {
+ return activeSessionId;
+ },
close() {
if (!closing) {
phase = 'closing';
diff --git a/scripts/mcp-server.mjs b/scripts/mcp-server.mjs
index 4786ef80..6f4decb0 100644
--- a/scripts/mcp-server.mjs
+++ b/scripts/mcp-server.mjs
@@ -530,9 +530,16 @@ const assetRecipe = z.strictObject({
nodeOverrides: z.array(z.strictObject({ id: identifier, translation: vector3.optional(), rotation: quaternion.optional(), scale: z.tuple([positive, positive, positive]).optional() })).max(4096).optional(),
motion: recipeMotionReference.nullable().optional(),
});
+// Agents copy the add-node shape into set-node and set-material and wrap the fields in a node or material key. Name the
+// fix in the message instead of the bare "unrecognized key".
+function flatFieldsHint(operationType, wrapperKey) {
+ return issue => issue.code === 'unrecognized_keys' && issue.keys.includes(wrapperKey)
+ ? `${operationType} takes its fields beside type, not inside ${wrapperKey}: {"type":"${operationType}","id":"<id>",...fields}. Move the fields of ${wrapperKey} up one level.`
+ : undefined;
+}
const operation = z.discriminatedUnion('type', [
- z.strictObject({ type: z.literal('set-node'), id: identifier, geometry: identifier.optional(), material: identifier.optional(), ...nodeFields }),
- z.strictObject({ type: z.literal('set-material'), id: identifier, ...materialFields }),
+ z.strictObject({ type: z.literal('set-node'), id: identifier, geometry: identifier.optional(), material: identifier.optional(), ...nodeFields }, { error: flatFieldsHint('set-node', 'node') }),
+ z.strictObject({ type: z.literal('set-material'), id: identifier, ...materialFields }, { error: flatFieldsHint('set-material', 'material') }),
z.strictObject({ type: z.literal('set-camera'), ...cameraFields }),
z.strictObject({ type: z.literal('set-motion'), motion: recipeMotionReference.nullable() }),
z.strictObject({ type: z.literal('set-armatures'), armatures: armaturesReference.nullable() }),
@@ -553,7 +560,7 @@ const operation = z.discriminatedUnion('type', [
]);
const branchName = z.string().regex(BRANCH_NAME_PATTERN).describe('Branch name, up to 24 characters.');
const labelsFlag = z.boolean().optional().describe('Draw part names, tags and lint problems on the image; returned with pixel positions.');
-const sessionFields = { sessionId: z.uuid().describe('Session UUID returned by scene_create.') };
+const sessionFields = { sessionId: z.uuid('sessionId is not a valid UUID. Leave it out to use the active scene.').optional().describe('Leave out: the active scene is used.') };
const checkpointFields = { ...sessionFields, checkpointId: z.uuid().describe('Checkpoint UUID returned by scene_checkpoint for this session.') };
const expectedRevision = z.number().int().min(0).max(Number.MAX_SAFE_INTEGER).describe('Current revision returned by create, inspect, apply or restore. Stale edits fail atomically.');
const jobFields = { jobId: z.uuid().describe('Render job UUID returned by scene_render_submit or capabilities jobs.records.') };
@@ -575,7 +582,22 @@ const edit = { readOnlyHint: false, destructiveHint: true, idempotentHint: false
// names bundle internals the agent cannot act on, so only the message is returned.
export function readableErrorMessage(error) {
const message = error instanceof Error ? error.message : String(error);
- return message.split(/\s+at (?:\S+ \()?https?:\/\//)[0].replace(/^page\.evaluate: (?:\w*Error: )?/, '').trim();
+ const readable = message.split(/\s+at (?:\S+ \()?https?:\/\//)[0].replace(/^page\.evaluate: (?:\w*Error: )?/, '').trim();
+ if (!isEngineFault(readable)) {
+ return readable;
+ }
+ console.error(`67js internal error: ${readable}`);
+ return ENGINE_FAULT_ADVICE;
+}
+
+// The messages a JavaScript engine raises for a bug in our code (a missing field read, a wrong type called), as opposed
+// to the validation messages we write ourselves. They name no input the agent can change, so the agent gets advice and
+// the detail goes to the server log.
+const ENGINE_FAULT = /Cannot (?:read|set) propert(?:y|ies) of (?:undefined|null)|Cannot destructure|is not a function|is not iterable|is not defined|Cannot convert undefined or null/;
+const ENGINE_FAULT_ADVICE = 'Internal error in the 67js server, not caused by your input. Call scene_inspect to check the scene, retry once, and if it repeats, leave out the optional field you just added (for example labels) or report the tool name.';
+
+function isEngineFault(message) {
+ return ENGINE_FAULT.test(message);
}
function jsonResult(value) {
@@ -594,10 +616,20 @@ export function createAgentMcpServer(runtime, { version = packageMetadata.versio
error => console.error(`67js runtime cleanup failed: ${error.message}`),
);
};
+ // One scene exists at a time, so a call that leaves sessionId out means that scene. A stale or invented ID is still
+ // rejected by the runtime: acting on a scene the caller did not name could edit the wrong one.
+ function withActiveSession(argumentsValue, inputSchema) {
+ const takesSession = inputSchema.shape !== undefined && 'sessionId' in inputSchema.shape;
+ if (!takesSession || argumentsValue.sessionId !== undefined) {
+ return argumentsValue;
+ }
+ const activeSessionId = runtime.activeSessionId();
+ return activeSessionId ? { ...argumentsValue, sessionId: activeSessionId } : argumentsValue;
+ }
function register(name, description, inputSchema, annotations, run) {
server.registerTool(name, { description, inputSchema, annotations }, async argumentsValue => {
try {
- return await run(argumentsValue);
+ return await run(withActiveSession(argumentsValue, inputSchema));
} catch (error) {
return { isError: true, content: [{ type: 'text', text: `${name} failed: ${readableErrorMessage(error)}` }] };
}
diff --git a/src/agent-errors.js b/src/agent-errors.js
index 8238e0c4..86a62842 100644
--- a/src/agent-errors.js
+++ b/src/agent-errors.js
@@ -6,5 +6,5 @@ export function sessionProblem(requestedSessionId, activeSessionId) {
if (!activeSessionId) {
return 'No scene is active: it was never created, was disposed, or scene_create failed. Call scene_create or scene_create_asset first, then pass the sessionId it returns.';
}
- return `Unknown scene session ${requestedSessionId}. The active session is ${activeSessionId}; pass that sessionId, or call scene_dispose and then scene_create for a new scene.`;
+ return `Unknown scene session ${requestedSessionId}. The active session is ${activeSessionId}; leave sessionId out or pass that one, or call scene_dispose and then scene_create for a new scene.`;
}
diff --git a/src/agent-scene.js b/src/agent-scene.js
index a86cc44d..c3b62fbf 100644
--- a/src/agent-scene.js
+++ b/src/agent-scene.js
@@ -273,7 +273,7 @@ function nodeFrom(value) {
}
result.rotation = result.rotation.map(component => component / length);
if ((value.geometry !== undefined) !== (value.material !== undefined)) {
- throw new TypeError(`Node ${value.id}: set both geometry and material, or neither for a group node.`);
+ throw new TypeError(`Node ${value.id}: set both geometry and material, or neither for a group node. Name a geometry to draw it, or drop material to make it a group.`);
}
if (value.geometry !== undefined) {
identifier(value.geometry);
@@ -577,6 +577,26 @@ function addArmatures(recipe, limits) {
recipe.nodes = [...derived, ...recipe.nodes];
}
+const DEFAULT_MATERIAL_ID = 'default';
+
+/**
+ * A node that names a geometry and no material gets the material "default" (neutral grey, every field at its default),
+ * added to the recipe when it is missing, so the normalized and exported recipe stays explicit.
+ */
+function withDefaultMaterial(recipe) {
+ const materials = recipe.materials;
+ const nodes = Array.isArray(recipe.nodes) ? recipe.nodes : [];
+ const unpainted = nodes.filter(node => node?.geometry !== undefined && node.material === undefined);
+ if (unpainted.length === 0 || !Array.isArray(materials)) {
+ return materials;
+ }
+ for (const node of unpainted) {
+ node.material = DEFAULT_MATERIAL_ID;
+ }
+ const alreadyDefined = materials.some(material => material?.id === DEFAULT_MATERIAL_ID);
+ return alreadyDefined ? materials : [...materials, { id: DEFAULT_MATERIAL_ID }];
+}
+
function normalizeRecipe(input, limits) {
let recipe = copiedJson(input, limits.maxRecipeBytes);
knownKeys(recipe, ['format', 'schemaVersion', 'geometries', 'materials', 'nodes', 'armatures', 'camera', 'environment', 'effects', 'shadow', 'motion', 'physics', 'cloth'], 'recipe');
@@ -593,7 +613,7 @@ function normalizeRecipe(input, limits) {
}
return definition;
});
- recipe.materials = resources(recipe.materials, limits.maxMaterials, 'materials', materialFrom);
+ recipe.materials = resources(withDefaultMaterial(recipe), limits.maxMaterials, 'materials', materialFrom);
const distinctPatterns = new Set(recipe.materials.filter(material => material.pattern).map(material => JSON.stringify(material.pattern)));
if (distinctPatterns.size > MAX_MATERIAL_PATTERNS) {
throw new RangeError(`A scene holds at most ${MAX_MATERIAL_PATTERNS} different material patterns; it has ${distinctPatterns.size}. Reuse a pattern and tint it with color.`);
diff --git a/tests/agent-preview.test.js b/tests/agent-preview.test.js
index 630076c4..32b0354d 100644
--- a/tests/agent-preview.test.js
+++ b/tests/agent-preview.test.js
@@ -9,6 +9,7 @@ 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, '');
@@ -24,7 +25,7 @@ function previewHarness() {
const tiles = [];
const makeCanvas = () => ({ width: 768, height: 512,
replaceWith() {}, toDataURL: () => 'data:image/png;base64,cG5n',
- getContext: kind => kind === '2d' ? { fillRect() {}, fillText() {},
+ getContext: kind => kind === '2d' ? { fillRect() {}, fillText() {}, strokeText() {},
drawImage: () => tiles.push(renders.at(-1)) } : { getExtension: () => null } });
const canvas = makeCanvas();
class FaultInjectedRenderer {
@@ -62,14 +63,15 @@ function previewHarness() {
createAgentAssetScene: (asset, input) => {
currentScene = createAgentAssetScene(asset, JSON.parse(JSON.stringify(input)));
const scene = currentScene;
- return new Proxy({}, { get: (target, field) => field === 'sampleFrame'
- ? frame => scene.sampleFrame(JSON.parse(JSON.stringify(frame))) : scene[field] });
+ 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,
+ 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.
@@ -266,3 +268,18 @@ test('driver errors disclose committed revision and context loss preserves recip
assert.equal(preview.inspect({ sessionId: 'scene' }).revision, 2);
assert.equal(preview.dispose({ sessionId: 'scene' }).disposed, true);
});
+
+test('scene_look with labels names the parts of an imported asset instead of throwing', async () => {
+ const harness = previewHarness();
+ const sessionId = 'asset-labels';
+ const input = { format: '67js.asset', schemaVersion: 1, assetId: 'ab'.repeat(32) };
+ await harness.preview.createAsset({ sessionId, recipe: input,
+ data: Buffer.from(skinnedStripAsset()).toString('base64'), backend: 'cpu', memoryBudgetMiB: 64 });
+ const { metadata } = harness.preview.look({ sessionId, labels: true });
+ assert.ok(Array.isArray(metadata.labels));
+ assert.ok(metadata.labels.length > 0);
+ for (const label of metadata.labels) {
+ assert.match(label.id, /^mesh-\d+$/);
+ assert.equal(label.tag, null);
+ }
+});
diff --git a/tests/agent-scene.test.js b/tests/agent-scene.test.js
index 7ce5ca12..1670055e 100644
--- a/tests/agent-scene.test.js
+++ b/tests/agent-scene.test.js
@@ -602,3 +602,26 @@ test('topology rejects stale revisions and detached active or checkpoint matrice
assert.deepEqual(session.exportRecipe(), before);
assert.equal(session.revision, 1);
});
+
+test('a node with a geometry and no material gets an explicit default material, deterministically', () => {
+ const input = recipe();
+ delete input.nodes[0].material;
+ const first = createAgentScene(input).exportRecipe();
+ const second = createAgentScene(input).exportRecipe();
+ assert.deepEqual(first, second);
+ assert.equal(first.nodes.find(node => node.id === 'child').material, 'default');
+ assert.deepEqual(first.materials.map(material => material.id), ['finish', 'default']);
+ assert.deepEqual(createAgentScene(first).exportRecipe(), first);
+});
+
+test('an existing default material is reused and a node with only a material still names the fix', () => {
+ const input = recipe();
+ input.materials.push({ id: 'default', color: [0.9, 0.1, 0.1] });
+ delete input.nodes[0].material;
+ const exported = createAgentScene(input).exportRecipe();
+ assert.equal(exported.materials.filter(material => material.id === 'default').length, 1);
+ const orphan = recipe();
+ delete orphan.nodes[1].geometry;
+ orphan.nodes[1].material = 'finish';
+ assert.throws(() => createAgentScene(orphan), /Name a geometry to draw it, or drop material/);
+});
diff --git a/tests/mcp-tools.test.js b/tests/mcp-tools.test.js
index edf2efa2..45697893 100644
--- a/tests/mcp-tools.test.js
+++ b/tests/mcp-tools.test.js
@@ -99,6 +99,7 @@ async function connect(context) {
return { disposed: true, sessionId };
},
async close() { closed = true; },
+ activeSessionId() { return scene ? sessionId : null; },
};
const server = createAgentMcpServer(runtime);
const client = new Client({ name: '67js-boundary-test', version: '1' });
@@ -441,3 +442,28 @@ test('SDK dynamic batches create resources, reject dangling edits, and restore s
assert.equal(restored.structuredContent.inspection.counts.parts, 0);
assert.equal(restored.structuredContent.inspection.counts.geometries, 0);
});
+
+test('a tool that takes a sessionId defaults to the active scene, and still rejects a session that is not active', async context => {
+ const { client, sessionId } = await connect(context);
+ const { tools } = await client.listTools();
+ for (const tool of tools.filter(candidate => candidate.inputSchema.properties?.sessionId)) {
+ assert.ok(!tool.inputSchema.required?.includes('sessionId'), `${tool.name} must not require sessionId`);
+ }
+ await client.callTool({ name: 'scene_create', arguments: { recipe: recipe() } });
+ const inspected = await client.callTool({ name: 'scene_inspect', arguments: {} });
+ assert.equal(inspected.isError, undefined);
+ assert.equal(inspected.structuredContent.sessionId, sessionId);
+ const checkpoint = await client.callTool({ name: 'scene_checkpoint', arguments: {} });
+ assert.equal(checkpoint.isError, undefined);
+ await rejected(client, 'scene_inspect', { sessionId: 'not-a-uuid' });
+ const invalid = await client.callTool({ name: 'scene_inspect', arguments: { sessionId: 'not-a-uuid' } }).catch(error => error);
+ assert.match(String(invalid.message ?? invalid.content?.[0]?.text), /Leave it out/);
+});
+
+test('scene_apply names the fix when the fields of set-node are wrapped in a node key', async context => {
+ const { client } = await connect(context);
+ await client.callTool({ name: 'scene_create', arguments: { recipe: recipe() } });
+ const wrapped = await client.callTool({ name: 'scene_apply', arguments: { expectedRevision: 0,
+ operations: [{ 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/);
+});
diff --git a/tests/tool-errors.test.js b/tests/tool-errors.test.js
index 3bf1d000..a481e74e 100644
--- a/tests/tool-errors.test.js
+++ b/tests/tool-errors.test.js
@@ -29,7 +29,7 @@ const TRIGGERS = {
'unknown geometry field': withRecipe(recipe => { recipe.geometries[0].width = 2; }),
'node refers to a missing geometry': withRecipe(recipe => { recipe.nodes[0].geometry = 'nothing'; }),
'node refers to a missing material': withRecipe(recipe => { recipe.nodes[0].material = 'nothing'; }),
- 'node with a geometry and no material': withRecipe(recipe => { delete recipe.nodes[0].material; }),
+ 'node with a material and no geometry': withRecipe(recipe => { delete recipe.nodes[0].geometry; }),
'node parent that does not exist': withRecipe(recipe => { recipe.nodes[1].parent = 'ghost'; }),
'duplicate node id': withRecipe(recipe => { recipe.nodes.push({ id: 'body' }); }),
'opacity above one': withRecipe(recipe => { recipe.materials[0].opacity = 2; }),
@@ -81,3 +81,33 @@ test('page errors lose the evaluate prefix and the bundle stack', () => {
const error = new Error('page.evaluate: RangeError: Unknown mesh ID: node1. Use mesh-0. at Object.inspect (http://127.0.0.1:5173/preview.js:1:2) at Array.map (<anonymous>)');
assert.equal(readableErrorMessage(error), 'Unknown mesh ID: node1. Use mesh-0.');
});
+
+// Messages a JavaScript engine writes for a bug in our code. The agent must get advice instead, never the raw text.
+const ENGINE_FAULTS = [
+ new TypeError("Cannot read properties of undefined (reading 'map')"),
+ new TypeError('page.evaluate: TypeError: scene.inspect is not a function at Object.look (http://127.0.0.1:5173/preview.js:1:2)'),
+ new TypeError('undefined is not iterable (cannot read property Symbol(Symbol.iterator))'),
+ new ReferenceError('sessionProblem is not defined'),
+ new TypeError("Cannot destructure property 'id' of 'undefined' as it is undefined."),
+];
+
+for (const fault of ENGINE_FAULTS) {
+ test(`engine fault "${fault.message.slice(0, 40)}" reaches an agent as advice with a next action`, () => {
+ const originalConsoleError = console.error;
+ console.error = () => {};
+ let message;
+ try {
+ message = readableErrorMessage(fault);
+ } finally {
+ console.error = originalConsoleError;
+ }
+ assert.doesNotMatch(message, /Cannot read|Cannot destructure|is not a function|is not iterable|is not defined|undefined/i);
+ assert.match(message, /Internal error/);
+ assert.match(message, NEXT_ACTION);
+ });
+}
+
+test('the validation errors we write ourselves are not mistaken for engine faults', () => {
+ const message = 'Only mesh nodes can have a skin.';
+ assert.equal(readableErrorMessage(new TypeError(message)), message);
+});