Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Add isolated agent visual review in 67js 0.9.0

Nguyen Xuan An45fb38cc1c2f
diff --git a/.gitignore b/.gitignore
index 8020a502..c6590ae0 100644
--- a/.gitignore
+++ b/.gitignore
@@ -43,3 +43,4 @@ public/agent-render-jobs.md
public/agent-motion.md
public/agent-character-motion.md
+public/agent-review.md
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f853efde..f0d81298 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,13 @@
# Changelog
+## 0.9.0
+
+- Add `scene_review` to compare up to four labeled camera, motion or imported clip samples in one PNG
+- Preserve source recipes, revisions, preview poses, viewport dimensions and checkpoints through isolated reviews
+- Bound review dimensions, image bytes, pending frames, sampled memory and private-render deadlines
+- Restore the source preview after failed shots and release private renderers during connection closure
+- Document the agent review workflow and verify independent shots through actual CPU-rendered pixel comparisons
+
## 0.8.1
- Refine the film scientist with integrated facial surfaces, inset eyes, swept hair and a shorter neck
diff --git a/README.md b/README.md
index d7611afb..d6c3f26f 100644
--- a/README.md
+++ b/README.md
@@ -143,9 +143,11 @@ After installing the package, run `npx 67js-mcp --backend gpu --memory 192` with
The server and preview are built into the package. The browser driver loads only when a scene is created.
Version `0.8.0` adds [imported character motion](docs/agent-character-motion.md) with stable joint IDs and atomic pose transactions.
+Version `0.9.0` adds [visual review](docs/agent-review.md) with up to four labeled views or poses in one PNG grid.
+Review snapshots preserve the source revision, preview pose and checkpoint handles.
The [asset adapter](docs/agent-asset.md) imports catalog GLBs with supported textures, rigs, morphs and clips.
-Animation track authoring, imported mesh topology edits and persistent video jobs remain implementation work.
+Imported morph track authoring and mesh topology edits remain implementation work.
## Checks and performance
diff --git a/docs/agent-review.md b/docs/agent-review.md
new file mode 100644
index 00000000..66af85e7
--- /dev/null
+++ b/docs/agent-review.md
@@ -0,0 +1,88 @@
+# Agent visual review
+
+Release `0.9.0` adds `scene_review` for inspecting several views or motion samples in one MCP image.
+The tool renders an isolated snapshot. It preserves the source recipe, revision, preview pose and checkpoint handles.
+
+## Compare views
+
+1. Create a scene or import a configured GLB.
+2. Inspect its current revision.
+3. Call `scene_review` with that revision and one to four shots.
+4. Inspect the returned PNG and each shot's metadata.
+5. Apply corrections to the source with its unchanged revision.
+
+```json
+{
+ "sessionId": "<scene UUID>",
+ "expectedRevision": 0,
+ "width": 384,
+ "height": 384,
+ "shots": [
+ {
+ "label": "Front",
+ "camera": { "eye": [0, 2, 7], "target": [0, 1.5, 0] }
+ },
+ {
+ "label": "Side",
+ "camera": { "eye": [7, 2, 0], "target": [0, 1.5, 0] }
+ },
+ {
+ "label": "Back",
+ "camera": { "eye": [0, 2, -7], "target": [0, 1.5, 0] }
+ }
+ ]
+}
+```
+
+The response contains one PNG image block, JSON text and structured metadata.
+The grid labels identify shots. Each shot reports its sampled camera, clocks, output dimensions and render resources.
+This tool does not require a configured render job directory or write output files.
+
+## Compare motion
+
+Each shot starts independently from the authored base pose.
+Omitted sampling does not inherit the previous shot's motion time or imported clip sample.
+
+`motionTime` samples recipe-owned motion. `null` selects the authored base pose.
+`animation` supplies an imported clip index and absolute time. Procedural scenes reject imported clip sampling.
+Imported clip and authored motion clocks compose through one atomic pose transaction.
+
+```json
+{
+ "sessionId": "<scene UUID>",
+ "expectedRevision": 0,
+ "shots": [
+ { "label": "Authored base" },
+ { "label": "Start", "motionTime": 0 },
+ { "label": "Middle", "motionTime": 1.5 },
+ { "label": "End", "motionTime": 3 }
+ ]
+}
+```
+
+These samples require authored motion. Nonlooping motion holds its endpoint after the duration. Looping motion wraps the requested time.
+`rendererTime` controls shader animation independently and defaults to zero.
+Camera fields override only the private shot camera. They do not author tracks or edit the source camera.
+
+## Budgets and ownership
+
+| Limit | Value |
+| --- | --- |
+| Shots | One to four |
+| Requested size per shot | 64 to 480 pixels per axis |
+| Default size per shot | 384 by 384 pixels |
+| Label | At most 48 characters |
+| Response image | At most 1 MiB |
+| Review output | One labeled PNG grid |
+
+The renderer can reduce actual dimensions to respect its memory budget. Metadata reports the actual size of each shot.
+The runtime captures one frame at a time. It releases the private renderer before restoring the source preview renderer.
+
+Review calls serialize with source edits. Active render jobs retain their exclusive renderer lease.
+Invalid shots fail without editing the source. Closing the MCP connection releases the private review resources.
+
+The 30-second deadline covers private page acquisition and rendering after snapshot and asset verification.
+Cleanup and source preview recovery follow that deadline. `elapsedSeconds` reports the measured review duration.
+
+The tool provides visual evidence. It does not diagnose every intersection, guarantee a good composition or supply automatic framing of deformed assets.
+Mesh inspection bounds describe authored geometry. Skinning and morphs can move the visible surface beyond those bounds.
diff --git a/docs/guide.md b/docs/guide.md
index c52655c1..861e3d71 100644
--- a/docs/guide.md
+++ b/docs/guide.md
@@ -401,12 +401,15 @@ Disconnect observers, cancel animation frames, release pointer state and call `d
## Models and AI agents
Version `0.5.0` includes [agent scene sessions](/agent-scene.md) and the `67js-mcp` command.
-Its [MCP server](/mcp.md) provides seventeen tools for authoring, previewing and exporting scenes through a persistent browser runtime.
+Its [MCP server](/mcp.md) provides eighteen tools for authoring, previewing and exporting scenes through a persistent browser runtime.
Release `0.7.0` adds [agent motion](/agent-motion.md) for deterministic joint, material and camera keyframes.
Read the MCP guide for npm installation, client configuration and CPU/GPU selection.
The [agent look contract](/agent-look.md) adds retained lighting, volumetric fog, grading and directional shadows to recipe edits and checkpoints.
Release `0.8.0` adds [imported character motion](/agent-character-motion.md) with editable joints and retained skin, morph and texture resources.
+Release `0.9.0` adds [visual review](/agent-review.md) for several labeled views or motion samples in one PNG grid.
+Review uses an isolated snapshot and preserves the source preview pose, revision and checkpoint handles.
+
The [asset adapter](/agent-asset.md) imports local catalog GLBs with supported textures, rigs, morphs and deterministic clip sampling.
The addon accepts JSON recipes with stable object IDs, shared geometry and material resources, hierarchy and a camera.
diff --git a/docs/mcp.md b/docs/mcp.md
index 39ced841..b75c126b 100644
--- a/docs/mcp.md
+++ b/docs/mcp.md
@@ -8,6 +8,7 @@ Release `0.5.0` exposes twelve tools for bounded JSON scene authoring and local
Release `0.6.0` adds five render job tools for PNG images, still sequences and MP4 video.
Release `0.7.0` adds [procedural motion](agent-motion.md), transient preview seeks and motion sampling in snapshot jobs.
Release `0.8.0` adds [imported character motion](agent-character-motion.md) with source joints and independent clip timing.
+Release `0.9.0` adds [visual review](agent-review.md) for several labeled views or poses from one isolated snapshot.
It renders one active scene and returns PNG images through MCP image content.
Tool results also contain JSON text and structured metadata.
@@ -29,7 +30,7 @@ The MCP connection uses stdin and stdout, without an HTTP MCP listener.
```
Run the installed command with `npx 67js-mcp --backend gpu --memory 192`.
- For a standalone launch, use `npx --package @codepawlhq/[email protected] 67js-mcp --backend gpu --memory 192`.
+ For a standalone launch, use `npx --package @codepawlhq/[email protected] 67js-mcp --backend gpu --memory 192`.
`67js-mcp --help` lists options. `67js-mcp --version` reports the installed version.
2. Configure your MCP client with absolute paths to Node and the installed CLI:
@@ -102,6 +103,7 @@ Inspect or export the recipe before retrying. Context loss still permits recipe
| `scene_inspect` | `sessionId`, optional `ids`, `limit`, `includeBounds` | Compact node records and revision |
| `scene_apply` | `sessionId`, `expectedRevision`, `operations` | Updated revision, inspection, and render status |
| `scene_look` | `sessionId`, optional `width`, `height`, `motionTime` | PNG image and metadata |
+| `scene_review` | `sessionId`, `expectedRevision`, `shots`, optional `width`, `height` | Labeled PNG grid and metadata from an isolated snapshot |
| `scene_checkpoint` | `sessionId` | Checkpoint ID, session ID, and revision |
| `scene_restore` | `sessionId`, `checkpointId`, `expectedRevision` | Updated revision, inspection, and render status |
| `scene_release_checkpoint` | `sessionId`, `checkpointId` | Release confirmation |
@@ -123,6 +125,9 @@ Set operations use `set-node`, `set-material`, or `set-camera`, with fields dire
An explicit `null` restores the authored base pose. Release `0.8.0` also supports imported source-node motion.
Imported clip sampling remains available through `set-animation`.
+`scene_review` compares up to four cameras or motion samples without changing the source recipe, revision or preview pose.
+Each shot starts from the authored base pose. The [review guide](agent-review.md) describes separate clocks, dimensions and resource limits.
+
`set-node` can rebind a mesh to another geometry/material pair.
The recipe also accepts [authored lighting, fog, effects and shadow coverage](agent-look.md).
diff --git a/docs/release-verification.md b/docs/release-verification.md
index 15ebdc7f..4d6ac939 100644
--- a/docs/release-verification.md
+++ b/docs/release-verification.md
@@ -1,5 +1,33 @@
# Release verification
+## 0.9.0
+
+Source checks used Windows Node.js, installed Chrome with CPU SwiftShader and actual MCP calls.
+Registry publication and live deployment require separate verification against the pushed commit.
+
+| Check | Measured result |
+| --- | --- |
+| Node tests | 434 tests passed. |
+| Native review | Front, side and back camera shots produced one labeled PNG grid. |
+| Independent poses | An omitted second motion sample matched the authored base pixels exactly. |
+| Imported clips | Explicit and omitted clip samples matched their independently rendered reference pixels. |
+| Source preservation | Preview PNG bytes, canonical recipe, revision and checkpoint restoration survived reviews and invalid shots. |
+| Active closure | Closing a confirmed active review released the runtime in 0.12 seconds. |
+
+The review response limits shots to four, dimensions to 480 pixels per axis and PNG bytes to 1 MiB.
+It keeps one pending frame and reports requested tile sizes separately from actual render dimensions.
+The private review has a 30-second deadline after source snapshot and asset verification. Cleanup and preview recovery follow it.
+
+The public contract review found a stalled page acquisition that could delay closure.
+A rejecting cancellation race and late-page disposal removed that path. Regression tests failed before the correction and passed afterward.
+The source follow-up found no remaining findings within its scope.
+
+Only one model family reviewed the contract because the other reviewer remained unavailable. This gives weaker coverage than a completed cross review.
+
+A clean source package passed modern and legacy MCP calls without development dependencies or source files.
+These checks cover CPU rendering. They do not establish hardware GPU performance or better artistic quality.
+
+
## 0.8.1
Source checks used Windows Node.js, installed Chrome with CPU SwiftShader and FFmpeg H.264 encoding.
diff --git a/package-lock.json b/package-lock.json
index 65d404f7..b513bddc 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "@codepawlhq/67js",
- "version": "0.8.1",
+ "version": "0.9.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@codepawlhq/67js",
- "version": "0.8.1",
+ "version": "0.9.0",
"license": "MIT",
"dependencies": {
"playwright-core": "1.64.0"
diff --git a/package.json b/package.json
index ca8825ae..1bed91ba 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "@codepawlhq/67js",
- "version": "0.8.1",
+ "version": "0.9.0",
"private": false,
"type": "module",
"description": "JavaScript tools for agent-driven 3D authoring, browser previews and memory-aware CPU/GPU rendering",
@@ -49,7 +49,8 @@
"docs/agent-asset.md",
"docs/agent-render-jobs.md",
"docs/agent-motion.md",
- "docs/agent-character-motion.md"
+ "docs/agent-character-motion.md",
+ "docs/agent-review.md"
],
"main": "./build/67.module.js",
"module": "./build/67.module.js",
@@ -106,7 +107,8 @@
"smoke:enhancements": "node scripts/smoke-enhancements.mjs",
"smoke:site": "node scripts/smoke-site.mjs",
"publish:ci": "node scripts/publish-ci.mjs",
- "smoke:agent-character": "node scripts/smoke-agent-character.mjs"
+ "smoke:agent-character": "node scripts/smoke-agent-character.mjs",
+ "smoke:agent-review": "node scripts/smoke-agent-review.mjs"
},
"peerDependencies": {
"@dimforge/rapier3d-compat": "0.21.0"
diff --git a/public/llms.txt b/public/llms.txt
index f4b47628..08e7da70 100644
--- a/public/llms.txt
+++ b/public/llms.txt
@@ -11,6 +11,10 @@ Version `0.5.0` adds `67js/addons/agent-scene` and the `67js-mcp` command.
Version `0.6.0` adds asynchronous snapshot render jobs. Read `/agent-render-jobs.md` for submission, progress, cancellation and artifact results.
Version `0.8.0` adds imported source-node overrides and motion. Read `/agent-character-motion.md` for joint IDs, layering and pose ownership.
+
+Version `0.9.0` adds `scene_review`. Read `/agent-review.md` for a labeled PNG grid of up to four views or poses.
+Review uses an isolated snapshot with separate camera and clock settings. It preserves the source revision and preview pose.
+
Version `0.7.0` adds recipe motion and atomic set-motion authoring. Read `/agent-motion.md` before generating tracks.
Use scene_look motionTime for absolute procedural preview seeks. Omit it to preserve the last pose, or use null for the authored base.
diff --git a/scripts/agent-preview-browser.js b/scripts/agent-preview-browser.js
index 4ddbd2dd..63be2493 100644
--- a/scripts/agent-preview-browser.js
+++ b/scripts/agent-preview-browser.js
@@ -61,7 +61,7 @@ function renderInfo(renderer) {
};
}
-function draw(record, time = 0) {
+function draw(record, time = 0, camera = record.scene.camera) {
if (!record.renderer) throw new Error('The scene renderer is leased to a render job.');
if (record.renderer.context.isContextLost()) {
throw new Error('The render context was lost. Export the recipe and dispose this session.');
@@ -85,7 +85,7 @@ function draw(record, time = 0) {
record.shadowKey = shadowKey;
}
record.renderer.world = environment.world;
- record.renderer.render({ ...record.scene.camera, environment, effects, exposure: effects.exposure, time });
+ record.renderer.render({ ...camera, environment, effects, exposure: effects.exposure, time });
const error = record.renderer.context.getError();
if (error !== 0) {
throw new Error(`WebGL render failed with error ${error}.`);
@@ -168,6 +168,48 @@ function createPreview(scene, { sessionId, memoryBudgetMiB, backend }, asset) {
}
window.__agentPreview = {
+ reviewBegin({ sessionId, width, height }) {
+ const record = requireSession(sessionId);
+ record.reviewGrid = document.createElement('canvas');
+ record.reviewGrid.width = width;
+ record.reviewGrid.height = height;
+ const context = record.reviewGrid.getContext('2d');
+ context.fillStyle = '#202428';
+ context.fillRect(0, 0, width, height);
+ return { width, height };
+ },
+ reviewShot({ sessionId, shot, index, width, height, columns }) {
+ const record = requireSession(sessionId);
+ const recipe = record.scene.exportRecipe();
+ const animation = shot.animation ?? recipe.animation ?? null;
+ if (record.asset) {
+ record.scene.sampleFrame({ animation, motionTime: shot.motionTime });
+ } else {
+ if (shot.animation !== undefined) throw new RangeError('Imported animation requires an asset scene.');
+ record.scene.sampleMotion(shot.motionTime);
+ }
+ const camera = createAgentScene({ format: '67js.scene', schemaVersion: 1,
+ geometries: [], materials: [], nodes: [], camera: { ...record.scene.camera, ...shot.camera } }).camera;
+ validatePreviewCamera(camera);
+ draw(record, shot.rendererTime, camera);
+ const render = renderInfo(record.renderer);
+ if (render.width < 64 || render.height < 64) throw new Error('Render budget reduced review below its minimum output size.');
+ const context = record.reviewGrid.getContext('2d');
+ const x = index % columns * width;
+ const y = Math.floor(index / columns) * (height + 24);
+ context.drawImage(canvas, x, y + 24, width, height);
+ context.fillStyle = '#e4e7e9';
+ context.font = '12px sans-serif';
+ context.textBaseline = 'middle';
+ context.fillText(shot.label.replace(/[\r\n\t]/g, ' '), x + 8, y + 12, width - 16);
+ return { label: shot.label, camera, animation: record.asset ? animation : null,
+ motionTime: record.scene.motionTime ?? null, rendererTime: shot.rendererTime,
+ requestedWidth: width, requestedHeight: height, ...render };
+ },
+ reviewResult({ sessionId }) {
+ const record = requireSession(sessionId);
+ return { data: record.reviewGrid.toDataURL('image/png').split(',')[1], mimeType: 'image/png' };
+ },
snapshot({ sessionId, expectedRevision }) {
const record = requireSession(sessionId);
if (record.scene.revision !== expectedRevision) throw new Error('Stale revision for render snapshot.');
diff --git a/scripts/agent-review.mjs b/scripts/agent-review.mjs
new file mode 100644
index 00000000..ca483f40
--- /dev/null
+++ b/scripts/agent-review.mjs
@@ -0,0 +1,64 @@
+export const REVIEW_LIMITS = Object.freeze({ minimumShots: 1, maximumShots: 4,
+ minimumDimension: 64, maximumDimension: 480, defaultWidth: 384, defaultHeight: 384,
+ labelHeight: 24, maximumLabelLength: 48, maximumGridWidth: 960, maximumGridHeight: 1008,
+ maximumImageBytes: 1024 * 1024, maximumPendingFrames: 1 });
+
+function fields(value, allowed, name) {
+ if (!value || typeof value !== 'object' || Array.isArray(value) ||
+ Object.keys(value).some(key => !allowed.includes(key))) {
+ throw new TypeError(`Invalid or unknown ${name} fields.`);
+ }
+}
+
+function clock(value, name) {
+ if (!Number.isFinite(value) || value < 0 || value > 3600) {
+ throw new RangeError(`${name} must be finite and within zero and 3600.`);
+ }
+ return value;
+}
+
+/** Validate before leasing the source renderer. Camera relationships use the sampled pose. */
+export function normalizeReview(input) {
+ fields(input, ['sessionId', 'expectedRevision', 'width', 'height', 'shots'], 'review');
+ if (typeof input.sessionId !== 'string' || !Number.isSafeInteger(input.expectedRevision) || input.expectedRevision < 0) {
+ throw new TypeError('Review requires a sessionId and a safe nonnegative expectedRevision.');
+ }
+ const width = input.width === undefined ? REVIEW_LIMITS.defaultWidth : input.width;
+ const height = input.height === undefined ? REVIEW_LIMITS.defaultHeight : input.height;
+ if (![width, height].every(value => Number.isInteger(value) && value >= 64 && value <= 480)) {
+ throw new RangeError('Review dimensions must be integers from 64 to 480.');
+ }
+ if (!Array.isArray(input.shots) || input.shots.length < 1 || input.shots.length > 4) {
+ throw new RangeError('Review requires one to four shots.');
+ }
+ const shots = input.shots.map((shot, index) => {
+ fields(shot, ['label', 'camera', 'animation', 'motionTime', 'rendererTime'], 'shot');
+ if (shot.label !== undefined && (typeof shot.label !== 'string' || shot.label.length > 48)) {
+ throw new TypeError('Shot label must be a string of at most 48 characters.');
+ }
+ if (shot.camera !== undefined) {
+ fields(shot.camera, ['eye', 'target', 'up', 'fov', 'near', 'far'], 'camera');
+ for (const [field, value] of Object.entries(shot.camera)) {
+ const components = ['eye', 'target', 'up'].includes(field) ? value : [value];
+ if (!Array.isArray(components) || components.length !== (['eye', 'target', 'up'].includes(field) ? 3 : 1) ||
+ !components.every(component => Number.isFinite(component) && Number.isFinite(Math.fround(component)))) {
+ throw new RangeError('Shot camera must contain finite Float32 values.');
+ }
+ }
+ }
+ if (shot.animation !== undefined) {
+ fields(shot.animation, ['clip', 'time'], 'animation');
+ if (!Number.isSafeInteger(shot.animation.clip) || shot.animation.clip < 0) throw new RangeError('Invalid animation clip.');
+ clock(shot.animation.time, 'Animation time');
+ }
+ const motionTime = shot.motionTime ?? null;
+ if (motionTime !== null) clock(motionTime, 'Motion time');
+ return { label: shot.label ?? `View ${index + 1}`,
+ ...(shot.camera === undefined ? {} : { camera: structuredClone(shot.camera) }),
+ ...(shot.animation === undefined ? {} : { animation: structuredClone(shot.animation) }),
+ motionTime, rendererTime: clock(shot.rendererTime === undefined ? 0 : shot.rendererTime, 'Renderer time') };
+ });
+ const columns = shots.length > 1 ? 2 : 1;
+ return { sessionId: input.sessionId, expectedRevision: input.expectedRevision, width, height, shots,
+ gridWidth: width * columns, gridHeight: (height + REVIEW_LIMITS.labelHeight) * Math.ceil(shots.length / columns), columns };
+}
diff --git a/scripts/agent-runtime.mjs b/scripts/agent-runtime.mjs
index 658135a8..3e962902 100644
--- a/scripts/agent-runtime.mjs
+++ b/scripts/agent-runtime.mjs
@@ -8,6 +8,7 @@ import { createAgentScene, AGENT_SCENE_CAPABILITIES } from '../src/agent-scene.j
import { createAgentAssetCatalog } from './agent-asset-catalog.mjs';
import { createAgentRenderJobs } from './agent-render-jobs.mjs';
import { createFrameEncoder } from './frame-encoder.mjs';
+import { normalizeReview, REVIEW_LIMITS } from './agent-review.mjs';
const EMPTY_RECIPE = { format: '67js.scene', schemaVersion: 1, geometries: [], materials: [], nodes: [] };
const SCENE_LIMITS = createAgentScene(EMPTY_RECIPE).limits;
@@ -42,6 +43,8 @@ export function createAgentRuntime({ backend = 'gpu', browser: browserPath, memo
let browserInstance;
let httpServer;
let page;
+ let reviewPage;
+ let cancelReview;
let activeSessionId = null;
let queuedCalls = 0;
let queue = Promise.resolve();
@@ -167,24 +170,30 @@ export function createAgentRuntime({ backend = 'gpu', browser: browserPath, memo
return evaluate(method, input);
}
- async function evaluate(method, input) {
+ async function evaluate(method, input, target = page) {
let timer;
let timedOut = false;
try {
return await Promise.race([
- page.evaluate(({ method, input }) => window.__agentPreview[method](input), { method, input }),
+ target.evaluate(({ method, input }) => window.__agentPreview[method](input), { method, input }),
new Promise((resolve, reject) => {
timer = setTimeout(() => {
timedOut = true;
- phase = 'failed';
- reject(new Error('The preview operation exceeded 30 seconds. This runtime must be closed.'));
+ if (target === page) phase = 'failed';
+ reject(new Error(target === page
+ ? 'The preview operation exceeded 30 seconds. This runtime must be closed.'
+ : 'The private render operation exceeded 30 seconds.'));
}, EVALUATION_TIMEOUT_MS);
}),
]);
} catch (error) {
if (timedOut) {
- activeSessionId = null;
- await shutdownResources();
+ if (target === page) {
+ activeSessionId = null;
+ await shutdownResources();
+ } else {
+ await target.close();
+ }
}
throw error;
} finally {
@@ -305,6 +314,9 @@ export function createAgentRuntime({ backend = 'gpu', browser: browserPath, memo
scene: AGENT_SCENE_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 },
+ review: { ...REVIEW_LIMITS, backend, memoryBudgetMiB: memory, evaluationTimeoutMs: EVALUATION_TIMEOUT_MS,
+ totalTimeoutMs: EVALUATION_TIMEOUT_MS,
+ sourcePreserved: true, defaultMotionTime: null, defaultRendererTime: 0 },
phase: closing && phase !== 'closed' ? 'closing' : phase,
availableIn: packageMetadata.version,
assets: {
@@ -383,6 +395,128 @@ export function createAgentRuntime({ backend = 'gpu', browser: browserPath, memo
return invoke('checkpoint', { ...input, checkpointId: randomUUID() });
});
},
+ review(input) {
+ let settings;
+ try { settings = normalizeReview(input); }
+ catch (error) { return Promise.reject(error); }
+ return enqueue(async () => {
+ await requirePreviewRenderer();
+ requireSession(settings.sessionId);
+ const snapshot = await invoke('snapshot', settings);
+ const assetBytes = snapshot.recipe.format === '67js.asset' ? await (await catalog()).read(snapshot.recipe.assetId) : undefined;
+ const privateSessionId = randomUUID();
+ const started = performance.now();
+ let suspended = false;
+ let privateCreated = false;
+ let session;
+ let output;
+ let deadlineExpired = false;
+ let cancellationReason;
+ const cancellation = new Promise((resolve, reject) => {
+ cancelReview = error => {
+ cancellationReason ??= error;
+ reject(cancellationReason);
+ reviewPage?.close().catch(() => {});
+ };
+ });
+ // Cancellation can arrive during source suspension, before acquisition attaches its race.
+ cancellation.catch(() => {});
+ const deadline = setTimeout(() => {
+ deadlineExpired = true;
+ cancelReview(new Error('The review exceeded its total 30 second deadline.'));
+ }, EVALUATION_TIMEOUT_MS);
+ function requireReviewOpen() {
+ if (deadlineExpired) throw new Error('The review exceeded its total 30 second deadline.');
+ if (closing) throw new Error('The agent runtime is closing.');
+ }
+ async function reviewEvaluate(method, value) {
+ requireReviewOpen();
+ const result = await evaluate(method, value, reviewPage);
+ requireReviewOpen();
+ return result;
+ }
+ try {
+ await invoke('suspend', { sessionId: settings.sessionId });
+ suspended = true;
+ phase = 'reviewing';
+ requireReviewOpen();
+ const acquisition = browserInstance.newPage({ viewport: { width: settings.width, height: settings.height }, deviceScaleFactor: 1 })
+ .then(async acquired => {
+ if (cancellationReason) {
+ await acquired.close();
+ throw cancellationReason;
+ }
+ return acquired;
+ });
+ reviewPage = await Promise.race([acquisition, cancellation]);
+ requireReviewOpen();
+ const origin = `http://127.0.0.1:${httpServer.address().port}`;
+ await reviewPage.route('**/*', route => new URL(route.request().url()).origin === origin ? route.continue() : route.abort());
+ reviewPage.setDefaultTimeout(15000);
+ await reviewPage.goto(origin);
+ await reviewPage.waitForFunction(() => Boolean(window.__agentPreview));
+ await reviewEvaluate(assetBytes ? 'createAsset' : 'create', { sessionId: privateSessionId,
+ recipe: snapshot.recipe, memoryBudgetMiB: memory, backend,
+ ...(assetBytes ? { data: assetBytes.toString('base64') } : {}) });
+ privateCreated = true;
+ await reviewEvaluate('reviewBegin', { sessionId: privateSessionId,
+ width: settings.gridWidth, height: settings.gridHeight });
+ session = await reviewPage.context().newCDPSession(reviewPage);
+ const shots = [];
+ let peakBrowserHeap = 0;
+ let peakNodeBytes = 0;
+ for (const [index, shot] of settings.shots.entries()) {
+ const rendered = await reviewEvaluate('reviewShot', { sessionId: privateSessionId, shot, index,
+ width: settings.width, height: settings.height, columns: settings.columns });
+ if (backend === 'cpu' && !/swiftshader/i.test(rendered.graphics)) throw new Error('CPU review did not select SwiftShader.');
+ peakNodeBytes = Math.max(peakNodeBytes, process.memoryUsage().rss);
+ peakBrowserHeap = Math.max(peakBrowserHeap, (await session.send('Runtime.getHeapUsage')).usedSize);
+ if (peakNodeBytes > 512 * 1024 ** 2 || peakBrowserHeap > 256 * 1024 ** 2) {
+ throw new Error('Review exceeded its Node RSS or sampled browser heap guard.');
+ }
+ shots.push(rendered);
+ }
+ const result = await reviewEvaluate('reviewResult', { sessionId: privateSessionId });
+ if (Buffer.byteLength(result.data, 'base64') > MAXIMUM_IMAGE_BYTES) throw new Error('The review PNG exceeds the 1 MiB image response budget. Request smaller shots.');
+ output = { ...result, metadata: { sessionId: settings.sessionId, sourceRevision: snapshot.sourceRevision,
+ backend, width: settings.gridWidth, height: settings.gridHeight, shots,
+ peakNodeBytes, peakBrowserHeap, maximumPendingFrames: 1 } };
+ } catch (error) {
+ if (deadlineExpired) throw new Error('The review exceeded its total 30 second deadline.');
+ throw error;
+ } finally {
+ clearTimeout(deadline);
+ cancelReview = undefined;
+ try {
+ if (reviewPage && !reviewPage.isClosed()) {
+ try {
+ if (privateCreated && !closing) await evaluate('dispose', { sessionId: privateSessionId }, reviewPage);
+ } finally {
+ try { await reviewPage.close(); }
+ catch (error) {
+ phase = 'failed';
+ await shutdownResources();
+ throw error;
+ }
+ }
+ }
+ } finally {
+ reviewPage = undefined;
+ await session?.detach().catch(() => {});
+ if (suspended && !closing && phase !== 'failed') {
+ try { await invoke('resume', { sessionId: settings.sessionId }); }
+ catch (error) {
+ phase = 'failed';
+ throw new Error(`Preview recovery failed after review: ${error.message}`);
+ }
+ phase = 'ready';
+ }
+ }
+ }
+ output.metadata.elapsedSeconds = (performance.now() - started) / 1000;
+ return output;
+ });
+ },
restore(input) {
return enqueue(async () => {
await requirePreviewRenderer();
@@ -444,8 +578,10 @@ export function createAgentRuntime({ backend = 'gpu', browser: browserPath, memo
close() {
if (!closing) {
phase = 'closing';
+ cancelReview?.(new Error('The agent runtime is closing.'));
closing = (async () => {
try {
+ await reviewPage?.close().catch(() => {});
if (jobsPromise) await (await jobsPromise).close();
} finally {
await queue;
diff --git a/scripts/mcp-server.mjs b/scripts/mcp-server.mjs
index 8e80c84f..c46881f0 100644
--- a/scripts/mcp-server.mjs
+++ b/scripts/mcp-server.mjs
@@ -206,7 +206,7 @@ function jsonResult(value) {
export function createAgentMcpServer(runtime, { version = packageMetadata.version } = {}) {
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. Use scene_look to judge the actual image. 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. 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. 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 = () => {
@@ -236,6 +236,21 @@ export function createAgentMcpServer(runtime, { version = packageMetadata.versio
const { data, mimeType, metadata } = await runtime.look(argumentsValue);
return { content: [{ type: 'image', data, mimeType }, { type: 'text', text: JSON.stringify(metadata) }], structuredContent: metadata };
});
+ register('scene_review', 'Compare one to four independent camera or motion samples in one labeled PNG grid. Preserves source revision, transient pose, viewport and checkpoints. Omitted motionTime restores authored base pose; omitted animation uses the authored asset clip pose; rendererTime defaults to zero. No render job store is required.', z.strictObject({
+ ...sessionFields, expectedRevision,
+ width: z.number().int().min(64).max(480).default(384),
+ height: z.number().int().min(64).max(480).default(384),
+ shots: z.array(z.strictObject({
+ label: z.string().max(48).optional(),
+ camera: z.strictObject(cameraFields).optional(),
+ animation: z.strictObject({ clip: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER), time: z.number().min(0).max(3600) }).optional(),
+ motionTime: z.number().min(0).max(3600).nullable().optional(),
+ rendererTime: z.number().min(0).max(3600).optional(),
+ })).min(1).max(4),
+ }), readOnly, async argumentsValue => {
+ const { data, mimeType, metadata } = await runtime.review(argumentsValue);
+ 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.', z.strictObject({ ...checkpointFields, 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), edit, async argumentsValue => jsonResult(await runtime.releaseCheckpoint(argumentsValue)));
diff --git a/scripts/prepare-release.mjs b/scripts/prepare-release.mjs
index 102467c7..5b5a6a2f 100644
--- a/scripts/prepare-release.mjs
+++ b/scripts/prepare-release.mjs
@@ -41,7 +41,7 @@ const sourceDocuments = [
'gltf-morph.md', 'morph-targets.md', 'skinning.md', 'physics.md',
'export-glb.md', 'sculpt.md', 'surface.md', 'mesh-query.md', 'primitives.md', 'shrinkwrap.md',
'camera-path.md', 'lighting.md', 'volumetric.md', 'film-physics.md',
- 'surface-attachment.md', 'agent-scene.md', 'mcp.md', 'agent-look.md', 'agent-asset.md', 'agent-render-jobs.md', 'agent-motion.md', 'agent-character-motion.md',
+ 'surface-attachment.md', 'agent-scene.md', 'mcp.md', 'agent-look.md', 'agent-asset.md', 'agent-render-jobs.md', 'agent-motion.md', 'agent-character-motion.md', 'agent-review.md',
];
for (const name of sourceDocuments) {
await copyFile(resolve(root, 'docs', name), resolve(root, 'public', name));
diff --git a/scripts/smoke-agent-assets.mjs b/scripts/smoke-agent-assets.mjs
index 765616d7..243627b4 100644
--- a/scripts/smoke-agent-assets.mjs
+++ b/scripts/smoke-agent-assets.mjs
@@ -35,7 +35,7 @@ async function look(sessionId, label) {
}
try {
await client.connect(transport, { timeout: 180000 });
- assert.equal((await client.listTools()).tools.length, 17);
+ assert.equal((await client.listTools()).tools.length, 18);
const catalog = (await call('scene_asset_catalog')).structuredContent;
assert.equal(catalog.configured, true);
assert.equal(catalog.assets.length, 2);
@@ -81,7 +81,7 @@ try {
await call('scene_restore', { sessionId: rigId, checkpointId: initialCheckpoint.checkpointId, expectedRevision: 3 });
assert.deepEqual(await look(rigId, 'rig-restored'), initial);
await call('scene_dispose', { sessionId: rigId });
- const report = { tools: 17, backend: 'cpu', robotParts: created.inspection.counts.parts,
+ const report = { tools: 18, backend: 'cpu', robotParts: created.inspection.counts.parts,
robotRestoreExact: true, texturedRigLoaded: true, backwardSeekExact: true, originalPoseRestoreExact: true };
await writeFile('artifacts/agent-assets-cpu.json', JSON.stringify(report, null, 2));
console.log(JSON.stringify(report));
diff --git a/scripts/smoke-agent-render-jobs.mjs b/scripts/smoke-agent-render-jobs.mjs
index 256094fb..90c5002c 100644
--- a/scripts/smoke-agent-render-jobs.mjs
+++ b/scripts/smoke-agent-render-jobs.mjs
@@ -57,7 +57,7 @@ async function close() {
}
try {
await connect();
- assert.equal((await client.listTools()).tools.length, 17);
+ assert.equal((await client.listTools()).tools.length, 18);
const catalog = (await call('scene_asset_catalog')).structuredContent;
const created = (await call('scene_create_asset', { recipe: {
format: '67js.asset', schemaVersion: 1, assetId: catalog.assets[0].assetId,
@@ -127,7 +127,7 @@ try {
animatedFramesDiffer: true, activeCancel: true, eofCleanup: true, restartResults: true,
sourcePngExact: true, sourceCheckpointRetained: true, immutableAsset: true,
imageAndEightStills: true, release: true }, null, 2));
- console.log(JSON.stringify({ tools: 17, videoFrames: 8, activeCancel: true, eofCleanup: true,
+ console.log(JSON.stringify({ tools: 18, videoFrames: 8, activeCancel: true, eofCleanup: true,
restartResults: true, sourcePngExact: true, maximumPendingFrames: result.metrics.maximumPendingFrames }));
} finally {
if (client) await client.close();
diff --git a/scripts/smoke-agent-review-close.mjs b/scripts/smoke-agent-review-close.mjs
new file mode 100644
index 00000000..dcab8964
--- /dev/null
+++ b/scripts/smoke-agent-review-close.mjs
@@ -0,0 +1,36 @@
+import assert from 'node:assert/strict';
+import { constants, setPriority } from 'node:os';
+import { performance } from 'node:perf_hooks';
+import { setTimeout as delay } from 'node:timers/promises';
+import { writeFile } from 'node:fs/promises';
+import { createAgentRuntime } from './agent-runtime.mjs';
+import { createAgentPreviewFixture } from './agent-preview-fixture.mjs';
+
+setPriority(0, constants.priority.PRIORITY_BELOW_NORMAL);
+const runtime = createAgentRuntime({ backend: 'cpu', memory: 96 });
+try {
+ const created = await runtime.create({ recipe: createAgentPreviewFixture() });
+ const pending = runtime.review({ sessionId: created.sessionId, expectedRevision: 0,
+ width: 480, height: 480, shots: [{}, {}, {}, {}] }).then(
+ () => ({ completed: true }), error => ({ completed: false, message: error.message }));
+ const deadline = performance.now() + 5000;
+ let phase;
+ do {
+ phase = (await runtime.capabilities()).phase;
+ if (phase === 'reviewing') break;
+ await delay(2);
+ } while (performance.now() < deadline);
+ assert.equal(phase, 'reviewing', 'Close must target a confirmed active review');
+ const start = performance.now();
+ await runtime.close();
+ const elapsedSeconds = (performance.now() - start) / 1000;
+ const outcome = await pending;
+ assert.equal(outcome.completed, false);
+ assert.equal((await runtime.capabilities()).phase, 'closed');
+ assert.ok(elapsedSeconds < 5, 'Closing an active review must release resources promptly');
+ const report = { activePhaseObserved: phase, finalPhase: 'closed', outcome, elapsedSeconds };
+ await writeFile('artifacts/agent-review-close.json', JSON.stringify(report, null, 2));
+ console.log(JSON.stringify(report));
+} finally {
+ await runtime.close();
+}
diff --git a/scripts/smoke-agent-review.mjs b/scripts/smoke-agent-review.mjs
new file mode 100644
index 00000000..8cb65113
--- /dev/null
+++ b/scripts/smoke-agent-review.mjs
@@ -0,0 +1,137 @@
+import assert from 'node:assert/strict';
+import { mkdtemp, mkdir, writeFile } from 'node:fs/promises';
+import { tmpdir, constants, setPriority } from 'node:os';
+import { join, resolve } from 'node:path';
+import { createHash } from 'node:crypto';
+import { spawnSync } from 'node:child_process';
+import { Client } from '@modelcontextprotocol/client';
+import { StdioClientTransport } from '@modelcontextprotocol/client/stdio';
+import { createAgentCharacterFixture } from './agent-character-fixture.mjs';
+import { createTexturedRigFixture } from './agent-asset-fixture.mjs';
+
+setPriority(0, constants.priority.PRIORITY_BELOW_NORMAL);
+const directory = await mkdtemp(join(tmpdir(), '67js-review-proof-'));
+const assets = join(directory, 'assets');
+await mkdir(assets);
+const fixture = await createAgentCharacterFixture();
+await writeFile(join(assets, 'pip.glb'), fixture.bytes);
+fixture.recipe.assetId = createHash('sha256').update(fixture.bytes).digest('hex');
+const clipFixture = await createTexturedRigFixture();
+await writeFile(join(assets, 'clip-rig.glb'), clipFixture);
+const clipAssetId = createHash('sha256').update(clipFixture).digest('hex');
+const cli = resolve(process.argv[2] ?? 'bin/67js-mcp.mjs');
+const transport = new StdioClientTransport({ command: process.execPath,
+ args: [cli, '--backend', 'cpu', '--memory', '96', '--assets', assets], cwd: directory, stderr: 'pipe' });
+let diagnostics = '';
+transport.stderr.on('data', bytes => { diagnostics = (diagnostics + bytes).slice(-8192); });
+const client = new Client({ name: '67js-review-proof', version: '1' });
+async function call(name, argumentsValue) {
+ const result = await client.callTool({ name, arguments: argumentsValue }, { timeout: 60000 });
+ assert.equal(result.isError, undefined, result.content?.find(item => item.type === 'text')?.text);
+ return result;
+}
+async function rejected(argumentsValue) {
+ const result = await client.callTool({ name: 'scene_review', arguments: argumentsValue }, { timeout: 60000 });
+ assert.equal(result.isError, true, 'Invalid review must fail rather than commit source changes');
+}
+function image(result) {
+ const block = result.content.find(item => item.type === 'image');
+ assert.equal(block.mimeType, 'image/png');
+ return Buffer.from(block.data, 'base64');
+}
+function pixels(bytes, crop) {
+ const decoded = spawnSync('ffmpeg', ['-hide_banner', '-loglevel', 'error', '-i', 'pipe:0',
+ ...(crop ? ['-vf', crop] : []), '-frames:v', '1', '-f', 'rawvideo', '-pix_fmt', 'rgba', 'pipe:1'],
+ { input: bytes, windowsHide: true, maxBuffer: 8 * 1024 * 1024 });
+ assert.equal(decoded.status, 0, decoded.stderr.toString());
+ return decoded.stdout;
+}
+try {
+ await client.connect(transport);
+ assert.equal((await client.listTools()).tools.length, 18);
+ const created = (await call('scene_create_asset', { recipe: fixture.recipe })).structuredContent;
+ const sessionId = created.sessionId;
+ const checkpoint = (await call('scene_checkpoint', { sessionId })).structuredContent;
+ const canonical = (await call('scene_export_recipe', { sessionId })).structuredContent.recipe;
+ const base = image(await call('scene_look', { sessionId, motionTime: null, width: 384, height: 384 }));
+ const preview = image(await call('scene_look', { sessionId, motionTime: 1.5, width: 384, height: 384 }));
+ assert.notDeepEqual(base, preview);
+ const settings = { sessionId, expectedRevision: 0, width: 384, height: 384 };
+ const single = await call('scene_review', { ...settings, shots: [{ label: 'One pose', motionTime: 1.5 }] });
+ assert.equal(single.structuredContent.width, 384);
+ assert.equal(single.structuredContent.height, 408);
+ assert.deepEqual(pixels(image(single), 'crop=384:384:0:24'), pixels(preview));
+ const maximum = await call('scene_review', { ...settings, shots: [
+ { label: 'Start', motionTime: 0 }, { label: 'Middle', motionTime: 1.5 },
+ { label: 'End', motionTime: 3 }, { label: 'Authored base' },
+ ] });
+ assert.equal(maximum.structuredContent.width, 768);
+ assert.equal(maximum.structuredContent.height, 816);
+ assert.deepEqual(pixels(image(maximum), 'crop=384:384:384:432'), pixels(base));
+
+ const views = await call('scene_review', { ...settings, shots: [
+ { label: 'Front', motionTime: 1.5, camera: { eye: [0, 2, 7], target: [0, 1.55, 0] } },
+ { label: 'Side', motionTime: 1.5, camera: { eye: [7, 2, 0], target: [0, 1.55, 0] } },
+ { label: 'Back', motionTime: 1.5, camera: { eye: [0, 2, -7], target: [0, 1.55, 0] } },
+ ] });
+ const grid = image(views);
+ assert.ok(grid.length <= 1024 * 1024);
+ await mkdir('artifacts', { recursive: true });
+ await writeFile('artifacts/agent-review-views.png', grid);
+ const poses = await call('scene_review', { ...settings,
+ shots: [{ label: 'Motion at 1.5', motionTime: 1.5 }, { label: 'Authored base' }] });
+ const poseGrid = image(poses);
+ await writeFile('artifacts/agent-review-poses.png', poseGrid);
+ assert.deepEqual(pixels(poseGrid, 'crop=384:384:384:24'), pixels(base), 'Omitted second shot must independently return the authored base');
+ assert.notDeepEqual(pixels(poseGrid, 'crop=384:384:0:24'), pixels(base));
+ assert.deepEqual(image(await call('scene_look', { sessionId, width: 384, height: 384 })), preview);
+ assert.deepEqual((await call('scene_export_recipe', { sessionId })).structuredContent.recipe, canonical);
+ for (const invalid of [
+ { ...settings, expectedRevision: 1, shots: [{}] },
+ { ...settings, shots: Array(5).fill({}) },
+ { ...settings, shots: [{ file: 'outside.png' }] },
+ { ...settings, shots: [{ motionTime: 0 }, { animation: { clip: 999, time: 0 } }] },
+ { ...settings, shots: [{}, { camera: { eye: [0, 0, 0], target: [0, 0, 0] } }] },
+ ]) {
+ await rejected(invalid);
+ assert.deepEqual(image(await call('scene_look', { sessionId, width: 384, height: 384 })), preview);
+ assert.deepEqual((await call('scene_export_recipe', { sessionId })).structuredContent.recipe, canonical);
+ }
+ const inspected = (await call('scene_inspect', { sessionId })).structuredContent;
+ assert.equal(inspected.revision, 0);
+ await call('scene_apply', { sessionId, expectedRevision: 0,
+ operations: [{ type: 'set-camera', eye: [0, 4, 7] }] });
+ await call('scene_restore', { sessionId, expectedRevision: 1, checkpointId: checkpoint.checkpointId });
+ assert.deepEqual(image(await call('scene_look', { sessionId, motionTime: 1.5, width: 384, height: 384 })), preview);
+ await call('scene_dispose', { sessionId });
+ const imported = (await call('scene_create_asset', { recipe: {
+ format: '67js.asset', schemaVersion: 1, assetId: clipAssetId,
+ camera: { eye: [1, 3, 7], target: [1, 3, 0], fov: 35, near: 0.1, far: 40 },
+ } })).structuredContent;
+ const clipSessionId = imported.sessionId;
+ const clipBase = image(await call('scene_look', { sessionId: clipSessionId, width: 384, height: 384 }));
+ await call('scene_apply', { sessionId: clipSessionId, expectedRevision: 0,
+ operations: [{ type: 'set-animation', clip: 0, time: 1.1 }] });
+ const clipPreview = image(await call('scene_look', { sessionId: clipSessionId, width: 384, height: 384 }));
+ assert.notDeepEqual(clipPreview, clipBase);
+ const clips = await call('scene_review', { sessionId: clipSessionId, expectedRevision: 1,
+ width: 384, height: 384, shots: [
+ { label: 'Clip at zero', animation: { clip: 0, time: 0 } },
+ { label: 'Authored clip at 1.1' },
+ ] });
+ const clipGrid = image(clips);
+ assert.deepEqual(pixels(clipGrid, 'crop=384:384:0:24'), pixels(clipBase));
+ assert.deepEqual(pixels(clipGrid, 'crop=384:384:384:24'), pixels(clipPreview));
+ assert.deepEqual(image(await call('scene_look', { sessionId: clipSessionId, width: 384, height: 384 })), clipPreview);
+ await writeFile('artifacts/agent-review-clips.png', clipGrid);
+ await call('scene_dispose', { sessionId: clipSessionId });
+ const report = { cli, tools: 18, singleShotPixelsExact: true, maximumShotsPixelsExact: true, sourceRevisionUnchanged: true, previewPngExact: true,
+ independentBasePixelsExact: true, checkpointRetained: true, invalidInputsPreserveSource: true,
+ importedClipPixelsExact: true, views: views.structuredContent, poses: poses.structuredContent,
+ clips: clips.structuredContent };
+ await writeFile('artifacts/mcp-agent-review-proof.json', JSON.stringify(report, null, 2));
+ console.log(JSON.stringify(report));
+} finally {
+ await client.close();
+ assert.equal(diagnostics.replace('67js preview resources closed.\n', '').trim(), '');
+}
diff --git a/scripts/smoke-mcp-package.mjs b/scripts/smoke-mcp-package.mjs
index 091c5ef4..5d027147 100644
--- a/scripts/smoke-mcp-package.mjs
+++ b/scripts/smoke-mcp-package.mjs
@@ -108,13 +108,13 @@ for (const era of ['modern', 'legacy']) {
const connectMs = performance.now() - start;
processId = transport.pid;
assert.equal(client.getServerVersion().version, metadata.version);
- assert.equal((await client.listTools()).tools.length, 17);
+ assert.equal((await client.listTools()).tools.length, 18);
const capabilities = (await call('scene_capabilities')).structuredContent;
assert.equal(capabilities.phase, 'idle');
assert.equal(capabilities.preview.maximumActiveScenes, 1);
assert.equal(capabilities.availableIn, metadata.version);
if (protocolOnly) {
- results.push({ era, tools: 17, connectMs, browserStarted: false });
+ results.push({ era, tools: 18, connectMs, browserStarted: false });
} else {
const created = (await call('scene_create', { recipe: createAgentPreviewFixture() })).structuredContent;
const before = await image(created.sessionId);
@@ -145,7 +145,7 @@ for (const era of ['modern', 'legacy']) {
assert.equal(exported.recipe.animation.time, 1.1);
await mkdir('artifacts', { recursive: true });
await writeFile(`artifacts/mcp-package-${era}.png`, bent);
- results.push({ era, tools: 17, connectMs, importedTexture: true, importedSkin: true, undoPngExact: true, reverseSeekPngExact: true });
+ results.push({ era, tools: 18, connectMs, importedTexture: true, importedSkin: true, undoPngExact: true, reverseSeekPngExact: true });
// Keep the final rig active to prove EOF closes its renderer and owned browser.
}
} finally {
diff --git a/scripts/smoke-mcp.mjs b/scripts/smoke-mcp.mjs
index 5f7b84ea..22d19ad8 100644
--- a/scripts/smoke-mcp.mjs
+++ b/scripts/smoke-mcp.mjs
@@ -53,7 +53,7 @@ try {
await client.connect(transport);
processId = transport.pid;
const listing = await client.listTools();
- assert.equal(listing.tools.length, 17);
+ assert.equal(listing.tools.length, 18);
const capabilities = (await call('scene_capabilities')).structuredContent;
assert.equal(capabilities.phase, 'idle');
const fixture = createAgentPreviewFixture();
diff --git a/skills/build-67js-scene/SKILL.md b/skills/build-67js-scene/SKILL.md
index ab8aea53..b8bbeb31 100644
--- a/skills/build-67js-scene/SKILL.md
+++ b/skills/build-67js-scene/SKILL.md
@@ -34,6 +34,7 @@ Use `simplify-code` and `engineering-workflows` for implementation.
- Agent render jobs use `docs/agent-render-jobs.md`. Check source versus published support, configure a private store and poll until terminal.
- Agent procedural animation uses `docs/agent-motion.md` from release `0.7.0`. Author recipe tracks, then seek through `sampleMotion` or MCP `motionTime`.
- Agent imported character motion uses `docs/agent-character-motion.md` from release `0.8.0`. Inspect source joints before authoring local tracks.
+- Agent comparisons use `scene_review` from release `0.9.0`. Read `docs/agent-review.md` for isolated views and independent pose samples.
- An image or video export uses `render-67js-media`.
Read [scene-contract.md](references/scene-contract.md) before creating parts or changing materials.
diff --git a/skills/build-67js-scene/references/scene-contract.md b/skills/build-67js-scene/references/scene-contract.md
index 391d5b97..86b29933 100644
--- a/skills/build-67js-scene/references/scene-contract.md
+++ b/skills/build-67js-scene/references/scene-contract.md
@@ -165,6 +165,9 @@ The server retains one renderer, bounds image dimensions and payloads, and close
Export the recipe before disposal. Release `0.6.0` includes bounded snapshot PNG, still and MP4 jobs documented in `docs/agent-render-jobs.md`.
Release `0.7.0` supports procedural `motionTime` preview seeks and `settings.motion.start` in jobs. Imported tracks retain their separate clip workflow.
+Release `0.9.0` adds `scene_review` for up to four labeled cameras or pose samples without editing the source.
+Read `docs/agent-review.md`. Each shot starts from the authored base pose and reports its camera, clocks and actual render resources.
+
For imported models, read `docs/agent-asset.md`, configure `--assets` with an absolute local GLB directory, then select a digest from `scene_asset_catalog`.
Use `scene_create_asset` with a `67js.asset` recipe. Supported texture maps, skinning, morphs and existing clips remain attached to decoded meshes.
Edit imported models through `set-root`, factor-only `set-material`, look commands and absolute `set-animation` sampling. Imported topology is immutable.
diff --git a/tests/agent-preview.test.js b/tests/agent-preview.test.js
index 14459803..84b40967 100644
--- a/tests/agent-preview.test.js
+++ b/tests/agent-preview.test.js
@@ -6,6 +6,9 @@ import { mat4 } from 'gl-matrix';
import { createAgentScene } from '../src/agent-scene.js';
import { applyProjection } from '../src/camera.js';
import { resolveAgentShadow } from '../src/agent-look.js';
+import { createAgentAssetScene } from '../src/agent-asset.js';
+import { parseGltf } from '../src/gltf.js';
+import { skinnedStripAsset } from './fixtures/skinned-strip.js';
const source = (await readFile(new URL('../scripts/agent-preview-browser.js', import.meta.url), 'utf8')).replace(/^import .+;\r?$/gm, '');
@@ -15,7 +18,14 @@ function previewHarness() {
let replacementError = false;
let replacementCount = 0;
let currentRenderer;
- const canvas = { width: 768, height: 512 };
+ let currentScene;
+ const renders = [];
+ const tiles = [];
+ const makeCanvas = () => ({ width: 768, height: 512,
+ replaceWith() {}, toDataURL: () => 'data:image/png;base64,cG5n',
+ getContext: kind => kind === '2d' ? { fillRect() {}, fillText() {},
+ drawImage: () => tiles.push(renders.at(-1)) } : { getExtension: () => null } });
+ const canvas = makeCanvas();
class FaultInjectedRenderer {
memoryPlan = { estimatedBytes: 1024 };
capabilities = { hdr: true, samples: 4 };
@@ -32,14 +42,29 @@ function previewHarness() {
if (replacementError) throw new Error('Injected replacement allocation failure');
replacementCount++;
}
- render() {}
+ render(camera) {
+ renders.push({ camera: JSON.parse(JSON.stringify(camera)),
+ parts: currentScene.parts.map(part => ({ matrix: Array.from(part.matrix),
+ joints: Array.from(part.skin?.jointMatrices ?? []) })) });
+ }
dispose() {}
}
const context = createContext({
window: {},
- document: { querySelector: () => canvas },
+ document: { querySelector: () => canvas, createElement: makeCanvas },
// The real browser bundles these functions in one realm. Bridge only the VM realm here.
- createAgentScene: input => createAgentScene(JSON.parse(JSON.stringify(input))),
+ createAgentScene: input => {
+ const scene = createAgentScene(JSON.parse(JSON.stringify(input)));
+ if (scene.parts.length) currentScene = scene;
+ return scene;
+ },
+ createAgentAssetScene: (asset, input) => {
+ currentScene = createAgentAssetScene(asset, JSON.parse(JSON.stringify(input)));
+ const scene = currentScene;
+ return new Proxy({}, { get: (target, field) => field === 'sampleFrame'
+ ? frame => scene.sampleFrame(JSON.parse(JSON.stringify(frame))) : scene[field] });
+ },
+ parseGltf, Uint8Array, atob,
applyProjection, mat4, resolveAgentShadow,
Renderer67: FaultInjectedRenderer,
});
@@ -52,6 +77,7 @@ function previewHarness() {
rejectReplacement: value => { replacementError = value; },
replacementCount: () => replacementCount,
disableHdr: () => { currentRenderer.capabilities.hdr = false; },
+ scene: () => currentScene, renders, tiles,
};
}
@@ -76,6 +102,92 @@ test('HDR fallback rejects enabling or restoring volume fog before canonical pub
assert.deepEqual(harness.preview.exportRecipe({ sessionId }), before);
});
+test('private review samples reset independently and camera overrides do not publish edits', () => {
+ const harness = previewHarness();
+ const input = recipe();
+ input.motion = { duration: 2, tracks: [{ kind: 'node', id: 'cube', property: 'translation',
+ keyframes: [{ time: 0, value: [0, 0, 0] }, { time: 2, value: [4, 0, 0] }] }] };
+ const { preview } = harness;
+ const sessionId = 'review';
+ preview.create({ recipe: input, sessionId, backend: 'cpu', memoryBudgetMiB: 64 });
+ const before = preview.exportRecipe({ sessionId });
+ preview.reviewBegin({ sessionId, width: 768, height: 408 });
+ const first = preview.reviewShot({ sessionId, index: 0, width: 384, height: 384, columns: 2,
+ shot: { label: 'Moving', motionTime: 1, rendererTime: 2, camera: { eye: [4, 3, 5] } } });
+ const second = preview.reviewShot({ sessionId, index: 1, width: 384, height: 384, columns: 2,
+ shot: { label: 'Base', motionTime: null, rendererTime: 0 } });
+ assert.equal(harness.tiles[0].parts[0].matrix[12], 2);
+ assert.equal(harness.tiles[1].parts[0].matrix[12], 0);
+ assert.deepEqual(Array.from(first.camera.eye), [4, 3, 5]);
+ assert.deepEqual(second.camera, before.recipe.camera);
+ assert.equal(second.motionTime, null);
+ assert.deepEqual(preview.exportRecipe({ sessionId }), before);
+ assert.equal(preview.reviewResult({ sessionId }).data, 'cG5n');
+});
+
+test('source suspend and resume preserve transient motion pose and checkpoints', () => {
+ const harness = previewHarness();
+ const input = recipe();
+ input.motion = { duration: 2, tracks: [{ kind: 'node', id: 'cube', property: 'translation',
+ keyframes: [{ time: 0, value: [0, 0, 0] }, { time: 2, value: [4, 0, 0] }] }] };
+ const { preview } = harness;
+ const sessionId = 'source';
+ preview.create({ recipe: input, sessionId, backend: 'cpu', memoryBudgetMiB: 64 });
+ preview.checkpoint({ sessionId, checkpointId: 'saved' });
+ preview.frame({ sessionId, motionTime: 1.5 });
+ const before = preview.exportRecipe({ sessionId });
+ preview.suspend({ sessionId });
+ preview.resume({ sessionId });
+ assert.equal(harness.scene().motionTime, 1.5);
+ assert.equal(harness.renders.at(-1).parts[0].matrix[12], 3);
+ assert.deepEqual(preview.exportRecipe({ sessionId }), before);
+ assert.equal(preview.restore({ sessionId, checkpointId: 'saved', expectedRevision: 0 }).revision, 1);
+});
+
+test('asset review samples imported clips and motion atomically and resets to authored clip pose', async () => {
+ const harness = previewHarness();
+ const sessionId = 'asset-review';
+ const input = { format: '67js.asset', schemaVersion: 1, assetId: 'ab'.repeat(32),
+ animation: { clip: 0, time: 0.25 }, motion: { duration: 2, tracks: [
+ { kind: 'node', id: 'node-0', property: 'translation', keyframes: [
+ { time: 0, value: [0, 0, 0] }, { time: 2, value: [2, 0, 0] } ] },
+ ] } };
+ await harness.preview.createAsset({ sessionId, recipe: input,
+ data: Buffer.from(skinnedStripAsset()).toString('base64'), backend: 'cpu', memoryBudgetMiB: 64 });
+ const before = harness.preview.exportRecipe({ sessionId });
+ harness.preview.reviewBegin({ sessionId, width: 768, height: 408 });
+ const shot = (index, animation, motionTime) => harness.preview.reviewShot({ sessionId, index,
+ width: 384, height: 384, columns: 2, shot: { label: 'Asset', rendererTime: 0, motionTime,
+ ...(animation === undefined ? {} : { animation }) } });
+ shot(0, { clip: 0, time: 1.5 }, 1);
+ const posed = harness.renders.at(-1).parts;
+ const reset = shot(1, undefined, null);
+ assert.notDeepEqual(harness.renders.at(-1).parts, posed);
+ harness.scene().sampleFrame({ animation: input.animation, motionTime: null });
+ assert.deepEqual(harness.renders.at(-1).parts, harness.scene().parts.map(part => ({
+ matrix: Array.from(part.matrix), joints: Array.from(part.skin?.jointMatrices ?? []) })));
+ assert.deepEqual(JSON.parse(JSON.stringify(reset.animation)), input.animation);
+ assert.deepEqual(harness.preview.exportRecipe({ sessionId }), before);
+ const poseBeforeFailure = harness.renders.at(-1).parts;
+ assert.throws(() => shot(1, { clip: 999, time: 0 }, 1), /clip/i);
+ assert.deepEqual(harness.scene().parts.map(part => ({ matrix: Array.from(part.matrix),
+ joints: Array.from(part.skin?.jointMatrices ?? []) })), poseBeforeFailure);
+});
+
+test('review private cameras reject Float32 overflow and preserve canonical revision after a partial grid', () => {
+ const harness = previewHarness();
+ const sessionId = 'invalid-review-camera';
+ harness.preview.create({ recipe: recipe(), sessionId, backend: 'cpu', memoryBudgetMiB: 64 });
+ const before = harness.preview.exportRecipe({ sessionId });
+ harness.preview.reviewBegin({ sessionId, width: 768, height: 408 });
+ const shot = camera => harness.preview.reviewShot({ sessionId, index: 0,
+ width: 384, height: 384, columns: 2, shot: { label: 'Camera', motionTime: null, rendererTime: 0, camera } });
+ shot({ eye: [4, 3, 5] });
+ assert.throws(() => shot({ fov: 1e-36 }), /aspect ratios/);
+ assert.equal(harness.tiles.length, 1);
+ assert.deepEqual(harness.preview.exportRecipe({ sessionId }), before);
+});
+
function recipe() {
return { format: '67js.scene', schemaVersion: 1,
geometries: [{ id: 'cube', type: 'box', bevel: 0 }],
diff --git a/tests/agent-review.test.js b/tests/agent-review.test.js
new file mode 100644
index 00000000..f15d53aa
--- /dev/null
+++ b/tests/agent-review.test.js
@@ -0,0 +1,41 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { normalizeReview, REVIEW_LIMITS } from '../scripts/agent-review.mjs';
+
+const request = () => ({ sessionId: 'scene', expectedRevision: 0, shots: [{}] });
+
+test('review independently defaults shot clocks and bounds its labeled grid', () => {
+ const input = { ...request(), width: 480, height: 480,
+ shots: [{ motionTime: 1, rendererTime: 2 }, {}, {}, {}] };
+ const normalized = normalizeReview(input);
+ assert.equal(normalized.gridWidth, REVIEW_LIMITS.maximumGridWidth);
+ assert.equal(normalized.gridHeight, REVIEW_LIMITS.maximumGridHeight);
+ assert.deepEqual(normalized.shots[1], { label: 'View 2', motionTime: null, rendererTime: 0 });
+ assert.equal(normalizeReview(request()).gridWidth, 384);
+ assert.equal(normalizeReview(request()).gridHeight, 408);
+});
+
+test('review rejects unknown fields, nonfinite values and unbounded inputs before allocation', () => {
+ for (const input of [
+ { ...request(), path: 'render.png' }, { ...request(), shots: [] }, { ...request(), shots: Array(5).fill({}) },
+ { ...request(), width: 481 }, { ...request(), height: 63 }, { ...request(), expectedRevision: NaN },
+ { ...request(), width: null }, { ...request(), shots: [{ rendererTime: null }] },
+ { ...request(), shots: [{ code: 'alert(1)' }] }, { ...request(), shots: [{ label: 'x'.repeat(49) }] },
+ { ...request(), shots: [{ rendererTime: Infinity }] }, { ...request(), shots: [{ motionTime: NaN }] },
+ { ...request(), shots: [{ animation: { clip: 0, time: 0, url: 'https://example.com' } }] },
+ { ...request(), shots: [{ animation: { clip: 0, time: Infinity } }] },
+ { ...request(), shots: [{ camera: { projection: 'orthographic' } }] },
+ { ...request(), shots: [{ camera: { eye: [Infinity, 0, 0] } }] },
+ { ...request(), shots: [{ camera: { fov: 1e100 } }] },
+ { ...request(), shots: [{ camera: { fov: NaN } }] },
+ ]) assert.throws(() => normalizeReview(input));
+});
+
+test('review detaches caller camera and imported animation records', () => {
+ const input = { ...request(), shots: [{ camera: { eye: [4, 2, 1] }, animation: { clip: 0, time: 1 } }] };
+ const normalized = normalizeReview(input);
+ input.shots[0].camera.eye[0] = 99;
+ input.shots[0].animation.time = 99;
+ assert.equal(normalized.shots[0].camera.eye[0], 4);
+ assert.equal(normalized.shots[0].animation.time, 1);
+});
diff --git a/tests/agent-runtime.test.js b/tests/agent-runtime.test.js
index 0a6a0d2e..dd851db6 100644
--- a/tests/agent-runtime.test.js
+++ b/tests/agent-runtime.test.js
@@ -1,6 +1,12 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { createAgentRuntime } from '../scripts/agent-runtime.mjs';
+import { readFile } from 'node:fs/promises';
+import { createServer } from 'node:http';
+import { randomUUID } from 'node:crypto';
+import { createContext, Script } from 'node:vm';
+import { createAgentScene, AGENT_SCENE_CAPABILITIES } from '../src/agent-scene.js';
+import { normalizeReview, REVIEW_LIMITS } from '../scripts/agent-review.mjs';
test('runtime reports real scene capabilities without launching a browser and closes idempotently', async () => {
const runtime = createAgentRuntime({ backend: 'cpu', memory: 64 });
@@ -10,6 +16,9 @@ test('runtime reports real scene capabilities without launching a browser and cl
assert.equal(capabilities.preview.maximumActiveScenes, 1);
assert.equal(capabilities.preview.memoryBudgetMiB, 64);
assert.equal(capabilities.preview.backend, 'cpu');
+ assert.equal(capabilities.review.maximumShots, 4);
+ assert.equal(capabilities.review.maximumGridHeight, 1008);
+ assert.equal(capabilities.review.maximumPendingFrames, 1);
assert.equal(capabilities.sceneLimits.maxGeometryBytes, 32 * 1024 * 1024);
await runtime.close();
await runtime.close();
@@ -17,6 +26,223 @@ test('runtime reports real scene capabilities without launching a browser and cl
await assert.rejects(runtime.create({ recipe: {} }), /closed/);
});
+async function reviewRuntimeHarness({ failShot, blockShot = false, oversize = false, deadlineMs,
+ failDispose = false, heapSize = 1024, stallPrivatePage = false, resumeDelayMs = 0 } = {}) {
+ const events = [];
+ let privatePage;
+ let sourceRevision = 0;
+ let resolveShotStarted;
+ const shotStarted = new Promise(resolve => { resolveShotStarted = resolve; });
+ let resolveAcquisitionStarted;
+ const acquisitionStarted = new Promise(resolve => { resolveAcquisitionStarted = resolve; });
+ let resolvePrivatePage;
+ const acquiredPage = new Promise(resolve => { resolvePrivatePage = () => resolve(privatePage = new FakePage(true)); });
+ const recipe = { format: '67js.scene', schemaVersion: 1, geometries: [], materials: [], nodes: [] };
+ class FakePage {
+ constructor(privateTarget) { this.privateTarget = privateTarget; this.closed = false; }
+ route() {}
+ setDefaultTimeout() {}
+ goto() {}
+ waitForFunction() {}
+ isClosed() { return this.closed; }
+ context() { return { newCDPSession: async () => ({
+ send: async () => ({ usedSize: heapSize }), detach: async () => { events.push('detach'); },
+ }) }; }
+ async evaluate(callback, { method, input }) {
+ events.push(`${this.privateTarget ? 'private' : 'source'}:${method}`);
+ if (method === 'create') return { sessionId: input.sessionId, revision: 0 };
+ if (method === 'snapshot') {
+ if (input.expectedRevision !== sourceRevision) throw new Error('Stale revision for render snapshot.');
+ return { sourceRevision, recipe };
+ }
+ if (method === 'reviewShot') {
+ resolveShotStarted();
+ if (blockShot) return new Promise((resolve, reject) => { this.rejectShot = reject; });
+ if (input.index === failShot) throw new Error('Injected partial shot failure');
+ return { label: input.shot.label, motionTime: input.shot.motionTime,
+ rendererTime: input.shot.rendererTime, graphics: 'SwiftShader', width: 384, height: 384 };
+ }
+ if (method === 'reviewResult') return { mimeType: 'image/png',
+ data: Buffer.alloc(oversize ? 1024 * 1024 + 1 : 16).toString('base64') };
+ if (method === 'dispose' && failDispose) throw new Error('Injected disposal failure');
+ if (method === 'resume' && resumeDelayMs) await new Promise(resolve => setTimeout(resolve, resumeDelayMs));
+ if (method === 'apply') { sourceRevision++; return { revision: sourceRevision }; }
+ return {};
+ }
+ async close() {
+ if (this.closed) return;
+ this.closed = true;
+ events.push(`${this.privateTarget ? 'private' : 'source'}:close`);
+ this.rejectShot?.(new Error('Review page closed'));
+ }
+ }
+ const sourcePage = new FakePage(false);
+ let pageCount = 0;
+ const browser = { isConnected: () => true,
+ newPage: async () => {
+ if (++pageCount === 1) return sourcePage;
+ resolveAcquisitionStarted();
+ return stallPrivatePage ? acquiredPage : (privatePage = new FakePage(true));
+ },
+ close: async () => { await privatePage?.close(); await sourcePage.close(); events.push('browser:close'); },
+ };
+ let source = (await readFile(new URL('../scripts/agent-runtime.mjs', import.meta.url), 'utf8'))
+ .replace(/^import .+;\r?$/gm, '')
+ .replace('export function createAgentRuntime', 'function createAgentRuntime')
+ .replaceAll('import.meta.url', JSON.stringify(import.meta.url))
+ .replace("import('playwright-core')", 'Promise.resolve({ chromium: globalThis.chromium })');
+ if (deadlineMs) source = source.replace('const EVALUATION_TIMEOUT_MS = 30000;', `const EVALUATION_TIMEOUT_MS = ${deadlineMs};`);
+ const context = createContext({ createServer, randomUUID, existsSync: () => true,
+ readFile: async () => '', packageMetadata: { version: 'test' },
+ createAgentScene: input => createAgentScene(JSON.parse(JSON.stringify(input))),
+ AGENT_SCENE_CAPABILITIES, normalizeReview, REVIEW_LIMITS,
+ chromium: { launch: async () => browser }, URL, Buffer, process, performance, setTimeout, clearTimeout,
+ });
+ new Script(`${source}\nglobalThis.runtime = createAgentRuntime({ backend: 'cpu' });`).runInContext(context);
+ const runtime = context.runtime;
+ const created = await runtime.create({ recipe });
+ return { runtime, sessionId: created.sessionId, events, shotStarted, acquisitionStarted, resolvePrivatePage };
+}
+
+function boundedResult(promise) {
+ let timer;
+ return Promise.race([promise.then(() => 'settled', () => 'settled'),
+ new Promise(resolve => { timer = setTimeout(() => resolve('stalled'), 150); }),
+ ]).finally(() => clearTimeout(timer));
+}
+
+test('review deadline rejects stalled page acquisition and disposes a late page', async () => {
+ const { runtime, sessionId, events, acquisitionStarted, resolvePrivatePage } = await reviewRuntimeHarness({
+ stallPrivatePage: true, deadlineMs: 40,
+ });
+ const pending = runtime.review({ sessionId, expectedRevision: 0, shots: [{}] });
+ try {
+ await acquisitionStarted;
+ assert.equal(await boundedResult(pending), 'settled', 'deadline must reject without waiting for newPage');
+ await assert.rejects(pending, /deadline/);
+ assert.equal((await runtime.capabilities()).phase, 'ready');
+ resolvePrivatePage();
+ await new Promise(resolve => setImmediate(resolve));
+ assert.ok(events.includes('private:close'));
+ assert.ok(!events.includes('private:create'));
+ assert.equal((await runtime.apply({ sessionId })).revision, 1);
+ } finally {
+ resolvePrivatePage();
+ await pending.catch(() => {});
+ await runtime.close();
+ }
+});
+
+test('close interrupts stalled page acquisition and late resolution cannot resurrect the runtime', async () => {
+ const { runtime, sessionId, events, acquisitionStarted, resolvePrivatePage } = await reviewRuntimeHarness({ stallPrivatePage: true });
+ const pending = runtime.review({ sessionId, expectedRevision: 0, shots: [{}] });
+ pending.catch(() => {});
+ await acquisitionStarted;
+ const closing = runtime.close();
+ try {
+ assert.equal(await boundedResult(closing), 'settled', 'close must not wait for newPage');
+ await closing;
+ await assert.rejects(pending, /closing|closed/);
+ assert.ok(events.includes('browser:close'));
+ resolvePrivatePage();
+ await new Promise(resolve => setImmediate(resolve));
+ assert.ok(events.includes('private:close'));
+ assert.ok(!events.includes('private:create'));
+ assert.ok(!events.includes('source:resume'));
+ assert.equal((await runtime.capabilities()).phase, 'closed');
+ } finally {
+ resolvePrivatePage();
+ await pending.catch(() => {});
+ await closing;
+ }
+});
+
+test('review queue releases private renderer before source resume, including partial and size failures', async () => {
+ for (const options of [{}, { failShot: 1 }, { oversize: true }, { heapSize: 256 * 1024 ** 2 + 1 }]) {
+ const { runtime, sessionId, events } = await reviewRuntimeHarness(options);
+ try {
+ const pending = runtime.review({ sessionId, expectedRevision: 0, shots: [{ motionTime: 1 }, {}] });
+ if (options.failShot !== undefined || options.oversize || options.heapSize) await assert.rejects(pending, /partial shot|1 MiB|heap guard/);
+ else {
+ const result = await pending;
+ assert.equal(result.metadata.sourceRevision, 0);
+ assert.equal(result.metadata.shots[1].motionTime, null);
+ assert.equal(result.metadata.maximumPendingFrames, 1);
+ }
+ assert.ok(events.indexOf('private:dispose') < events.indexOf('private:close'));
+ assert.ok(events.indexOf('private:close') < events.indexOf('source:resume'));
+ assert.equal(events.filter(event => event === 'source:resume').length, 1);
+ assert.equal((await runtime.apply({ sessionId })).revision, 1);
+ } finally { await runtime.close(); }
+ }
+});
+
+test('queued review detaches its request before a caller can mutate shot clocks', async () => {
+ const { runtime, sessionId } = await reviewRuntimeHarness();
+ try {
+ const input = { sessionId, expectedRevision: 0, shots: [{ motionTime: 1 }] };
+ const pending = runtime.review(input);
+ input.shots[0].motionTime = 99;
+ input.shots.push({ motionTime: 88 });
+ const result = await pending;
+ assert.equal(result.metadata.shots.length, 1);
+ assert.equal(result.metadata.shots[0].motionTime, 1);
+ } finally { await runtime.close(); }
+});
+
+test('successful review elapsed time includes source renderer recovery', async () => {
+ const { runtime, sessionId } = await reviewRuntimeHarness({ resumeDelayMs: 30 });
+ try {
+ const result = await runtime.review({ sessionId, expectedRevision: 0, shots: [{}] });
+ assert.ok(result.metadata.elapsedSeconds >= 0.02, 'elapsed must include the delayed source resume');
+ assert.equal((await runtime.capabilities()).phase, 'ready');
+ } finally { await runtime.close(); }
+});
+
+test('total review deadline closes private page and restores the usable source', async () => {
+ const { runtime, sessionId, events } = await reviewRuntimeHarness({ blockShot: true, deadlineMs: 40 });
+ try {
+ await assert.rejects(runtime.review({ sessionId, expectedRevision: 0, shots: [{}] }), /total 30 second deadline/);
+ assert.ok(events.includes('private:close'));
+ assert.ok(events.includes('source:resume'));
+ assert.equal((await runtime.capabilities()).phase, 'ready');
+ assert.equal((await runtime.apply({ sessionId })).revision, 1);
+ } finally { await runtime.close(); }
+});
+
+test('private disposal failure still closes its page before restoring source', async () => {
+ const { runtime, sessionId, events } = await reviewRuntimeHarness({ failDispose: true });
+ try {
+ await assert.rejects(runtime.review({ sessionId, expectedRevision: 0, shots: [{}] }), /disposal failure/);
+ assert.ok(events.indexOf('private:close') < events.indexOf('source:resume'));
+ assert.equal((await runtime.capabilities()).phase, 'ready');
+ } finally { await runtime.close(); }
+});
+
+test('review stale revisions and strict runtime fields reject before leasing source', async () => {
+ const { runtime, sessionId, events } = await reviewRuntimeHarness();
+ try {
+ await assert.rejects(runtime.review({ sessionId, expectedRevision: 1, shots: [{}] }), /Stale/);
+ await assert.rejects(runtime.review({ sessionId, expectedRevision: 0, shots: [{ url: 'https://example.com' }] }), /unknown/i);
+ assert.ok(!events.includes('source:suspend'));
+ assert.equal((await runtime.apply({ sessionId })).revision, 1);
+ } finally { await runtime.close(); }
+});
+
+test('runtime close promptly aborts a pending private review and skips source resume', async () => {
+ const { runtime, sessionId, events, shotStarted } = await reviewRuntimeHarness({ blockShot: true });
+ const pending = runtime.review({ sessionId, expectedRevision: 0, shots: [{}] });
+ const rejected = assert.rejects(pending, /closed/);
+ await shotStarted;
+ assert.equal((await runtime.capabilities()).phase, 'reviewing');
+ await runtime.close();
+ await rejected;
+ assert.ok(events.includes('private:close'));
+ assert.ok(events.includes('browser:close'));
+ assert.ok(!events.includes('source:resume'));
+ assert.equal((await runtime.capabilities()).phase, 'closed');
+});
+
test('invalid preview configuration rejects before any browser or renderer allocation', () => {
assert.throws(() => createAgentRuntime({ backend: 'fake' }), /backend/);
for (const memory of [0, 31, 257, 64.5, NaN]) {
diff --git a/tests/mcp-tools.test.js b/tests/mcp-tools.test.js
index d3f08310..64fd616d 100644
--- a/tests/mcp-tools.test.js
+++ b/tests/mcp-tools.test.js
@@ -51,6 +51,12 @@ async function connect(context) {
return { data: png, mimeType: 'image/png', metadata: { sessionId, revision: scene.revision,
motionTime: scene.motionTime, width, height, backend: 'fake' } };
},
+ async review({ expectedRevision, width, height, shots }) {
+ calls++;
+ assert.equal(expectedRevision, scene.revision);
+ return { data: png, mimeType: 'image/png', metadata: { sessionId,
+ sourceRevision: scene.revision, width, height, shots, backend: 'fake' } };
+ },
async checkpoint() {
const checkpointId = randomUUID();
checkpoints.set(checkpointId, scene.checkpoint());
@@ -100,7 +106,7 @@ test('SDK advertises the complete strict JSON contract and truthful annotations'
const { tools } = await client.listTools();
assert.deepEqual(tools.map(tool => tool.name).sort(), [
'scene_apply', 'scene_asset_catalog', 'scene_capabilities', 'scene_checkpoint', 'scene_create', 'scene_create_asset', 'scene_dispose',
- 'scene_export_recipe', 'scene_inspect', 'scene_look', 'scene_release_checkpoint', 'scene_restore',
+ 'scene_export_recipe', 'scene_inspect', 'scene_look', 'scene_review', 'scene_release_checkpoint', 'scene_restore',
'scene_render_cancel', 'scene_render_release', 'scene_render_result', 'scene_render_status', 'scene_render_submit',
].sort());
for (const tool of tools) {
@@ -132,6 +138,33 @@ test('SDK advertises the complete strict JSON contract and truthful annotations'
assert.ok(look.inputSchema.properties.motionTime);
});
+test('review SDK exposes one image and rejects unknown or unbounded shot fields before dispatch', async context => {
+ const { client, sessionId, calls } = await connect(context);
+ await client.callTool({ name: 'scene_create', arguments: { recipe: recipe() } });
+ const { tools } = await client.listTools();
+ const tool = tools.find(tool => tool.name === 'scene_review');
+ assert.equal(tools.length, 18);
+ assert.equal(tool.annotations.readOnlyHint, true);
+ assert.equal(tool.inputSchema.properties.shots.maxItems, 4);
+ assert.equal(tool.inputSchema.properties.shots.items.additionalProperties, false);
+ assert.equal(tool.inputSchema.properties.shots.items.properties.camera.additionalProperties, false);
+ const input = { sessionId, expectedRevision: 0, shots: [{ label: 'Front', camera: { eye: [4, 2, 1] } }, {}] };
+ const result = await client.callTool({ name: 'scene_review', arguments: input });
+ assert.equal(result.content.filter(block => block.type === 'image').length, 1);
+ assert.equal(result.structuredContent.sourceRevision, 0);
+ assert.equal(result.structuredContent.width, 384);
+ assert.ok(!JSON.stringify(result.structuredContent).includes(png));
+ const before = calls();
+ for (const invalid of [
+ { ...input, width: 481 }, { ...input, shots: [] }, { ...input, shots: Array(5).fill({}) },
+ { ...input, code: 'console.log(1)' }, { ...input, shots: [{ camera: { projection: 'orthographic' } }] },
+ { ...input, shots: [{ animation: { clip: 0, time: 0, url: 'https://example.com' } }] },
+ { ...input, shots: [{ label: 'x'.repeat(49) }] }, { ...input, shots: [{ motionTime: -1 }] },
+ { ...input, shots: [{ rendererTime: 3601 }] }, { ...input, expectedRevision: -1 },
+ ]) await rejected(client, 'scene_review', invalid);
+ assert.equal(calls(), before);
+});
+
test('SDK rejects unknown fields, missing revisions, invalid vectors and oversized inputs before runtime dispatch', async context => {
const boundary = await connect(context);
const { client, sessionId } = boundary;