Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Undo the last edits with scene_restore and a revision, no checkpoint needed (#744)

Nguyen Xuan Ancf81747bf2ba
diff --git a/changes/744.md b/changes/744.md
new file mode 100644
index 00000000..d1eab6bc
--- /dev/null
+++ b/changes/744.md
@@ -0,0 +1 @@
+- `scene_restore` takes `revision` to undo the last few `scene_apply` edits in one call, with no checkpoint made first (#744)
diff --git a/changes/744.size.md b/changes/744.size.md
new file mode 100644
index 00000000..9d394021
--- /dev/null
+++ b/changes/744.size.md
@@ -0,0 +1,4 @@
+- tool:scene_restore: a cold agent that never made a checkpoint can still undo its last edits with one call (a `revision` field), 99 bytes on one tool
+- scene:agent-scene: undo by revision keeps the last 4 states and a budget-aware drop of the oldest, 324 bytes gzip for an agent-facing capability
+- scene:agent-scene+lazy: same code as scene:agent-scene
+- goal:agent-scene: the growth is the revision history; no tool schema beyond 99 bytes grew, and agents can undo without planning a checkpoint
diff --git a/docs/mcp.md b/docs/mcp.md
index bb1bdc4f..0ff4f47b 100644
--- a/docs/mcp.md
+++ b/docs/mcp.md
@@ -108,6 +108,7 @@ Known gaps, checked by `npm run check:tool-schemas`:
`scene_create` returns the session ID, current revision, inspection, and render status. `scene_apply` and `scene_restore` return the same without the inspection, so an edit answer stays small; call `scene_inspect` to read the nodes.
`scene_checkpoint` returns a checkpoint UUID scoped to its session UUID.
A restore increments revision and keeps the checkpoint available.
+To undo the last edits without a checkpoint, call `scene_restore` with `revision` set to an earlier revision number. The session keeps the 4 revisions before the current one (every `scene_apply` and `scene_restore` leaves one behind), drops the oldest first, and an unknown or dropped revision fails with the revisions still kept. The restore is itself a revision, so it can be undone the same way.
A stale revision or invalid command produces an error without publishing partial edits.
SDK validation rejects unknown tool fields before dispatch.
Backend errors return `isError: true` with a readable message.
@@ -134,7 +135,7 @@ Inspect or export the recipe before retrying. Context loss still permits recipe
| `scene_look` | `sessionId`, optional `width`, `height`, `motionTime`, `labels` | PNG image and metadata |
| `scene_review` | `sessionId`, `expectedRevision`, `shots` (each with an optional `branch`), optional `width`, `height`, `labels` | Labeled PNG grid and metadata from an isolated snapshot |
| `scene_checkpoint` | `sessionId` | Checkpoint ID, session ID, and revision |
-| `scene_restore` | `sessionId`, `expectedRevision`, and a `checkpointId` or a `branch` | Updated revision and render status |
+| `scene_restore` | `sessionId`, `expectedRevision`, and a `checkpointId`, a `revision` or a `branch` | Updated revision and render status |
| `scene_release_checkpoint` | `sessionId`, `checkpointId` | Release confirmation |
| `scene_export_recipe` | `sessionId` | Canonical recipe and revision |
| `scene_export_glb` | `sessionId`, optional `clip`, `motionTime`, `maxTextureSize` | A GLB file under `<jobs>/exports/` with a server-chosen name: path, bytes, SHA-256. See [GLB export](export-glb.md) |
@@ -210,6 +211,7 @@ The [scene contract](agent-scene.md) defines the geometry fields, transforms, ma
| Geometries and materials | 256 each |
| Operations per batch | 256 |
| Checkpoints per session | 8 |
+| Earlier revisions kept per session for `scene_restore` with `revision` | 4 |
| Geometry input points | 4096 per input, including all extrusion contours |
| Extrusion holes | 128 |
| Unique geometry vertices | 250000 |
@@ -232,6 +234,7 @@ Camera matrices must remain finite at every supported preview aspect ratio, from
Geometry resources remain immutable. Remove an unused definition and add its replacement in one batch, or add a new resource ID and rebind its nodes.
Checkpoints retain their resource handles for exact restoration. Active, checkpoint and staged geometry share a bounded allocation budget.
Release unused checkpoints to free that ownership before adding detail.
+The kept revisions share geometry buffers with the live scene, so four cost a recipe copy each (a few kilobytes) plus any geometry a later edit removed. That removed geometry counts in the same budget, and an edit that would exceed it drops the oldest kept revisions first instead of failing.
The preview reconciles rigid parts, textured ones with the `replace-textured-parts` addon, while retaining shader programs, render targets and shared geometry buffers.
A scene with material patterns gets a new renderer on each topology change instead. Skinned and morphed parts are not streamed either; `replaceParts` rejects adding or removing them.
diff --git a/scripts/agent-preview-browser.js b/scripts/agent-preview-browser.js
index 90febd7d..e24a4143 100644
--- a/scripts/agent-preview-browser.js
+++ b/scripts/agent-preview-browser.js
@@ -1076,8 +1076,12 @@ window.__agentPreview = {
record.checkpoints.set(checkpointId, { handle, fogDensity: record.scene.environment.volumeFog.density });
return { sessionId, checkpointId, revision: record.scene.revision };
},
- restore({ sessionId, checkpointId, expectedRevision }) {
+ restore({ sessionId, checkpointId, revision, expectedRevision }) {
const record = requireSession(sessionId);
+ if (revision !== undefined) {
+ record.scene.restoreRevision(revision, { expectedRevision });
+ return mutationStatus(record);
+ }
if (!record.checkpoints.has(checkpointId)) {
throw new Error('Unknown or released checkpoint.');
}
diff --git a/scripts/agent-runtime.mjs b/scripts/agent-runtime.mjs
index 78abf08a..5be00e48 100644
--- a/scripts/agent-runtime.mjs
+++ b/scripts/agent-runtime.mjs
@@ -983,7 +983,7 @@ export function createAgentRuntime({ kernelWorkers = true, backend = 'gpu', brow
if (input.branch !== undefined) {
return invoke('keepBranch', { sessionId: input.sessionId, name: validateBranchName(input.branch), expectedRevision: input.expectedRevision });
}
- if (input.checkpointId === undefined) throw new TypeError('Restore needs a checkpointId or a branch.');
+ if (input.revision === undefined && input.checkpointId === undefined) throw new TypeError('Restore needs a checkpointId, a revision or a branch.');
return invoke('restore', input);
});
},
diff --git a/scripts/mcp-server.mjs b/scripts/mcp-server.mjs
index f42918ba..8ab72889 100644
--- a/scripts/mcp-server.mjs
+++ b/scripts/mcp-server.mjs
@@ -840,7 +840,7 @@ export function createAgentMcpServer(runtime, { version = packageMetadata.versio
const branchField = branches ? { branch: branchName.optional().describe('Fork: store the result as this branch (up to 8), leaving the scene unchanged.') } : {};
const reviewBranchField = branches ? { branch: branchName.optional().describe('Render this scene_apply branch.') } : {};
const restoreBranchField = branches ? { branch: branchName.optional() } : {};
- const restoreCheckpointId = branches ? checkpointFields.checkpointId.optional() : checkpointFields.checkpointId;
+ const 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.',
@@ -907,7 +907,7 @@ export function createAgentMcpServer(runtime, { version = packageMetadata.versio
return { content: [{ type: 'image', data, mimeType }, { type: 'text', text: JSON.stringify(metadata) }], structuredContent: metadata };
});
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_restore', 'Restore a checkpoint atomically using the current revision. The checkpoint remains available and revision increments. With branch instead of checkpointId, keep that branch (one revision) and drop all branches.', z.strictObject({ ...sessionFields, checkpointId: restoreCheckpointId, ...restoreBranchField, expectedRevision }), edit, async argumentsValue => jsonResult(await runtime.restore(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)));
register('scene_export_glb', 'Write the active scene as a GLB file in the configured jobs folder, under a server-chosen name (the result has the path, byte count and SHA-256). Needs --jobs. Exports the current pose with pattern and imported textures, skins, morph weights and IK as posed; motionTime seeks authored motion first. For an imported asset, clip adds that source clip (translation, rotation, scale and morph weight tracks) on the source skeleton, which needs no animation, node overrides or motion in the scene. At most eight files are kept, oldest removed first; the GLB is at most 32 MiB.', z.strictObject({ ...sessionFields, clip: z.number().int().min(0).max(255).optional().describe('Imported assets only: index of the source clip to write.'), motionTime: z.number().min(0).max(3600).optional().describe('Seek authored motion (and IK) to this time before exporting. Leaves the preview there, like scene_look.'), maxTextureSize: z.number().int().min(1).max(4096).optional().describe('Largest texture side in pixels. Defaults to 2048.') }), edit, async argumentsValue => jsonResult(await runtime.exportGlb(argumentsValue)));
diff --git a/scripts/smoke-agent-branches.mjs b/scripts/smoke-agent-branches.mjs
index c69ac274..136490f2 100644
--- a/scripts/smoke-agent-branches.mjs
+++ b/scripts/smoke-agent-branches.mjs
@@ -104,8 +104,21 @@ try {
await rejected('scene_review', { sessionId, expectedRevision: 1, shots: [{ branch: 'warm' }] });
const restored = (await call('scene_restore', { sessionId, expectedRevision: 1, checkpointId: checkpoint.checkpointId })).structuredContent;
assert.equal(restored.revision, 2);
+
+ // Undo two edits with one call and no checkpoint: the pixels and the recipe match the scene before them.
+ await call('scene_apply', { sessionId, expectedRevision: 2, operations: recolor([1, 0.3, 0.1]) });
+ await call('scene_apply', { sessionId, expectedRevision: 3, operations: recolor([0.1, 1, 0.1]) });
+ assert.notDeepEqual(decodedPixels(imageBytes(await call('scene_look', { sessionId, width: 256, height: 256 }))), sourceBefore);
+ const unknownRevision = await client.callTool({ name: 'scene_restore', arguments: { sessionId, expectedRevision: 4, revision: 99 } }, { timeout: 60000 });
+ assert.equal(unknownRevision.isError, true);
+ assert.match(unknownRevision.content[0].text, /kept revisions: 0, 1, 2, 3/);
+ const undone = (await call('scene_restore', { sessionId, expectedRevision: 4, revision: 2 })).structuredContent;
+ assert.equal(undone.revision, 5);
+ assert.deepEqual((await call('scene_export_recipe', { sessionId })).structuredContent.recipe, recipeBefore);
+ assert.deepEqual(decodedPixels(imageBytes(await call('scene_look', { sessionId, width: 256, height: 256 }))), sourceBefore,
+ 'restoring an earlier revision gives the same image as before the edits');
await call('scene_dispose', { sessionId });
- console.log('Branch smoke passed: fork, shared snapshot, review, labels, keep, hostile names.');
+ console.log('Branch smoke passed: fork, shared snapshot, review, labels, keep, revision undo, hostile names.');
} finally {
await client.close().catch(() => {});
}
diff --git a/skills/build-67js-scene/SKILL.md b/skills/build-67js-scene/SKILL.md
index ad42993a..daa37c18 100644
--- a/skills/build-67js-scene/SKILL.md
+++ b/skills/build-67js-scene/SKILL.md
@@ -20,7 +20,7 @@ Start the server with `npx --package @codepawlhq/67js 67js-mcp --backend gpu --a
3. `scene_inspect`: node IDs, bounds, `diagnostics`, current `revision`.
4. `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.
+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.
`sessionId` may be left out: one scene is active at a time.
diff --git a/src/agent-asset.js b/src/agent-asset.js
index b7035c5a..64bcb7e3 100644
--- a/src/agent-asset.js
+++ b/src/agent-asset.js
@@ -1,5 +1,5 @@
import { mat4, mat3 } from 'gl-matrix';
-import { createAgentScene } from './agent-scene.js';
+import { createAgentScene, REVISION_HISTORY_LIMIT } from './agent-scene.js';
import { environmentPatchWithSetup } from './agent-look.js';
import { assetDiagnostics } from './agent-diagnostics.js';
import { fitPerspectiveDistance } from './camera.js';
@@ -348,6 +348,8 @@ export function createAgentAssetScene(asset, inputRecipe, { sources } = {}) {
let motionTime = null;
let sampledCamera;
const checkpoints = new Map();
+ // Earlier recipes, oldest first. A published recipe is never edited in place, so the reference is a safe snapshot.
+ const revisionHistory = [];
const materialOutputs = new Map([...materials].map(([source, record]) => {
const output = {};
for (const [field, value] of Object.entries(source)) {
@@ -758,6 +760,7 @@ export function createAgentAssetScene(asset, inputRecipe, { sources } = {}) {
parts = buildParts(editedParts);
topologyRevision++;
}
+ const previousRecipe = recipe;
if (transientTime === undefined) {
recipe = candidate;
sampler = stagedSampler;
@@ -772,6 +775,12 @@ export function createAgentAssetScene(asset, inputRecipe, { sources } = {}) {
matrices = stagedMatrices;
}
if (increment) {
+ if (transientTime === undefined) {
+ revisionHistory.push({ revision, recipe: previousRecipe });
+ while (revisionHistory.length > REVISION_HISTORY_LIMIT) {
+ revisionHistory.shift();
+ }
+ }
revision++;
}
return revision;
@@ -1109,6 +1118,18 @@ export function createAgentAssetScene(asset, inputRecipe, { sources } = {}) {
}
return publish(checkpoints.get(handle));
},
+ /** Go back to an earlier revision that apply or restore left behind; no checkpoint is needed. */
+ restoreRevision(target, options = {}) {
+ expected(options);
+ const entry = revisionHistory.find(candidate => candidate.revision === target);
+ if (!entry) {
+ const kept = revisionHistory.map(candidate => candidate.revision);
+ throw invalidField('revision', target, kept.length > 0
+ ? `one of the kept revisions: ${kept.join(', ')} (the last ${REVISION_HISTORY_LIMIT} are kept; older ones are dropped)`
+ : 'a revision this session kept, but none is kept yet because nothing has been edited; apply an edit first');
+ }
+ return publish(entry.recipe);
+ },
releaseCheckpoint(handle) {
if (!checkpoints.delete(handle)) {
throw invalidField('checkpointId', 'unknown or released', 'a checkpointId that scene_checkpoint returned and you have not released, such as the last one returned');
diff --git a/src/agent-scene.js b/src/agent-scene.js
index 864ca4aa..b8f2e843 100644
--- a/src/agent-scene.js
+++ b/src/agent-scene.js
@@ -13,6 +13,12 @@ import { closedRoomShare, CLOSED_ROOM_SHARE } from './closed-room.js';
import { depthLayerOf, MAXIMUM_DEPTH_LAYER } from './depth-layer.js';
import { armatureNodes, bakeRigExport, bindSkins, createSkinStages, normalizeArmatures, publishSkinPoses, restWorldMatrix, rigReport, stageSkinPoses, transformedBounds, withoutArmatureNodes } from './rig.js';
export { AGENT_SCENE_CAPABILITIES, AGENT_SCENE_DEFAULT_LIMITS };
+
+/**
+ * Earlier revisions a session keeps for scene_restore with a revision. Each one holds a recipe copy (a few kilobytes) and
+ * shares geometry buffers with the live scene, so four cost little; their geometry still counts in the allocation budget.
+ */
+export const REVISION_HISTORY_LIMIT = 4;
export { normalizeAgentLook, resolveAgentShadow } from './agent-look.js';
export { describeApplication } from './agent-apply-report.js';
export {
@@ -1163,6 +1169,18 @@ export function createAgentScene(input, inputLimits = {}, options = {}) {
let objectReflectionCache = null;
const skinCache = new Map();
const checkpoints = new Map();
+ // The states before the last edits, oldest first, each with the revision number it had.
+ const revisionHistory = [];
+
+ function snapshotState() {
+ return {
+ recipe: authoredRecipe(state.recipe),
+ geometryRecords: new Map(state.geometryRecords),
+ materialHandles: new Map(state.materialHandles),
+ restParts: state.restParts,
+ sourceRestParts: state.sourceRestParts,
+ };
+ }
function drawnNodeGeometry(id, label) {
identifier(id);
@@ -1177,8 +1195,9 @@ export function createAgentScene(input, inputLimits = {}, options = {}) {
function ownedGeometryRecords() {
const records = new Set(state?.geometryRecords.values() ?? []);
- for (const checkpoint of checkpoints.values()) {
- for (const record of checkpoint.geometryRecords.values()) {
+ const snapshots = [...checkpoints.values(), ...revisionHistory.map(entry => entry.snapshot)];
+ for (const snapshot of snapshots) {
+ for (const record of snapshot.geometryRecords.values()) {
records.add(record);
}
}
@@ -1197,24 +1216,34 @@ export function createAgentScene(input, inputLimits = {}, options = {}) {
if (state) {
retainedMatrices(state.parts);
}
- const ownedRecords = ownedGeometryRecords();
- const availableRecords = new Map();
- for (const record of ownedRecords) {
- availableRecords.set(record.signature, record);
- }
- const plans = recipe.geometries.map(definition => {
- const signature = JSON.stringify(definition);
- const preferredRecord = preferred?.geometryRecords.get(definition.id);
- const activeRecord = state?.geometryRecords.get(definition.id);
- const existing = [preferredRecord, activeRecord, availableRecords.get(signature)]
- .find(record => record?.signature === signature);
- return { definition, signature, existing, estimatedVertices: definition.type === 'asset' ? 0 : geometryEstimate(definition) };
- });
- const residentStats = geometryStats(ownedRecords);
- const pendingPlans = plans.filter(plan => !plan.existing);
- const pendingVertices = pendingPlans.reduce((total, plan) => total + plan.estimatedVertices, 0);
- if (residentStats.vertices + pendingVertices > limits.maxVertices ||
- residentStats.geometryBytes + pendingVertices * 56 > limits.maxGeometryBytes) {
+ const planGeometry = () => {
+ const ownedRecords = ownedGeometryRecords();
+ const availableRecords = new Map();
+ for (const record of ownedRecords) {
+ availableRecords.set(record.signature, record);
+ }
+ const plans = recipe.geometries.map(definition => {
+ const signature = JSON.stringify(definition);
+ const preferredRecord = preferred?.geometryRecords.get(definition.id);
+ const activeRecord = state?.geometryRecords.get(definition.id);
+ const existing = [preferredRecord, activeRecord, availableRecords.get(signature)]
+ .find(record => record?.signature === signature);
+ return { definition, signature, existing, estimatedVertices: definition.type === 'asset' ? 0 : geometryEstimate(definition) };
+ });
+ const residentStats = geometryStats(ownedRecords);
+ const pendingVertices = plans.filter(plan => !plan.existing).reduce((total, plan) => total + plan.estimatedVertices, 0);
+ const overBudget = residentStats.vertices + pendingVertices > limits.maxVertices ||
+ residentStats.geometryBytes + pendingVertices * 56 > limits.maxGeometryBytes;
+ return { plans, residentStats, pendingVertices, overBudget };
+ };
+ let planned = planGeometry();
+ // Automatic undo history never blocks an edit: drop the oldest kept revisions before refusing for budget.
+ while (planned.overBudget && revisionHistory.length > 0) {
+ revisionHistory.shift();
+ planned = planGeometry();
+ }
+ const { plans, residentStats, pendingVertices } = planned;
+ if (planned.overBudget) {
throw new RangeError('Geometry preflight exceeds peak maxVertices or maxGeometryBytes across active, checkpoint and staged resources. Reduce detail or release checkpoints');
}
@@ -1505,6 +1534,12 @@ export function createAgentScene(input, inputLimits = {}, options = {}) {
if (stagedState.topologyChanged) {
topologyRevision++;
}
+ if (incrementRevision && state) {
+ revisionHistory.push({ revision, snapshot: snapshotState() });
+ while (revisionHistory.length > REVISION_HISTORY_LIMIT) {
+ revisionHistory.shift();
+ }
+ }
state = stagedState;
if (incrementRevision) {
revision++;
@@ -1828,13 +1863,7 @@ export function createAgentScene(input, inputLimits = {}, options = {}) {
throw invalidField('checkpoints', `${checkpoints.size} saved`, `at most ${limits.maxCheckpoints} saved checkpoints; release one with scene_release_checkpoint first`);
}
const handle = Object.freeze({});
- checkpoints.set(handle, {
- recipe: authoredRecipe(state.recipe),
- geometryRecords: new Map(state.geometryRecords),
- materialHandles: new Map(state.materialHandles),
- restParts: state.restParts,
- sourceRestParts: state.sourceRestParts,
- });
+ checkpoints.set(handle, snapshotState());
return handle;
},
restore(handle, options = {}) {
@@ -1845,6 +1874,18 @@ export function createAgentScene(input, inputLimits = {}, options = {}) {
}
return commit(stage(checkpoint.recipe, checkpoint), true);
},
+ /** Go back to an earlier revision that scene_apply or scene_restore left behind; no checkpoint is needed. */
+ restoreRevision(target, options = {}) {
+ expected(options);
+ const entry = revisionHistory.find(candidate => candidate.revision === target);
+ if (!entry) {
+ const kept = revisionHistory.map(candidate => candidate.revision);
+ throw invalidField('revision', target, kept.length > 0
+ ? `one of the kept revisions: ${kept.join(', ')} (the last ${REVISION_HISTORY_LIMIT} are kept; older ones are dropped)`
+ : 'a revision this session kept, but none is kept yet because nothing has been edited; apply an edit first');
+ }
+ return commit(stage(entry.snapshot.recipe, entry.snapshot), true);
+ },
releaseCheckpoint(handle) {
if (!checkpoints.delete(handle)) {
throw invalidField('checkpointId', handle, 'a checkpointId that scene_checkpoint returned and you have not released');
diff --git a/tests/agent-asset-mesh.test.js b/tests/agent-asset-mesh.test.js
index f59a08f8..62a9a7bc 100644
--- a/tests/agent-asset-mesh.test.js
+++ b/tests/agent-asset-mesh.test.js
@@ -165,6 +165,21 @@ test('a checkpoint undoes a mesh edit and replace swaps the log', async () => {
asset.dispose();
});
+test('restoreRevision undoes mesh edits of an asset without a checkpoint', async () => {
+ const asset = await loadRobot();
+ const scene = createScene(asset);
+ applyEdits(scene, TORSO, [{ op: 'delete', select: { tag: 'top' } }]);
+ applyEdits(scene, TORSO, [{ op: 'delete', select: { tag: 'bottom' } }]);
+ const edited = partOf(scene, TORSO).geometry.indices.length;
+ scene.restoreRevision(0, { expectedRevision: scene.revision });
+ assert.equal(partOf(scene, TORSO).geometry, asset.parts[1].geometry);
+ assert.equal(scene.exportRecipe().meshEdits, undefined);
+ assert.throws(() => scene.restoreRevision(9, { expectedRevision: scene.revision }), /kept revisions: 0, 1, 2/);
+ scene.restoreRevision(2, { expectedRevision: scene.revision });
+ assert.equal(partOf(scene, TORSO).geometry.indices.length, edited);
+ asset.dispose();
+});
+
test('an exported recipe replays the edits on a fresh decode', async () => {
const asset = await loadRobot();
const scene = createScene(asset);
diff --git a/tests/agent-scene.test.js b/tests/agent-scene.test.js
index eef05fe3..13f38f53 100644
--- a/tests/agent-scene.test.js
+++ b/tests/agent-scene.test.js
@@ -2,7 +2,7 @@ import './support/load-agent-scene-modules.mjs';
import test from 'node:test';
import assert from 'node:assert/strict';
import { Matrix4, Quaternion, Vector3 } from 'three';
-import { createAgentScene, AGENT_SCENE_CAPABILITIES, AGENT_SCENE_DEFAULT_LIMITS } from '../src/agent-scene.js';
+import { createAgentScene, AGENT_SCENE_CAPABILITIES, AGENT_SCENE_DEFAULT_LIMITS, REVISION_HISTORY_LIMIT } from '../src/agent-scene.js';
import * as lightweightCapabilities from '../src/agent-scene-capabilities.js';
test('the plain-data capabilities module matches the scene engine', () => {
@@ -460,7 +460,8 @@ test('node deletion distinguishes nonrecursive rejection from explicit subtree r
{ type: 'remove-geometry', id: 'box' },
], { expectedRevision: 1 });
assert.equal(session.parts.length, 0);
- assert.equal(session.inspect().residentGeometryBytes, 0);
+ assert.equal(session.inspect().geometryBytes, 0);
+ assert.equal(session.inspect().residentGeometryBytes, 720, 'the kept earlier revisions still own the removed geometry');
});
test('resource removal and node rebinding resolve final references after sequential commands', () => {
@@ -551,7 +552,8 @@ test('peak geometry budgets count checkpoint ownership and free it on release',
{ type: 'remove-geometry', id: 'box' }, { type: 'remove-material', id: 'finish' },
], { expectedRevision: 2 });
session.releaseCheckpoint(secondCheckpoint);
- assert.equal(session.inspect().residentGeometryBytes, 0);
+ // Kept revisions still own the box; an edit that needs the room drops them oldest first.
+ assert.equal(session.inspect().residentGeometryBytes, 720);
session.apply(add, { expectedRevision: 3 });
assert.equal(session.inspect().geometryBytes, 720);
assert.equal(session.topologyRevision, 3);
@@ -650,3 +652,62 @@ test("recipe materials accept alphaMode 'add' and keep it when opacity is below
input.materials.push({ id: 'bad', color: [1, 1, 1], alphaMode: 'multiply' });
assert.throws(() => createAgentScene(input), /alphaMode: got .*; expected one of opaque, blend, add/);
});
+
+function geometryBytes(session) {
+ return session.parts.map(part => Buffer.concat([
+ Buffer.from(part.geometry.positions.buffer, part.geometry.positions.byteOffset, part.geometry.positions.byteLength),
+ Buffer.from(part.geometry.indices.buffer, part.geometry.indices.byteOffset, part.geometry.indices.byteLength),
+ Buffer.from(part.matrix.buffer, part.matrix.byteOffset, part.matrix.byteLength),
+ ]).toString('hex'));
+}
+
+test('restoreRevision undoes the last edits without a checkpoint and restores byte-identical geometry', () => {
+ const session = createAgentScene(recipe());
+ const before = session.exportRecipe();
+ const bytesBefore = geometryBytes(session);
+ const originalParts = session.parts;
+ session.apply([{ type: 'set-node', id: 'root', translation: [9, 9, 9] }], { expectedRevision: 0 });
+ session.apply([
+ { type: 'remove-node', id: 'other' },
+ { type: 'add-geometry', geometry: { id: 'wide', type: 'box', bevel: 0, subdivisions: 1 } },
+ { type: 'add-node', node: { id: 'wide-node', geometry: 'wide', material: 'finish' } },
+ ], { expectedRevision: 1 });
+ session.apply([{ type: 'set-material', id: 'finish', color: [1, 0, 0] }], { expectedRevision: 2 });
+ assert.equal(session.restoreRevision(0, { expectedRevision: 3 }), 4);
+ assert.deepEqual(session.exportRecipe(), before);
+ assert.deepEqual(geometryBytes(session), bytesBefore);
+ assert.equal(session.parts[0], originalParts[0], 'part identities are retained for the renderer');
+ assert.throws(() => session.restoreRevision(0, { expectedRevision: 3 }), /expectedRevision/);
+});
+
+test('restoreRevision keeps a bounded history, drops the oldest first and names the kept revisions', () => {
+ const session = createAgentScene(recipe());
+ assert.throws(() => session.restoreRevision(0, { expectedRevision: 0 }), /revision: got 0; expected a revision this session kept, but none is kept yet/);
+ const edits = REVISION_HISTORY_LIMIT + 3;
+ for (let index = 0; index < edits; index++) {
+ session.apply([
+ { type: 'add-geometry', geometry: { id: `extra-${index}`, type: 'box', bevel: 0, subdivisions: 1 } },
+ ...(index > 0 ? [{ type: 'remove-geometry', id: `extra-${index - 1}` }] : []),
+ ], { expectedRevision: index });
+ assert.ok(session.inspect().residentGeometryBytes <= (REVISION_HISTORY_LIMIT + 2) * 6000, 'history stays inside a fixed allocation');
+ }
+ const kept = Array.from({ length: REVISION_HISTORY_LIMIT }, (_, index) => edits - REVISION_HISTORY_LIMIT + index);
+ assert.throws(() => session.restoreRevision(0, { expectedRevision: edits }), new RegExp(`expected one of the kept revisions: ${kept.join(', ')}`));
+ assert.throws(() => session.restoreRevision(edits, { expectedRevision: edits }), /kept revisions/);
+ session.restoreRevision(kept[1], { expectedRevision: edits });
+ assert.ok(session.exportRecipe().geometries.some(geometry => geometry.id === `extra-${kept[1] - 1}`));
+ // Undoing the undo works: the state before the restore is kept under its own revision.
+ session.restoreRevision(edits, { expectedRevision: edits + 1 });
+ assert.ok(session.exportRecipe().geometries.some(geometry => geometry.id === `extra-${edits - 1}`));
+});
+
+test('kept revisions never block an edit that fits the geometry budget without them', () => {
+ const session = createAgentScene(recipe(), { maxVertices: 24, maxGeometryBytes: 1344 });
+ session.apply([
+ { type: 'remove-node', id: 'root', recursive: true }, { type: 'remove-node', id: 'other' },
+ { type: 'remove-geometry', id: 'box' }, { type: 'remove-material', id: 'finish' },
+ ], { expectedRevision: 0 });
+ session.apply([{ type: 'add-geometry', geometry: { id: 'new', type: 'box', bevel: 0 } }], { expectedRevision: 1 });
+ assert.equal(session.inspect().geometryBytes, 720);
+ assert.throws(() => session.restoreRevision(0, { expectedRevision: 2 }), /kept revisions: 1/);
+});
diff --git a/tests/mcp-tools.test.js b/tests/mcp-tools.test.js
index 61709f3f..f40472b4 100644
--- a/tests/mcp-tools.test.js
+++ b/tests/mcp-tools.test.js
@@ -82,7 +82,11 @@ async function connect(context) {
checkpoints.set(checkpointId, scene.checkpoint());
return { checkpointId, sessionId, revision: scene.revision };
},
- async restore({ checkpointId, expectedRevision }) {
+ async restore({ checkpointId, revision, expectedRevision }) {
+ if (revision !== undefined) {
+ scene.restoreRevision(revision, { expectedRevision });
+ return editStatus();
+ }
scene.restore(checkpoints.get(checkpointId), { expectedRevision });
return editStatus();
},
@@ -411,6 +415,24 @@ test('real SDK calls preserve atomic revisions, checkpoints, recipe snapshots an
assert.equal(boundary.closed(), true);
});
+test('scene_restore with a revision undoes the last edits without a checkpoint and names the kept revisions', async context => {
+ const { client, sessionId } = await connect(context);
+ const call = (name, argumentsValue = {}) => client.callTool({ name, arguments: argumentsValue });
+ await call('scene_create', { recipe: recipe() });
+ const before = (await call('scene_export_recipe', { sessionId })).structuredContent.recipe;
+ const imageBefore = (await call('scene_look', { sessionId })).content[0].data;
+ for (let revision = 0; revision < 3; revision++) {
+ await call('scene_apply', { sessionId, expectedRevision: revision, operations: [{ type: 'set-node', id: 'mesh', translation: [revision + 1, 0, 0] }] });
+ }
+ const unknown = await call('scene_restore', { sessionId, expectedRevision: 3, revision: 7 });
+ assert.equal(unknown.isError, true);
+ assert.match(unknown.content[0].text, /revision: got 7; expected one of the kept revisions: 0, 1, 2/);
+ const restored = await call('scene_restore', { sessionId, expectedRevision: 3, revision: 0 });
+ assert.equal(restored.structuredContent.revision, 4);
+ assert.deepEqual((await call('scene_export_recipe', { sessionId })).structuredContent.recipe, before);
+ assert.equal((await call('scene_look', { sessionId })).content[0].data, imageBefore);
+});
+
test('SDK stdio EOF closes the runtime without launching a scene', async () => {
const input = new PassThrough();
const output = new PassThrough();
@@ -442,7 +464,8 @@ test('branches off leaves the branch field and the variants advice out of the sc
assert.ok(!JSON.stringify(tool.inputSchema).includes('"branch"'), `${toolName} must not offer a branch`);
}
const restore = tools.find(candidate => candidate.name === 'scene_restore');
- assert.ok(restore.inputSchema.required.includes('checkpointId'));
+ assert.ok(!restore.inputSchema.required.includes('checkpointId'), 'a revision can stand in for the checkpoint');
+ assert.ok(restore.inputSchema.properties.revision);
assert.ok(!client.getInstructions().includes('branch'));
});