3D engine that AI agents drive
MCP: several open scenes with explicit scene ids, 16 checkpoints with oldest-first eviction (part of #658)
Nguyen Xuan An090cfe1dcb63
diff --git a/changes/658.md b/changes/658.mdnew file mode 100644index 00000000..1d1e2b6c--- /dev/null+++ b/changes/658.md@@ -0,0 +1 @@+- MCP: one server holds up to 4 open scenes under a 96 MiB geometry cap; the least recently used scene is evicted with a clear error. `sessionId` (returned by `scene_create`) picks the scene on every tool, and a call without it uses the last used scene. Each scene keeps 16 checkpoints, oldest evicted first (`evictedCheckpointIds`), and a render job stays tied to its scene (#658).diff --git a/docs/agent-scene.md b/docs/agent-scene.mdindex 06868c74..4a6254b7 100644--- a/docs/agent-scene.md+++ b/docs/agent-scene.md@@ -478,7 +478,7 @@ The optional second constructor argument overrides the following positive intege| `maxVertices` | `250000`, across unique active, checkpoint, and staged geometry allocations || `maxGeometryBytes` | `33554432` || `maxOperations` | `256`, per application |-| `maxCheckpoints` | `8` |+| `maxCheckpoints` | `16` || `maxRecipeBytes` | `1048576`, also used for each command batch |Preflight accounts for peak geometry ownership before generating any new resource.diff --git a/docs/learn/agent-workflows.md b/docs/learn/agent-workflows.mdindex da331732..c5c663c5 100644--- a/docs/learn/agent-workflows.md+++ b/docs/learn/agent-workflows.md@@ -63,7 +63,7 @@ The client sends `initialize`. The server answers with its name, version and ins"maxVertices": 250000,"maxGeometryBytes": 33554432,"maxOperations": 256,- "maxCheckpoints": 8,+ "maxCheckpoints": 16,"maxRecipeBytes": 1048576},"preview": {@@ -72,7 +72,7 @@ The client sends `initialize`. The server answers with its name, version and ins"maximumWidth": 1024,"maximumHeight": 1024,"maximumImageBytes": 1048576,- "maximumActiveScenes": 1,+ "maximumActiveScenes": 4,"maximumQueuedCalls": 16,"evaluationTimeoutMs": 30000},diff --git a/docs/learn/connect-mcp.md b/docs/learn/connect-mcp.mdindex 5f3ffa99..d3f9ac62 100644--- a/docs/learn/connect-mcp.md+++ b/docs/learn/connect-mcp.md@@ -6,7 +6,7 @@ This page connects the 67js MCP server to an AI agent harness. A harness is the`67js-mcp` is a local program. The harness starts it and talks to it over stdin and stdout. It has no network listener for MCP.-The server holds one active scene. When the agent calls `scene_create`, the server starts your installed Chrome in the background and renders the scene there. It gives the agent 23 tools to build, look at and export the scene. The tools take JSON, and they never run code that the agent writes.+The server holds a few open scenes and uses the last one you used when a call has no `sessionId`. When the agent calls `scene_create`, the server starts your installed Chrome in the background and renders the scene there. It gives the agent 23 tools to build, look at and export the scene. The tools take JSON, and they never run code that the agent writes.You need two things:diff --git a/docs/learn/optimize-for-agents.md b/docs/learn/optimize-for-agents.mdindex c1180716..c85e47c5 100644--- a/docs/learn/optimize-for-agents.md+++ b/docs/learn/optimize-for-agents.md@@ -68,7 +68,7 @@ Every call is a turn. These habits remove turns:- **Batch edits.** One `scene_apply` takes up to 256 operations. Adding four legs in one call took one call and 49 ms in the local test. A call for each leg takes four.- **Read the answer, not the scene.** `scene_apply` returns the revision, the render status, a result for each operation and a diff of the IDs it changed. Call `scene_inspect` only when you need node bounds or counts.- **Edit, do not rewrite.** A small mesh change as a `mesh_edit` call is 187 bytes. The same change as a new `scene_create` is 1,202 bytes, plus 52 bytes to dispose the old scene. The gap grows with the size of the scene.-- **Leave out `sessionId`.** One scene exists at a time. Every tool uses the active scene when the field is missing.+- **Leave out `sessionId`.** Every tool uses the last used scene when the field is missing. Pass it only when you work on two scenes.- **Send the right revision.** A stale `expectedRevision` costs a failed call and a retry. Pass the `revision` from the last result.- **Compare variants with branches.** `scene_apply` with a `branch` name tries a change without touching the scene. One `scene_review` compares up to four branches. `scene_restore` with the winning `branch` keeps it.- **Checkpoint before a risky edit.** `scene_checkpoint` and `scene_restore` return to a good state in two calls. Rebuilding a scene takes many.@@ -91,7 +91,7 @@ The scene lives in the server process. The agent does not resend it on each call- **Do not resend the recipe.** After `scene_create`, send only operations. A recipe can be up to 1 MiB of JSON.- **Save the recipe.** `scene_export_recipe` returns the canonical recipe, 2,664 bytes in the measured case. Ask the agent to save it to a file after each good step. A server restart loses the active scene, and the recipe is how the agent rebuilds it.- **Keep the tool list stable.** A harness that caches the start of the prompt can reuse the cache only while the tool list stays the same. Do not switch the server on and off during a session. This is an inference that was not measured.-- **Dispose before a new scene.** One scene is active at a time. `scene_dispose` frees its memory before `scene_create` starts the next.+- **Dispose what you finished with.** The server keeps up to 4 scenes and closes the least recently used one past that. `scene_dispose` frees a scene's memory early.## Speeddiff --git a/docs/mcp.md b/docs/mcp.mdindex 913f7cd0..a0bd8f2d 100644--- a/docs/mcp.md+++ b/docs/mcp.md@@ -12,7 +12,7 @@ Release `0.9.0` adds [visual review](agent-review.md) for several labeled viewsTo see what changed, including changes not yet released, read `https://67js.codepawl.com/changelog.json`: `released` sections, `unreleased` entries and each entry's issue number and `breaking` flag.-It renders one active scene and returns PNG images through MCP image content.+It renders scenes (several can be open) and returns PNG images through MCP image content.Tool results also contain JSON text and structured metadata.The image bytes appear only in the image content block.@@ -146,7 +146,11 @@ Inspect or export the recipe before retrying. Context loss still permits recipe| `scene_render_result` | `jobId`, optional `response_format` | 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.+`sessionId` is the scene ID: `scene_create` and `scene_create_asset` return it, and every scene tool takes it. It is optional: a call that leaves it out means the last used scene. An ID that names no open scene (an invented one, one from a disposed scene, or one that was evicted) is rejected with the open IDs in the message, because acting on a scene the caller did not name could edit the wrong one.++One server keeps up to 4 scenes open, within 96 MiB of resident geometry together. Creating a scene past either cap closes the least recently used scene, and the create result lists it under `evictedSessions`; a later call with that ID fails with an `evicted` error. Save a scene with `scene_export_recipe` before it can be evicted. Only one scene holds the preview renderer at a time, so a call on another scene rebuilds it first; that costs a moment, so finish a batch of calls on one scene before switching.++Each scene keeps up to 16 checkpoints. `scene_checkpoint` returns `checkpointId`; past the limit the oldest checkpoint is evicted and the result lists it under `evictedCheckpointIds`. A `checkpointId` belongs to the scene that returned it. A render job stays tied to the scene it was submitted for. While a job runs the preview renderer is leased, so `scene_create`, edits and disposal wait for it, as before.### Tool errorsdiff --git a/scripts/agent-preview-browser.js b/scripts/agent-preview-browser.jsindex f670d6f0..1e981765 100644--- a/scripts/agent-preview-browser.js+++ b/scripts/agent-preview-browser.js@@ -27,21 +27,104 @@ import { parseRadianceHdr } from '../src/hdri.js';import { parseCube } from '../src/view-transform.js';import { weightTracksFromGltfAnimation } from '../src/export-skeleton.js';import { clipFromGltfAnimation } from '../src/skeleton-pose.js';-import { sessionProblem } from '../src/agent-errors.js';+import { sessionProblem, SCENE_STORE_LIMITS } from '../src/agent-errors.js';+import { AGENT_SCENE_DEFAULT_LIMITS } from '../src/agent-scene-capabilities.js';import { describeApplication } from '../src/agent-apply-report.js';import { framingProblems, exposureProblems, lumaShares } from '../src/frame-checks.js';import { BRANCH_LIMITS, createBranchStore, printableLabel } from '../src/agent-branches.js';import { agentAssetDecodeOptions, withCatalogLimitAdvice } from '../src/agent-asset-limits.js';import { sceneQueryFor, summarizeWalkMap, walkOptionsFor, createQueryOnlyCache } from './agent-walkmap.js';-let active = null;+// Open scenes by sessionId, least recently used first. One canvas serves them all, so at most one record owns a renderer;+// a call on another scene hands the canvas over (the scene data stays, the renderer is rebuilt).+const records = new Map();+// The scene whose renderer a render job holds; no scene gets a renderer until the job gives it back.+let leasedRecord = null;+const EVICTED_SESSIONS_KEPT = 32;+const evictedSessions = [];let canvas = document.querySelector('canvas');+function sessionError(sessionId) {+ const openSessionIds = [...records.keys()];+ return new Error(sessionProblem(sessionId, openSessionIds.at(-1), { openSessionIds, evictedSessionIds: evictedSessions }));+}++function lookupSession(sessionId) {+ const record = records.get(sessionId);+ if (!record) throw sessionError(sessionId);+ // Re-insert so the Map order stays least to most recently used.+ records.delete(sessionId);+ records.set(sessionId, record);+ return record;+}++function releaseOtherRenderers(keep) {+ let released = false;+ for (const other of records.values()) {+ if (other === keep || !other.renderer) continue;+ other.renderer.dispose();+ other.renderer = null;+ released = true;+ }+ if (released) resetCanvas();+}+function requireSession(sessionId) {- if (!active || active.sessionId !== sessionId) {- throw new Error(sessionProblem(sessionId, active?.sessionId));+ const record = lookupSession(sessionId);+ if (record.renderer || leasedRecord) return record;+ releaseOtherRenderers(record);+ record.renderer = initializeRenderer(record.scene, record.options);+ record.rendererTopology = record.scene.topologyRevision;+ record.rendererTextured = sceneIsTextured(record.scene);+ record.shadowKey = null;+ return record;+}++function requireCheckpoint(record, checkpointId) {+ if (record.checkpoints.has(checkpointId)) return;+ const kept = [...record.checkpoints.keys()];+ const reason = record.evictedCheckpointIds.includes(checkpointId)+ ? `was evicted as the oldest when more than ${AGENT_SCENE_DEFAULT_LIMITS.maxCheckpoints} were saved`+ : 'is unknown or was released';+ throw new Error(`checkpointId ${checkpointId} ${reason}. Pass a checkpointId that scene_checkpoint returned for sessionId ${record.sessionId}${kept.length ? `: ${kept.join(', ')}` : '; this scene has none, so call scene_checkpoint first'}.`);+}++function releaseRecord(record) {+ try {+ record.renderer?.dispose();+ } finally {+ record.asset?.dispose();+ disposePlacedAssets(record.placedAssets);+ }+ record.checkpoints.clear();+ record.branches.clear();+ records.delete(record.sessionId);+}++function residentBytesOf(record) {+ return record.scene.inspect().residentGeometryBytes ?? 0;+}++// Close the least recently used scenes until `incoming` more scenes of `incomingBytes` fit, and name them to the caller.+function evictForNewScene(incomingBytes) {+ const evicted = [];+ let bytes = incomingBytes;+ const sizes = new Map();+ for (const record of records.values()) {+ const size = residentBytesOf(record);+ sizes.set(record, size);+ bytes += size;}- return active;+ for (const record of [...records.values()]) {+ const overCount = records.size + 1 > SCENE_STORE_LIMITS.maxOpenScenes;+ if (!overCount && bytes <= SCENE_STORE_LIMITS.maxOpenSceneBytes) break;+ bytes -= sizes.get(record);+ releaseRecord(record);+ evicted.push(record.sessionId);+ evictedSessions.push(record.sessionId);+ }+ evictedSessions.splice(0, Math.max(0, evictedSessions.length - EVICTED_SESSIONS_KEPT));+ return evicted;}function bytesFromBase64(data) {@@ -468,22 +551,22 @@ function objectMotionFor(record, motionTime, forVelocity = false) {}function createPreview(scene, { sessionId, memoryBudgetMiB, backend, transparent = false }, asset, placedAssets, sequenceFrames) {- if (active) {- throw new Error('Dispose the current scene before creating another.');- }+ if (leasedRecord) throw new Error('The scene renderer is leased to a render job.');validatePreviewCamera(scene.camera);let renderer;try {+ releaseOtherRenderers(null);renderer = initializeRenderer(scene, { memoryBudgetMiB, backend, transparent });const record = { scene, renderer, asset, placedAssets, sessionId, options: { memoryBudgetMiB, backend, transparent },- checkpoints: new Map(), branches: createBranchStore(), rendererTopology: scene.topologyRevision, rendererTextured: sceneIsTextured(scene), sequenceFrames };+ checkpoints: new Map(), evictedCheckpointIds: [], branches: createBranchStore(), rendererTopology: scene.topologyRevision, rendererTextured: sceneIsTextured(scene), sequenceFrames };draw(record);const result = status(record);if (backend === 'gpu' && /swiftshader|llvmpipe|software/i.test(result.render.graphics)) {throw new Error('Hardware GPU rendering was requested, but the browser selected a software renderer.');}- active = record;- return result;+ const evicted = evictForNewScene(result.inspection.residentGeometryBytes ?? 0);+ records.set(sessionId, record);+ return evicted.length ? { ...result, evictedSessions: evicted } : result;} catch (error) {renderer?.dispose();// A throwing constructor may already own GPU objects without returning an instance.@@ -793,16 +876,17 @@ window.__agentPreview = {clips: record.asset?.animations.map(clip => ({ duration: clip.duration })) ?? [] };},suspend({ sessionId }) {- const record = requireSession(sessionId);- if (!record.renderer) throw new Error('Scene renderer is already suspended.');- record.renderer.dispose();- record.renderer = null;+ const record = lookupSession(sessionId);+ if (leasedRecord) throw new Error('Scene renderer is already suspended.');+ releaseOtherRenderers(null);resetCanvas();+ leasedRecord = record;return { sessionId, revision: record.scene.revision, suspended: true };},resume({ sessionId }) {- const record = requireSession(sessionId);- if (record.renderer) throw new Error('Scene renderer is already active.');+ const record = lookupSession(sessionId);+ if (leasedRecord !== record) throw new Error('Scene renderer is already active.');+ leasedRecord = null;try {record.renderer = initializeRenderer(record.scene, record.options);record.rendererTopology = record.scene.topologyRevision;@@ -953,7 +1037,6 @@ window.__agentPreview = {},create(input) {registerLookData(input.lookData);- if (active)throw new Error('Dispose the current scene before creating another.');if (recipeAssetNeeds(input.recipe).length) return this.createWithAssets(input);// Only a recipe with image sequences waits for its frames to decode; any other create stays synchronous.const build = sequenceFrames => {@@ -972,7 +1055,6 @@ window.__agentPreview = {return afterMeshBooleans(input.recipe, () => (input.sequenceData ? loadSequenceFrames(new Map(), input.sequenceData).then(build) : build(new Map())));},async createAsset(input) {- if (active) throw new Error('Dispose the current scene before creating another.');const bytes = bytesFromBase64(input.data);let asset;try {@@ -1094,9 +1176,19 @@ window.__agentPreview = {},checkpoint({ sessionId, checkpointId }) {const record = requireSession(sessionId);+ // The oldest checkpoint goes first when the scene is at its limit; the answer names it so the agent can drop it from its notes.+ const evictedCheckpointIds = [];+ while (record.checkpoints.size >= AGENT_SCENE_DEFAULT_LIMITS.maxCheckpoints) {+ const [oldestId, oldest] = record.checkpoints.entries().next().value;+ record.scene.releaseCheckpoint(oldest.handle);+ record.checkpoints.delete(oldestId);+ record.evictedCheckpointIds.push(oldestId);+ evictedCheckpointIds.push(oldestId);+ }+ record.evictedCheckpointIds.splice(0, Math.max(0, record.evictedCheckpointIds.length - EVICTED_SESSIONS_KEPT));const handle = record.scene.checkpoint();record.checkpoints.set(checkpointId, { handle, fogDensity: record.scene.environment.volumeFog.density });- return { sessionId, checkpointId, revision: record.scene.revision };+ return { sessionId, checkpointId, revision: record.scene.revision, ...(evictedCheckpointIds.length ? { evictedCheckpointIds } : {}) };},restore({ sessionId, checkpointId, revision, expectedRevision }) {const record = requireSession(sessionId);@@ -1104,9 +1196,7 @@ window.__agentPreview = {record.scene.restoreRevision(revision, { expectedRevision });return mutationStatus(record);}- if (!record.checkpoints.has(checkpointId)) {- throw new Error('Unknown or released checkpoint.');- }+ requireCheckpoint(record, checkpointId);const checkpoint = record.checkpoints.get(checkpointId);if (checkpoint.fogDensity > 0 && !record.renderer.capabilities.hdr) {throw new Error('Volumetric fog requires HDR support; this preview cannot restore it.');@@ -1116,9 +1206,7 @@ window.__agentPreview = {},releaseCheckpoint({ sessionId, checkpointId }) {const record = requireSession(sessionId);- if (!record.checkpoints.has(checkpointId)) {- throw new Error('Unknown or released checkpoint.');- }+ requireCheckpoint(record, checkpointId);record.scene.releaseCheckpoint(record.checkpoints.get(checkpointId).handle);record.checkpoints.delete(checkpointId);return { sessionId, checkpointId, released: true };@@ -1170,16 +1258,7 @@ window.__agentPreview = {parts: parts.length, clips: options.clips?.length ?? 0, data: bytesToBase64(new Uint8Array(binary)) };},dispose({ sessionId }) {- const record = requireSession(sessionId);- try {- record.renderer?.dispose();- } finally {- record.asset?.dispose();- disposePlacedAssets(record.placedAssets);- }- record.checkpoints.clear();- record.branches.clear();- active = null;+ releaseRecord(lookupSession(sessionId));return { sessionId, disposed: true };},};diff --git a/scripts/agent-render-jobs.mjs b/scripts/agent-render-jobs.mjsindex c869c762..254dfaa8 100644--- a/scripts/agent-render-jobs.mjs+++ b/scripts/agent-render-jobs.mjs@@ -517,7 +517,7 @@ export async function createAgentRenderJobs({ root, run, limits: inputLimits = {const runnerDirectory = await directoryFor(record.jobId);if (controller.signal.aborted) throw controller.signal.reason;const completed = await run({- jobId: record.jobId, directory: runnerDirectory, snapshot, settings: structuredClone(record.settings), signal: controller.signal,+ jobId: record.jobId, sessionId: job.sessionId, directory: runnerDirectory, snapshot, settings: structuredClone(record.settings), signal: controller.signal,progress(update) {objectKeys(update, ['frames', 'maximumPendingFrames'], 'progress');if (controller.signal.aborted) throw controller.signal.reason;@@ -591,7 +591,7 @@ export async function createAgentRenderJobs({ root, run, limits: inputLimits = {async submit(input) {if (closed) throw new Error('Render job controller is closed.');if (active || admission) throw new Error('A render job is already active. No additional jobs are queued.');- objectKeys(input, ['sourceRevision', 'snapshot', 'settings'], 'submission');+ objectKeys(input, ['sessionId', 'sourceRevision', 'snapshot', 'settings'], 'submission');const sourceRevision = boundedNumber(input.sourceRevision, 0, Number.MAX_SAFE_INTEGER, 'source revision', true);objectKeys(input.snapshot, ['recipe', 'assetBytes', 'clips'], 'snapshot');const clips = jsonCopy(input.snapshot.clips ?? []);@@ -618,7 +618,7 @@ export async function createAgentRenderJobs({ root, run, limits: inputLimits = {const record = { schemaVersion: 1, jobId, sourceRevision, state: 'queued', settings, progress: { frames: 0, maximumPendingFrames: 0 }, artifacts: [] };await writeFile(join(staging, 'status.json'), JSON.stringify(record), { flag: 'wx', mode: 0o600 });await rename(staging, directory);- const job = { record, controller: new AbortController(), persistence: Promise.resolve() };+ const job = { record, sessionId: input.sessionId, controller: new AbortController(), persistence: Promise.resolve() };jobs.set(jobId, job);active = job;const result = structuredClone(record);diff --git a/scripts/agent-runtime.mjs b/scripts/agent-runtime.mjsindex 58d6808b..2d53295a 100644--- a/scripts/agent-runtime.mjs+++ b/scripts/agent-runtime.mjs@@ -32,7 +32,7 @@ import { isPreviewHost } from './preview-host.mjs';import { normalizeReview, REVIEW_LIMITS } from './agent-review.mjs';import { mergeFrameDiagnostics } from '../src/frame-checks.js';import { BRANCH_LIMITS, validateBranchName } from '../src/agent-branches.js';-import { sessionProblem } from '../src/agent-errors.js';+import { sessionProblem, SCENE_STORE_LIMITS } from '../src/agent-errors.js';const SCENE_LIMITS = AGENT_SCENE_DEFAULT_LIMITS;const MAXIMUM_IMAGE_BYTES = 1024 * 1024;@@ -44,6 +44,7 @@ const MAXIMUM_OBJECT_NAMES = 1000;// A path trace shares the machine with the person using it, so it takes half of the eight-thread ceiling.const PATH_TRACER_THREADS = 8;const MAXIMUM_QUEUED_CALLS = 16;+const MAXIMUM_REMEMBERED_EVICTIONS = 32;const MAXIMUM_GLB_BYTES = 32 * 1024 * 1024;const MAXIMUM_KEPT_GLBS = 8;const EVALUATION_TIMEOUT_MS = 30000;@@ -105,9 +106,12 @@ export function createAgentRuntime({ kernelWorkers = true, backend = 'gpu', browlet page;let reviewPage;let cancelReview;- let activeSessionId = null;- // Whether the active scene has a bake, so an edit that rebakes gets the longer deadline.- let activeSceneHasBake = false;+ // Open scenes, least recently used first; the last one is what a call without a sessionId means.+ const openSessionIds = new Set();+ // Scenes the page closed to stay under the scene cap, so a later call with one of them gets a clear error.+ const evictedSessionIds = [];+ // Scenes that have a bake, so an edit that rebakes gets the longer deadline.+ const bakedSessionIds = new Set();let queuedCalls = 0;let queue = Promise.resolve();let closing;@@ -358,10 +362,40 @@ export function createAgentRuntime({ kernelWorkers = true, backend = 'gpu', brow}}+ function lastUsedSessionId() {+ let lastUsed = null;+ for (const sessionId of openSessionIds) lastUsed = sessionId;+ return lastUsed;+ }++ function forgetSession(sessionId) {+ openSessionIds.delete(sessionId);+ bakedSessionIds.delete(sessionId);+ }++ function forgetAllSessions() {+ openSessionIds.clear();+ bakedSessionIds.clear();+ }+function requireSession(sessionId) {- if (!activeSessionId || sessionId !== activeSessionId) {- throw new Error(sessionProblem(sessionId, activeSessionId));+ if (!openSessionIds.has(sessionId)) {+ throw new Error(sessionProblem(sessionId, lastUsedSessionId(), { openSessionIds: [...openSessionIds], evictedSessionIds }));}+ // Re-insert so the Set order stays least to most recently used.+ openSessionIds.delete(sessionId);+ openSessionIds.add(sessionId);+ }++ // The page returns the scenes it closed to make room; the runtime forgets them and remembers why they are gone.+ function registerCreatedScene(sessionId, result, hasBake) {+ for (const evictedSessionId of result.evictedSessions ?? []) {+ forgetSession(evictedSessionId);+ evictedSessionIds.push(evictedSessionId);+ }+ evictedSessionIds.splice(0, Math.max(0, evictedSessionIds.length - MAXIMUM_REMEMBERED_EVICTIONS));+ openSessionIds.add(sessionId);+ if (hasBake) bakedSessionIds.add(sessionId);}async function invoke(method, input, timeoutMs = EVALUATION_TIMEOUT_MS) {@@ -393,7 +427,7 @@ export function createAgentRuntime({ kernelWorkers = true, backend = 'gpu', brow} catch (error) {if (timedOut) {if (target === page) {- activeSessionId = null;+ forgetAllSessions();await shutdownResources();} else {await target.close();@@ -405,13 +439,12 @@ export function createAgentRuntime({ kernelWorkers = true, backend = 'gpu', brow}}- async function runJob({ jobId, directory, snapshot, settings, signal, progress }) {+ async function runJob({ jobId, sessionId, directory, snapshot, settings, signal, progress }) {let jobPage;let encoder;let frameReceiver;let pageEncodes = false;let suspended = false;- const sessionId = activeSessionId;const started = performance.now();const metrics = { backend, requestedWidth: settings.width, requestedHeight: settings.height,renderSeconds: 0, captureSeconds: 0, peakNodeBytes: 0, peakBrowserHeap: 0, maximumPendingFrames: 1 };@@ -723,7 +756,7 @@ export function createAgentRuntime({ kernelWorkers = true, backend = 'gpu', browreturn {scene: { ...AGENT_SCENE_CAPABILITIES, postPasses: USER_PASS_CAPABILITIES, meshBlend: MESH_BLEND_CAPABILITIES, materialSnippet: MATERIAL_SNIPPET_CAPABILITIES, vegetation: VEGETATION_CAPABILITY_NOTE, crowd: CROWD_CAPABILITY_NOTE, textureSequence: TEXTURE_SEQUENCE_CAPABILITIES },sceneLimits: SCENE_LIMITS,- preview: { backend, memoryBudgetMiB: memory, maximumWidth: 1024, maximumHeight: 1024, maximumImageBytes: MAXIMUM_IMAGE_BYTES, maximumActiveScenes: 1, maximumQueuedCalls: MAXIMUM_QUEUED_CALLS, evaluationTimeoutMs: EVALUATION_TIMEOUT_MS },+ preview: { backend, memoryBudgetMiB: memory, maximumWidth: 1024, maximumHeight: 1024, maximumImageBytes: MAXIMUM_IMAGE_BYTES, maximumActiveScenes: SCENE_STORE_LIMITS.maxOpenScenes, maximumOpenSceneBytes: SCENE_STORE_LIMITS.maxOpenSceneBytes, maximumQueuedCalls: MAXIMUM_QUEUED_CALLS, evaluationTimeoutMs: EVALUATION_TIMEOUT_MS },review: { ...REVIEW_LIMITS, backend, memoryBudgetMiB: memory, evaluationTimeoutMs: EVALUATION_TIMEOUT_MS,totalTimeoutMs: EVALUATION_TIMEOUT_MS,sourcePreserved: true, defaultMotionTime: null, defaultRendererTime: 0, branches: BRANCH_LIMITS },@@ -748,14 +781,11 @@ export function createAgentRuntime({ kernelWorkers = true, backend = 'gpu', brow},create({ recipe }) {return enqueue(async () => {- if (activeSessionId) {- throw new Error('Dispose the current scene before creating another.');- }+ await requirePreviewRenderer();await boot();const sessionId = randomUUID();const result = await evaluate('create', { recipe, sessionId, memoryBudgetMiB: memory, backend, ...(await placedAssetData(recipe)) }, page, recipe?.bake ? BAKE_EVALUATION_TIMEOUT_MS : EVALUATION_TIMEOUT_MS);- activeSessionId = sessionId;- activeSceneHasBake = Boolean(recipe?.bake);+ registerCreatedScene(sessionId, result, Boolean(recipe?.bake));return result;});},@@ -764,12 +794,12 @@ export function createAgentRuntime({ kernelWorkers = true, backend = 'gpu', brow},createAsset({ recipe }) {return enqueue(async () => {- if (activeSessionId) throw new Error('Dispose the current scene before creating another.');+ await requirePreviewRenderer();const bytes = await (await catalog()).read(recipe.assetId);await boot();const sessionId = randomUUID();const result = await evaluate('createAsset', { recipe, data: bytes.toString('base64'), sessionId, memoryBudgetMiB: memory, backend, ...(await motionSources([recipe.motion])) });- activeSessionId = sessionId;+ registerCreatedScene(sessionId, result, false);return result;});},@@ -813,10 +843,12 @@ export function createAgentRuntime({ kernelWorkers = true, backend = 'gpu', browreturn invoke('branchApply', { ...rest, name: validateBranchName(branch) });}const bakeAfter = bakeAfterOperations(input.operations);- const rebakes = activeSceneHasBake || bakeAfter === true;+ const hadBake = bakedSessionIds.has(input.sessionId);+ const rebakes = hadBake || bakeAfter === true;const motions = (input.operations ?? []).filter(operation => operation.type === 'set-motion').map(operation => operation.motion);const applied = await invoke('apply', { ...input, ...(await motionSources(motions)), ...(await placedAssetData(input.operations)) }, rebakes ? BAKE_EVALUATION_TIMEOUT_MS : EVALUATION_TIMEOUT_MS);- activeSceneHasBake = bakeAfter ?? activeSceneHasBake;+ if (bakeAfter ?? hadBake) bakedSessionIds.add(input.sessionId);+ else bakedSessionIds.delete(input.sessionId);return applied;});},@@ -1003,7 +1035,7 @@ export function createAgentRuntime({ kernelWorkers = true, backend = 'gpu', browreturn enqueue(async () => {await requirePreviewRenderer();const result = await invoke('dispose', input);- activeSessionId = null;+ forgetSession(input.sessionId);return result;});},@@ -1029,7 +1061,7 @@ export function createAgentRuntime({ kernelWorkers = true, backend = 'gpu', browconst assetBytes = snapshot.recipe.format === '67js.asset' ? await (await catalog()).read(snapshot.recipe.assetId) : undefined;phase = 'rendering';try {- return await controller.submit({ sourceRevision: snapshot.sourceRevision,+ return await controller.submit({ sessionId, sourceRevision: snapshot.sourceRevision,snapshot: { recipe: snapshot.recipe, clips: snapshot.clips, ...(assetBytes ? { assetBytes } : {}) }, settings });} catch (error) {phase = 'ready';@@ -1056,9 +1088,9 @@ export function createAgentRuntime({ kernelWorkers = true, backend = 'gpu', browasync 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. */+ /** The ID of the last used scene, or null. Tools that take a sessionId default to it. */activeSessionId() {- return activeSessionId;+ return lastUsedSessionId();},close() {if (!closing) {@@ -1075,7 +1107,7 @@ export function createAgentRuntime({ kernelWorkers = true, backend = 'gpu', browawait shutdownResources();}})().finally(() => {- activeSessionId = null;+ forgetAllSessions();phase = 'closed';});}diff --git a/scripts/mcp-server.mjs b/scripts/mcp-server.mjsindex 103f5500..d91eec58 100644--- a/scripts/mcp-server.mjs+++ b/scripts/mcp-server.mjs@@ -757,7 +757,7 @@ function withoutRelationsAdvice(capabilities) {const operationWithoutRelations = z.discriminatedUnion('type', [...nodeOperations(nodeFieldsWithoutRelations, nodeRecordWithoutRelations), ...otherOperations]);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('sessionId is not a valid UUID. Leave it out to use the active scene.').optional().describe('Leave out: the active scene is used.') };+const sessionFields = { sessionId: z.uuid('sessionId is not a valid UUID. Leave it out to use the last used scene.').optional().describe('Leave out: the last used scene.') };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.') };@@ -860,7 +860,7 @@ export function createAgentMcpServer(runtime, { version = packageMetadata.versioconst restoreCheckpointId = checkpointFields.checkpointId.optional();const branchInstructions = branches ? ' To try variants, give scene_apply a branch name for each (the scene stays put), compare them in one scene_review with a branch per shot, then keep the best with scene_restore and its branch.' : '';const server = new McpServer({ name: '67js-scene', version }, {- instructions: 'Start with scene_capabilities. Create a procedural recipe with scene_create, or select a configured GLB digest from scene_asset_catalog and use scene_create_asset. Inspect stable IDs and save a checkpoint before editing. Apply small batches with the current expectedRevision and check committed, revision and renderSucceeded. A committed edit can have a separate renderError; do not retry it with an old revision.'+branchInstructions+' Pass labels: true to scene_look or scene_review to match part names to the image. Use scene_look to judge the actual image, or scene_review with the current expectedRevision to compare independent camera and motion samples in one grid while preserving the source pose. When jobs are configured, scene_render_submit captures an immutable snapshot. Poll scene_render_status, cancel when needed, and retrieve verified local artifact metadata with scene_render_result after completion. Preview rendering and edits pause during a job; source revision and checkpoints survive. Release outputs with scene_render_release. Export the final recipe and dispose the scene when finished. No arbitrary JavaScript, remote URLs or caller-selected output paths are exposed.',+ instructions: 'Start with scene_capabilities. Create a procedural recipe with scene_create, or select a configured GLB digest from scene_asset_catalog and use scene_create_asset. Pass its sessionId to work on several open scenes; without it the last used scene is used. Inspect stable IDs and save a checkpoint before editing. Apply small batches with the current expectedRevision and check committed, revision and renderSucceeded. A committed edit can have a separate renderError; do not retry it with an old revision.'+branchInstructions+' Pass labels: true to scene_look or scene_review to match part names to the image. Use scene_look to judge the actual image, or scene_review with the current expectedRevision to compare independent camera and motion samples in one grid while preserving the source pose. When jobs are configured, scene_render_submit captures an immutable snapshot. Poll scene_render_status, cancel when needed, and retrieve verified local artifact metadata with scene_render_result after completion. Preview rendering and edits pause during a job; source revision and checkpoints survive. Release outputs with scene_render_release. Export the final recipe and dispose the scene when finished. No arbitrary JavaScript, remote URLs or caller-selected output paths are exposed.',});let closePromise;server.server.onclose = () => {@@ -870,7 +870,7 @@ export function createAgentMcpServer(runtime, { version = packageMetadata.versioerror => 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+ // A call that leaves sessionId out means the last used scene. A stale, evicted 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;@@ -887,8 +887,7 @@ export function createAgentMcpServer(runtime, { version = packageMetadata.versioreturn await run(withActiveSession(argumentsValue, inputSchema));} catch (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');+ const sceneMissing = CREATE_TOOLS.has(name);return { isError: true, content: [{ type: 'text', text: `${name} failed: ${message}${sceneMissing ? ` ${SCENE_NOT_CREATED_ADVICE}` : ''}` }] };}};@@ -899,9 +898,9 @@ export function createAgentMcpServer(runtime, { version = packageMetadata.versioconst answer = answerCapabilities(relations ? await runtime.capabilities() : withoutRelationsAdvice(await runtime.capabilities()), topic, outlineSources);return jsonResult(chosenFormat('scene_capabilities', response_format) === 'concise' && answer.fields !== undefined ? { ...answer, fields: withoutNotes(answer.fields) } : answer);});- register('scene_create', 'Create the single active render scene from a JSON recipe. Dispose an existing scene first.', z.strictObject({ recipe: relations ? recipe : recipeWithoutRelations }), { ...edit, destructiveHint: false }, async argumentsValue => jsonResult(await runtime.create(argumentsValue)));+ register('scene_create', 'Create a render scene from a JSON recipe; the result has its sessionId. Several scenes stay open; past the cap the least recently used one is closed.', z.strictObject({ recipe: relations ? recipe : recipeWithoutRelations }), { ...edit, destructiveHint: false }, async argumentsValue => jsonResult(await runtime.create(argumentsValue)));register('scene_asset_catalog', 'List content-bound GLB and PNG, JPEG or WebP image IDs from the configured local asset directory. No arbitrary paths or downloads.', z.strictObject({}), readOnly, async () => jsonResult(await runtime.assetCatalog()));- register('scene_create_asset', 'Create the active scene from a catalog GLB and editable asset recipe. Preserves supported maps, skins, morphs and clips. Dispose the existing scene first.', z.strictObject({ recipe: assetRecipe }), { ...edit, destructiveHint: false }, async argumentsValue => jsonResult(await runtime.createAsset(argumentsValue)));+ register('scene_create_asset', 'Create the active scene from a catalog GLB and editable asset recipe. Preserves supported maps, skins, morphs and clips. The result has its sessionId.', z.strictObject({ recipe: assetRecipe }), { ...edit, destructiveHint: false }, async argumentsValue => jsonResult(await runtime.createAsset(argumentsValue)));register('scene_inspect', 'Read revision, counts and selected nodes. For a recipe with physics, the result lists body final positions, resting times, contacts and sensor enter/leave events. Bounds describe authored geometry rather than shader displacement.', z.strictObject({ ...sessionFields, ids: z.array(identifier).max(4096).optional().describe('Selected node IDs; an imported node means its parts and those below. Omit to inspect scene order.'), kind: z.enum(['meshes', 'hierarchy']).optional().describe('Imported assets only: hierarchy exposes stable source-node IDs and joints.'), offset: z.number().int().min(0).max(4096).optional().describe('Imported assets only: pagination offset.'), limit: z.number().int().min(1).max(4096).optional().describe('Maximum returned node records. Defaults to 64.'), includeBounds: z.boolean().optional().describe('Include world geometry bounds. Defaults to false.'), path: z.record(z.string(), z.unknown()).optional().describe('Walking route over a ground node, around holes: fields in scene_capabilities navigation.') }), readOnly, async argumentsValue => jsonResult(await runtime.inspect(argumentsValue)));register('scene_walkmap', 'Walkable map on a grid: rows of . walkable, x blocked, # no surface. keepOut (m) avoids obstacles. assetId: query a big catalog GLB, no render.', z.strictObject({ ...sessionFields, assetId: z.string().regex(/^[a-f0-9]{64}$/).optional(), min: z.tuple([z.number(), z.number()]), max: z.tuple([z.number(), z.number()]), cellSize: z.number().min(0.05).default(1), clearance: z.number().min(0).default(2), keepOut: z.number().min(0).optional(), streetY: z.number().optional(), includeCells: z.boolean().optional() }), readOnly, async argumentsValue => jsonResult(await runtime.walkMap(argumentsValue)));register('mesh_inspect', 'Check recipe geometries as polygon meshes: vertex, edge and face counts, triangles/quads/n-gons, connected and closed parts, face tags (top, bottom, side, left, right, front, back), bounds, and lint problems (non-manifold, inconsistent winding, inverted, degenerate, open, loose) with a suggested fix each. Also imported asset parts (mesh-0). Read-only and cached per geometry.', z.strictObject({ ...sessionFields, geometry: identifier.optional().describe('One geometry ID to check, as in mesh_edit.'), geometries: z.array(identifier).min(1).max(16).optional().describe('Geometry IDs to check. Omit both to check the first 16 geometries.') }), readOnly, async ({ geometry: geometryId, geometries, ...rest }) => jsonResult(await runtime.inspectMeshes({ ...rest, ...(geometries || geometryId ? { geometries: [...(geometries ?? []), ...(geometryId ? [geometryId] : [])] } : {}) })));@@ -931,7 +930,7 @@ export function createAgentMcpServer(runtime, { version = packageMetadata.versioconst shown = chosenFormat('scene_review', response_format) === 'concise' ? conciseReview(metadata) : metadata;return { content: [{ type: 'image', data, mimeType }, { type: 'text', text: JSON.stringify(shown) }], structuredContent: shown };});- register('scene_checkpoint', 'Save a private recipe snapshot. Up to eight checkpoints can be retained per session.', z.strictObject(sessionFields), { ...edit, destructiveHint: false }, async argumentsValue => jsonResult(await runtime.checkpoint(argumentsValue)));+ register('scene_checkpoint', 'Save a private recipe snapshot. Up to 16 are kept per scene; past that the oldest is evicted.', z.strictObject(sessionFields), { ...edit, destructiveHint: false }, async argumentsValue => jsonResult(await runtime.checkpoint(argumentsValue)));register('scene_restore', 'Restore a checkpoint atomically using the current revision. The checkpoint remains available and revision increments. With revision (last 4 kept), undo with no checkpoint. With branch, keep that branch (one revision) and drop all branches.', z.strictObject({ ...sessionFields, checkpointId: restoreCheckpointId, revision: z.number().int().min(0).optional(), ...restoreBranchField, expectedRevision }), edit, async argumentsValue => jsonResult(await runtime.restore(argumentsValue)));register('scene_release_checkpoint', 'Release one checkpoint slot. Released or foreign checkpoints fail.', z.strictObject(checkpointFields), destroy, async argumentsValue => jsonResult(await runtime.releaseCheckpoint(argumentsValue)));register('scene_export_recipe', 'Read a detached canonical JSON recipe for reproduction.', z.strictObject(sessionFields), readOnly, async argumentsValue => jsonResult(await runtime.exportRecipe(argumentsValue)));diff --git a/scripts/smoke-mcp-package.mjs b/scripts/smoke-mcp-package.mjsindex a0e67144..3e45fdce 100644--- a/scripts/smoke-mcp-package.mjs+++ b/scripts/smoke-mcp-package.mjs@@ -123,7 +123,7 @@ for (const era of ['modern', 'legacy']) {assert.equal((await client.listTools()).tools.length, 23);const capabilities = (await call('scene_capabilities')).structuredContent;assert.equal(capabilities.phase, 'idle');- assert.equal((await call('scene_capabilities', { topic: 'preview' })).structuredContent.value.maximumActiveScenes, 1);+ assert.equal((await call('scene_capabilities', { topic: 'preview' })).structuredContent.value.maximumActiveScenes, 4);assert.equal(capabilities.availableIn, metadata.version);if (protocolOnly) {results.push({ era, tools: 18, connectMs, browserStarted: false });diff --git a/skills/build-67js-scene/SKILL.md b/skills/build-67js-scene/SKILL.mdindex e9e0657a..522979af 100644--- a/skills/build-67js-scene/SKILL.md+++ b/skills/build-67js-scene/SKILL.md@@ -21,9 +21,9 @@ Start the server with `npx --package @codepawlhq/67js 67js-mcp --backend gpu --a4. `scene_look`: the PNG. Add `labels: true` to match node names to the image. Judge the image, not the lint.5. `scene_apply` with the current `expectedRevision` and a small `operations` batch. A stale revision fails whole.6. `scene_checkpoint` before a risky batch, `scene_restore` to undo, `scene_release_checkpoint` after. Without a checkpoint, `scene_restore` with `revision` goes back to one of the last 4 earlier revisions.-7. `scene_export_recipe` keeps the result. `scene_dispose` before a different scene.+7. `scene_export_recipe` keeps the result. `scene_dispose` a scene you finished with.-`sessionId` may be left out: one scene is active at a time.+`sessionId` may be left out: the last used scene is meant. With two scenes open, pass it on every call. The server keeps 4 scenes and closes the least recently used (`evictedSessions` in the create result), and 16 checkpoints per scene, oldest first (`evictedCheckpointIds`).Variants: `scene_apply` with a `branch` name, compare in one `scene_review` (a `branch` per shot), keep one with `scene_restore`.## Pick the recipediff --git a/skills/render-67js-media/SKILL.md b/skills/render-67js-media/SKILL.mdindex 3371a6ca..6a3f058f 100644--- a/skills/render-67js-media/SKILL.md+++ b/skills/render-67js-media/SKILL.md@@ -6,7 +6,7 @@ license: MIT# Export images and video from 67js over MCP-A render job is an immutable snapshot of the active scene. Edits made while it runs do not change it, and it does not+A render job is an immutable snapshot of one scene (`sessionId`, else the last used) and stays tied to it. Edits made while it runs do not change it, and it does notchange the scene's revision, pose or checkpoints. The MCP server must have been started with `--jobs <abs private dir>`;MP4 also needs `ffmpeg` on PATH or `--ffmpeg <abs path>`, and sound needs `--audio <abs dir>`. Without `--jobs` thesubmit call fails: tell the user which launch option is missing.diff --git a/src/agent-errors.js b/src/agent-errors.jsindex 86a62842..6182efca 100644--- a/src/agent-errors.js+++ b/src/agent-errors.js@@ -1,10 +1,23 @@/*** Wording for the agent errors that recorded runs hit most. The session errors alone were a third of all tool errors* (21 of 68): an agent used an ID it invented, or one from a scene that was disposed or never created.+ *+ * `openSessionIds` lists the open scenes from least to most recently used; `evictedSessionIds` lists scenes the server+ * closed to stay under its scene cap.*/-export function sessionProblem(requestedSessionId, activeSessionId) {+export function sessionProblem(requestedSessionId, activeSessionId, { openSessionIds = [], evictedSessionIds = [] } = {}) {+ if (evictedSessionIds.includes(requestedSessionId)) {+ const open = openSessionIds.length ? ` Open scenes: ${openSessionIds.join(', ')}.` : '';+ return `sessionId ${requestedSessionId} was evicted: the server keeps a limited number of open scenes and closes the least recently used one when a new scene is created.${open} Pass the sessionId of an open scene, or call scene_create again (scene_export_recipe saves a scene before it is evicted).`;+ }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.';}+ if (openSessionIds.length > 1) {+ return `Unknown scene session ${requestedSessionId}. Open scenes: ${openSessionIds.join(', ')}; the last used is ${activeSessionId}. Pass one of them as sessionId, leave sessionId out for the last used scene, or call 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.`;}++/** How many scenes one server keeps open, and the resident geometry bytes they may hold together. */+export const SCENE_STORE_LIMITS = Object.freeze({ maxOpenScenes: 4, maxOpenSceneBytes: 96 * 1024 * 1024 });diff --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.jsindex 387e6029..bff5a412 100644--- a/src/agent-scene-capabilities.js+++ b/src/agent-scene-capabilities.js@@ -14,7 +14,7 @@ import { MATERIAL_LAYER_FIELDS, MATERIAL_LAYER_SCALAR_RANGES, MATERIAL_LAYER_COLexport const AGENT_SCENE_DEFAULT_LIMITS = Object.freeze({maxNodes: 4096, maxDepth: 256, maxGeometries: 256, maxMaterials: 256,maxVertices: 250_000, maxGeometryBytes: 32 * 1024 * 1024,- maxOperations: 256, maxCheckpoints: 8, maxRecipeBytes: 1024 * 1024,+ maxOperations: 256, maxCheckpoints: 16, maxRecipeBytes: 1024 * 1024,});// The values of the water presets (src/world-material-shader.js holds the same numbers; a test keeps them in step), written outdiff --git a/tests/agent-render-jobs.test.js b/tests/agent-render-jobs.test.jsindex a7af9cee..efedc623 100644--- a/tests/agent-render-jobs.test.js+++ b/tests/agent-render-jobs.test.js@@ -450,3 +450,16 @@ test('the deadline of a traced film covers every frame', () => {const film = jobDeadlineMs({ frameCount: 5, width: 64, height: 64, renderer });assert.equal(film - single, 4 * 10 * 1000);});++test('a job runs against the scene it was submitted for', async context => {+ const root = await temporary(context);+ const scenesSeen = [];+ const controller = await createAgentRenderJobs({ root, limits, run: async input => {+ scenesSeen.push(input.sessionId);+ return writeImage(input);+ } });+ const submitted = await controller.submit({ ...request(), sessionId: 'scene-a' });+ await terminal(controller, submitted.jobId);+ assert.deepEqual(scenesSeen, ['scene-a']);+ await controller.close();+});diff --git a/tests/agent-runtime.test.js b/tests/agent-runtime.test.jsindex dd417570..77d0c2ea 100644--- a/tests/agent-runtime.test.js+++ b/tests/agent-runtime.test.js@@ -22,13 +22,14 @@ import { audioInputArguments, createAudioLibrary, measureStreamSeconds } from '.import { filmTimelineDuration, filmTimelineShotStarts, sampleFilmTimeline } from '../src/film-timeline.js';import { normalizeReview, REVIEW_LIMITS } from '../scripts/agent-review.mjs';import { BRANCH_LIMITS, validateBranchName } from '../src/agent-branches.js';+import { sessionProblem, SCENE_STORE_LIMITS } from '../src/agent-errors.js';test('runtime reports real scene capabilities without launching a browser and closes idempotently', async () => {const runtime = createAgentRuntime({ backend: 'cpu', memory: 64 });const capabilities = await runtime.capabilities();assert.equal(capabilities.phase, 'idle');assert.equal(capabilities.scene.schemaVersion, 1);- assert.equal(capabilities.preview.maximumActiveScenes, 1);+ assert.equal(capabilities.preview.maximumActiveScenes, 4);assert.equal(capabilities.preview.memoryBudgetMiB, 64);assert.equal(capabilities.preview.backend, 'cpu');assert.equal(capabilities.review.maximumShots, 4);@@ -113,7 +114,7 @@ async function reviewRuntimeHarness({ failShot, blockShot = false, oversize = facreateRequire: () => ({ resolve: () => { throw new Error('no peer in tests'); } }),VEGETATION_CAPABILITY_NOTE, CROWD_CAPABILITY_NOTE, USER_PASS_CAPABILITIES, MESH_BLEND_CAPABILITIES, MATERIAL_SNIPPET_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,recipeAssetNeeds, sequenceFrameIds, catalogLookReferences, BUNDLED_ENVIRONMENT_NAMES, BUNDLED_CUBE_LOOK_NAMES, TEXTURE_SEQUENCE_CAPABILITIES, AGENT_ASSET_LIMITS, assertCombinedAssetBytes,- audioInputArguments, createAudioLibrary, measureStreamSeconds, filmTimelineDuration, filmTimelineShotStarts, sampleFilmTimeline, normalizeReview, REVIEW_LIMITS, isPreviewHost, BRANCH_LIMITS, validateBranchName,+ audioInputArguments, createAudioLibrary, measureStreamSeconds, filmTimelineDuration, filmTimelineShotStarts, sampleFilmTimeline, normalizeReview, REVIEW_LIMITS, isPreviewHost, BRANCH_LIMITS, validateBranchName, sessionProblem, SCENE_STORE_LIMITS,chromium: { launch: async () => browser }, URL, Buffer, process, performance, clearTimeout,setTimeout: (callback, delay) => { deadlines.push(delay); return setTimeout(callback, delay); },});diff --git a/tests/mcp-scene-ids.test.js b/tests/mcp-scene-ids.test.jsnew file mode 100644index 00000000..10b421b3--- /dev/null+++ b/tests/mcp-scene-ids.test.js@@ -0,0 +1,178 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { existsSync } from 'node:fs';+import { Client } from '@modelcontextprotocol/client';+import { StdioClientTransport } from '@modelcontextprotocol/client/stdio';+import { sessionProblem, SCENE_STORE_LIMITS } from '../src/agent-errors.js';+import { AGENT_SCENE_DEFAULT_LIMITS } from '../src/agent-scene-capabilities.js';++const serverEntry = new URL('../bin/67js-mcp.mjs', import.meta.url).pathname.replace(/^\/(\w:)/, '$1');+const hasBuild = existsSync(new URL('../build/mcp/server.mjs', import.meta.url));++function recipeWithNode(nodeId) {+ return {+ format: '67js.scene', schemaVersion: 1,+ geometries: [{ id: 'cube', type: 'box', bevel: 0 }],+ materials: [{ id: 'blue', color: [0.1, 0.3, 0.8] }],+ nodes: [{ id: nodeId, geometry: 'cube', material: 'blue' }],+ };+}++function textOf(result) {+ return (result.content ?? []).map(part => part.text ?? '').join('\n');+}++async function connectServer(context) {+ const transport = new StdioClientTransport({ command: process.execPath, args: [serverEntry, '--backend', 'cpu'], stderr: 'ignore' });+ const client = new Client({ name: 'scene-ids-test', version: '1.0.0' });+ await client.connect(transport);+ context.after(() => client.close());+ return client;+}++async function createScene(client, nodeId) {+ const created = await client.callTool({ name: 'scene_create', arguments: { recipe: recipeWithNode(nodeId) } });+ assert.notEqual(created.isError, true, textOf(created));+ return created;+}++function nodeIdsOf(inspected) {+ return inspected.structuredContent.nodes.map(node => node.id);+}++test('session errors name the evicted scene and the open ones', () => {+ const evicted = sessionProblem('old', 'b', { openSessionIds: ['a', 'b'], evictedSessionIds: ['old'] });+ assert.match(evicted, /sessionId old was evicted/);+ assert.match(evicted, /Open scenes: a, b/);+ assert.match(evicted, /scene_create/);+ const unknown = sessionProblem('ghost', 'b', { openSessionIds: ['a', 'b'] });+ assert.match(unknown, /Open scenes: a, b; the last used is b/);+ assert.match(unknown, /leave sessionId out/);+});++test('two scenes in one server are edited without interference and a call without an id means the last used scene',+ { skip: !hasBuild && 'run npm run build first', timeout: 180000 }, async context => {+ const client = await connectServer(context);+ const first = await createScene(client, 'alpha').catch(error => {+ context.skip(`no browser for the scene: ${error.message.slice(0, 120)}`);+ });+ if (!first) return;+ const second = await createScene(client, 'beta');+ const firstId = first.structuredContent.sessionId;+ const secondId = second.structuredContent.sessionId;+ assert.notEqual(firstId, secondId);++ // Interleave edits and renders so the two scenes take turns on the one canvas.+ const movedFirst = await client.callTool({ name: 'scene_apply', arguments: { sessionId: firstId, expectedRevision: 0,+ operations: [{ type: 'set-node', id: 'alpha', translation: [3, 0, 0] }] } });+ assert.notEqual(movedFirst.isError, true, textOf(movedFirst));+ const lookSecond = await client.callTool({ name: 'scene_look', arguments: { sessionId: secondId, width: 64, height: 64 } });+ assert.notEqual(lookSecond.isError, true, textOf(lookSecond));+ const movedSecond = await client.callTool({ name: 'scene_apply', arguments: { sessionId: secondId, expectedRevision: 0,+ operations: [{ type: 'set-node', id: 'beta', translation: [0, 5, 0] }] } });+ assert.notEqual(movedSecond.isError, true, textOf(movedSecond));+ const lookFirst = await client.callTool({ name: 'scene_look', arguments: { sessionId: firstId, width: 64, height: 64 } });+ assert.notEqual(lookFirst.isError, true, textOf(lookFirst));++ const firstNodes = await client.callTool({ name: 'scene_inspect', arguments: { sessionId: firstId } });+ const secondNodes = await client.callTool({ name: 'scene_inspect', arguments: { sessionId: secondId } });+ assert.deepEqual(nodeIdsOf(firstNodes), ['alpha']);+ assert.deepEqual(nodeIdsOf(secondNodes), ['beta']);+ assert.equal(firstNodes.structuredContent.revision, 1);+ assert.equal(secondNodes.structuredContent.revision, 1);+ const firstRecipe = await client.callTool({ name: 'scene_export_recipe', arguments: { sessionId: firstId } });+ const secondRecipe = await client.callTool({ name: 'scene_export_recipe', arguments: { sessionId: secondId } });+ assert.deepEqual(firstRecipe.structuredContent.recipe.nodes[0].translation, [3, 0, 0]);+ assert.deepEqual(secondRecipe.structuredContent.recipe.nodes[0].translation, [0, 5, 0]);++ // No id: the scene used last. After naming the first scene, a bare call reads it, and a bare edit lands on it.+ const bare = await client.callTool({ name: 'scene_inspect', arguments: {} });+ assert.equal(bare.structuredContent.sessionId, secondId);+ await client.callTool({ name: 'scene_inspect', arguments: { sessionId: firstId } });+ const bareAfterNaming = await client.callTool({ name: 'scene_inspect', arguments: {} });+ assert.equal(bareAfterNaming.structuredContent.sessionId, firstId);+ const bareEdit = await client.callTool({ name: 'scene_apply', arguments: { expectedRevision: 1,+ operations: [{ type: 'set-node', id: 'alpha', translation: [9, 0, 0] }] } });+ assert.notEqual(bareEdit.isError, true, textOf(bareEdit));+ assert.equal(bareEdit.structuredContent.sessionId, firstId);+ const untouched = await client.callTool({ name: 'scene_inspect', arguments: { sessionId: secondId } });+ assert.equal(untouched.structuredContent.revision, 1);++ // Disposing one scene leaves the other open and makes it the default.+ const disposed = await client.callTool({ name: 'scene_dispose', arguments: { sessionId: firstId } });+ assert.notEqual(disposed.isError, true, textOf(disposed));+ const afterDispose = await client.callTool({ name: 'scene_inspect', arguments: {} });+ assert.equal(afterDispose.structuredContent.sessionId, secondId);+ const gone = await client.callTool({ name: 'scene_inspect', arguments: { sessionId: firstId } });+ assert.equal(gone.isError, true);+ assert.match(textOf(gone), /Unknown scene session/);+ });++test('the least recently used scene is evicted past the open scene cap and its id gets a clear error',+ { skip: !hasBuild && 'run npm run build first', timeout: 240000 }, async context => {+ const client = await connectServer(context);+ const opened = [];+ for (let index = 0; index < SCENE_STORE_LIMITS.maxOpenScenes; index++) {+ const created = await createScene(client, `node${index}`).catch(error => {+ context.skip(`no browser for the scene: ${error.message.slice(0, 120)}`);+ });+ if (!created) return;+ assert.equal(created.structuredContent.evictedSessions, undefined);+ opened.push(created.structuredContent.sessionId);+ }+ // Using the oldest scene makes the second one the least recently used.+ const touched = await client.callTool({ name: 'scene_inspect', arguments: { sessionId: opened[0] } });+ assert.notEqual(touched.isError, true, textOf(touched));++ const overflow = await createScene(client, 'overflow');+ assert.deepEqual(overflow.structuredContent.evictedSessions, [opened[1]]);++ const evicted = await client.callTool({ name: 'scene_inspect', arguments: { sessionId: opened[1] } });+ assert.equal(evicted.isError, true);+ assert.match(textOf(evicted), new RegExp(`sessionId ${opened[1]} was evicted`));+ assert.match(textOf(evicted), /scene_create/);++ for (const survivor of [opened[0], opened[2], opened[3], overflow.structuredContent.sessionId]) {+ const inspected = await client.callTool({ name: 'scene_inspect', arguments: { sessionId: survivor } });+ assert.notEqual(inspected.isError, true, textOf(inspected));+ }+ });++test('checkpoints are kept up to the limit per scene and the oldest is evicted first',+ { skip: !hasBuild && 'run npm run build first', timeout: 240000 }, async context => {+ const client = await connectServer(context);+ const created = await createScene(client, 'alpha').catch(error => {+ context.skip(`no browser for the scene: ${error.message.slice(0, 120)}`);+ });+ if (!created) return;+ const other = await createScene(client, 'beta');+ const sessionId = created.structuredContent.sessionId;+ const limit = AGENT_SCENE_DEFAULT_LIMITS.maxCheckpoints;+ assert.ok(limit > 8);++ const checkpointIds = [];+ for (let index = 0; index < limit; index++) {+ const saved = await client.callTool({ name: 'scene_checkpoint', arguments: { sessionId } });+ assert.notEqual(saved.isError, true, textOf(saved));+ assert.equal(saved.structuredContent.evictedCheckpointIds, undefined);+ checkpointIds.push(saved.structuredContent.checkpointId);+ }+ // Checkpoints of another scene do not count against this one.+ const foreignSave = await client.callTool({ name: 'scene_checkpoint', arguments: { sessionId: other.structuredContent.sessionId } });+ assert.notEqual(foreignSave.isError, true, textOf(foreignSave));++ const overflow = await client.callTool({ name: 'scene_checkpoint', arguments: { sessionId } });+ assert.notEqual(overflow.isError, true, textOf(overflow));+ assert.deepEqual(overflow.structuredContent.evictedCheckpointIds, [checkpointIds[0]]);++ const restoreEvicted = await client.callTool({ name: 'scene_restore', arguments: { sessionId, checkpointId: checkpointIds[0], expectedRevision: 0 } });+ assert.equal(restoreEvicted.isError, true);+ assert.match(textOf(restoreEvicted), /checkpointId .* was evicted as the oldest/);+ const restoreKept = await client.callTool({ name: 'scene_restore', arguments: { sessionId, checkpointId: checkpointIds[1], expectedRevision: 0 } });+ assert.notEqual(restoreKept.isError, true, textOf(restoreKept));++ // A checkpoint of one scene is foreign to the other.+ const foreignRestore = await client.callTool({ name: 'scene_restore', arguments: { sessionId: other.structuredContent.sessionId, checkpointId: checkpointIds[1], expectedRevision: 0 } });+ assert.equal(foreignRestore.isError, true);+ assert.match(textOf(foreignRestore), /scene_checkpoint returned for sessionId/);+ });