A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(editor): an open asset document can be saved, and opening one waits for it
yhhc0f6704cfcc3
diff --git a/desktop/scripts/editor-checks/material-authoring.mjs b/desktop/scripts/editor-checks/material-authoring.mjsnew file mode 100644index 000000000..e63e93f8b--- /dev/null+++ b/desktop/scripts/editor-checks/material-authoring.mjs@@ -0,0 +1,112 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file material-authoring — a driver can make a shader, not only look at one.+ *+ * Three separate holes made this one path unwalkable, and each looked fine on+ * its own. `.esmatgraph` was typed only by the renderer's Content-Browser table,+ * so the create door — which derives an extension from the SHARED meta table —+ * answered "unknown asset type" for the one type it was being asked for. Opening+ * an asset editor did not wait for the file to be read, so the very next call+ * could be told nothing was open. And there was no save for these documents at+ * all: `project.save` routes by whichever dock panel the user last clicked, so+ * driven from outside it wrote the scene, or nothing.+ *+ * A material graph is the case that proves all three, because its file is not+ * the whole asset: saving it must also recompile the sibling `.esshader` that+ * every material on it reads. A graph that saves without that is an edit that+ * appears to land and still renders the old thing — which no unit test on the+ * document can see, since the compile happens on the way to disk.+ */+import path from 'node:path';+import { cp } from 'node:fs/promises';+import { makeProject, checker, DESKTOP } from '../lib/editorDriver.mjs';++const EXAMPLE = path.resolve(DESKTOP, '..', 'examples', 'sprite-rendering');++const SCENE = JSON.stringify({+ version: '1.0', name: 'Main',+ entities: [+ {+ id: 0, name: 'Camera', parent: null, children: [], visible: true,+ components: [+ { type: 'Transform', data: { position: { x: 0, y: 0, z: 10 } } },+ { type: 'Camera', data: { projectionType: 1, orthoSize: 300, isActive: true, priority: 0 } },+ ],+ },+ ],+}, null, 1);++/** A texture sampled through a colour param — small, and it compiles. */+const GRAPH = JSON.stringify({+ name: 'Fire',+ output: 'out',+ nodes: [+ { id: 'tint', type: 'constColor', x: 60, y: 60, params: { name: 'u_tint', value: [1, 0, 0, 1] } },+ { id: 'tex', type: 'textureSample', x: 60, y: 200, params: { name: 'u_albedo', default: 'white' } },+ { id: 'mul', type: 'multiply', x: 260, y: 130, inputs: { a: 'tex', b: 'tint' } },+ { id: 'out', type: 'output', x: 460, y: 130, inputs: { color: 'mul' } },+ ],+}, null, 2);++export const name = 'material-authoring';+export const describes = 'a driver creates a material graph, edits it, and saves BOTH it and its shader';++export async function run(ed) {+ const root = await makeProject({ 'assets/scenes/main.esscene': SCENE });+ await cp(path.join(EXAMPLE, 'project.esproject'), path.join(root, 'project.esproject'));+ await cp(path.join(EXAMPLE, 'src'), path.join(root, 'src'), { recursive: true });+ const check = checker();++ await ed.open(root, 'assets/scenes/main.esscene');++ // A BARE name: the extension comes from the type, which is the half that was+ // missing. Passing "Fire.esmatgraph" would have worked all along.+ const graphPath = await ed.json('create_asset', {+ destDir: 'assets/fx', baseName: 'Fire', content: GRAPH, type: 'materialgraph',+ }, 60000);+ if (!check(graphPath === 'assets/fx/Fire.esmatgraph', `create_asset named it ${graphPath}`)) {+ return check.failures;+ }++ await ed.call('open_asset', { path: graphPath }, 60000);+ // Straight after the open, with no settle: the point is that open_asset does+ // not return until the document is bound.+ const doc = await ed.json('get_asset_document', {});+ if (!check(doc?.asset?.output === 'out', `the graph did not open as a document: ${JSON.stringify(doc)?.slice(0, 200)}`)) {+ return check.failures;+ }+ check(doc.docId === 'materialgraph', `it opened as "${doc.docId}"`);++ // Rename the colour param. It is a compiled-in name, so the shader beside the+ // graph either follows or it does not — no interpretation needed.+ await ed.call('edit_asset_document', {+ changes: [{ path: 'nodes.0.params.name', value: 'u_flame' }],+ label: 'Rename param',+ });+ const saved = await ed.json('save_asset_document', {});+ check(saved?.saved === true, `save_asset_document reported ${JSON.stringify(saved)}`);++ const onDisk = await ed.json('read_project_file', { path: graphPath });+ check(String(onDisk).includes('u_flame'), 'the graph file still holds the old param name');++ const shaderPath = 'assets/fx/Fire.esshader';+ let shader = null;+ try {+ shader = await ed.json('read_project_file', { path: shaderPath });+ } catch (err) {+ check(false, `${shaderPath} was never written — saving a graph must compile it: ${err.message}`);+ }+ if (shader != null) {+ check(String(shader).includes('u_flame'), `${shaderPath} does not mention u_flame — it was not recompiled`);+ check(!String(shader).includes('u_tint'), `${shaderPath} still carries the pre-edit param name`);+ }++ // The shader is an asset like any other: a material can name it, which is the+ // whole point of the graph having a sibling.+ const assets = await ed.json('list_assets', { match: 'Fire' });+ const paths = (assets?.assets ?? []).map((a) => a.path);+ check(paths.includes(graphPath), `the graph is not in the registry (${paths.join(', ')})`);++ return check.failures;+}diff --git a/desktop/shared/toolCatalog.mjs b/desktop/shared/toolCatalog.mjsindex 06ab6801f..1e771d2d5 100644--- a/desktop/shared/toolCatalog.mjs+++ b/desktop/shared/toolCatalog.mjs@@ -306,7 +306,8 @@ export const TOOLS = [}, ['kind', 'name']),js: (i) => `window.estella.project.createScript(${JSON.stringify(i.kind)}, ${JSON.stringify(i.name)}, ${JSON.stringify(i.dir ?? undefined)})` },{ name: 'create_asset', effect: 'irreversible',- description: 'Create a text asset file under a project-relative directory with the given content. `type` is the meta vocabulary: scene, prefab, shader, material, animclip (.esanim), animation (.estimeline), tileset, statemachine (.esfsm), behaviortree (.esbt), locale, inputmap, tilemap (.tmj). A bare baseName gets the type\'s canonical extension appended. Returns the project-relative path, immediately referenceable (the registry refresh happens before this resolves).',+ description: 'Create a text asset file under a project-relative directory with the given content. `type` is the meta vocabulary: scene, prefab, shader (.esshader), material (.esmaterial), materialgraph (.esmatgraph), animclip (.esanim), animation (.estimeline), tileset, statemachine (.esfsm), behaviortree (.esbt), locale, inputmap, tilemap (.tmj). A bare baseName gets the type\'s canonical extension appended. Returns the project-relative path, immediately referenceable (the registry refresh happens before this resolves). '+ + 'A material graph is the ONE type whose file is not the whole asset: it compiles to a sibling `.esshader`, which is written by save_asset_document — so create it, open_asset it, and save it, rather than leaving a graph with no shader beside it.',schema: obj({destDir: { type: 'string' }, baseName: { type: 'string' },content: { type: 'string' }, type: { type: 'string' },@@ -343,10 +344,10 @@ export const TOOLS = [: null),method: 'applyOps', args: (i) => [i.ops, i.label], root: 'editor' },// — The open asset editors. One set of doors for all eight kinds, because they- // share AssetDocument: `open_asset` puts one on screen, these read and write- // it. A clip, a timeline, a tileset and a material graph differ in what they- // HOLD, not in how they are edited, so a tool set per kind would be the same- // three verbs written eight times and drifting apart. —+ // share AssetDocument: `open_asset` puts one on screen, these read, write and+ // save it. A clip, a timeline, a tileset and a material graph differ in what+ // they HOLD, not in how they are edited, so a tool set per kind would be the+ // same three verbs written eight times and drifting apart. —{ name: 'list_asset_documents', effect: 'read',description: 'Which asset editors are open right now (animation clip, timeline, tileset, material, material graph, animator/state/behaviour graph), with their file path and whether they have unsaved edits. Use it to learn the `docId` the other two tools take when more than one is open.',schema: obj({}),@@ -367,6 +368,13 @@ export const TOOLS = [}, ['changes']),js: (i) => `window.__estellaEditor.editAssetDocument(${JSON.stringify(i.changes)}, ${JSON.stringify(i.docId ?? null)} ?? undefined, ${JSON.stringify(i.label ?? null)} ?? undefined)`,root: 'editor' },+ { name: 'save_asset_document', effect: 'irreversible',+ description: 'Write an open asset editor\'s document to its file — the save its own panel performs, which for a MATERIAL GRAPH also recompiles the sibling `.esshader` every material on it reads. '+ + 'This is the save for these files: `save_scene` writes the scene, and writing the bytes yourself with write_project_file skips the serializer (and, for a graph, leaves the shader stale — the edit appears to save and still renders the old thing). '+ + 'Omit `docId` when only one is open. Returns { saved } — false means it was already clean, not that it failed.',+ schema: obj({ docId: { type: 'string' } }),+ js: (i) => `window.__estellaEditor.saveAssetDocument(${JSON.stringify(i.docId ?? null)} ?? undefined)`,+ root: 'editor' },// — Tilemaps. Painting is not a field write: a cell is addressed by grid// coordinate, and a stroke is hundreds of them in one undo step. —diff --git a/desktop/src/document/DirtyRegistry.ts b/desktop/src/document/DirtyRegistry.tsindex cf83f09af..8f040944a 100644--- a/desktop/src/document/DirtyRegistry.ts+++ b/desktop/src/document/DirtyRegistry.ts@@ -56,6 +56,14 @@ class DirtyRegistryImpl {};}+ /** Whether a document registered under this id — i.e. whether {@link saveDoc}+ * can persist it at all. `saveDoc` answers false both for "clean" and for+ * "never registered", which a driver asked to SAVE something cannot tell+ * apart; this is how a caller turns the second one into an error. */+ knows(id: string): boolean {+ return this.docs.has(id);+ }+/** True when ANY registered document has unsaved changes. */isDirty(): boolean {for (const { doc } of this.docs.values()) if (doc.isDirty()) return true;diff --git a/desktop/src/document/assetDocumentOps.ts b/desktop/src/document/assetDocumentOps.tsindex d19c24a57..51a014dc1 100644--- a/desktop/src/document/assetDocumentOps.ts+++ b/desktop/src/document/assetDocumentOps.ts@@ -17,6 +17,7 @@* is what keeps a ninth editor from needing a ninth tool.*/import { AssetDocument } from './AssetDocument';+import { DirtyRegistry } from './DirtyRegistry';/** One open editor document, as the agent sees it in a listing. */export interface AssetDocumentInfo {@@ -126,3 +127,39 @@ export function editAssetDocument(});return { docId: doc.docId, applied: changes.length };}++/**+ * Persist an open asset document — the save its own panel performs.+ *+ * Not a JSON write of what {@link readAssetDocument} returns: a tileset and a+ * timeline have their own serializers, and a material graph COMPILES a sibling+ * `.esshader` that every material on it reads. Writing the file directly would+ * leave that shader stale — an edit that saves, reloads, and still renders the+ * old thing. So the one save per document lives in `dirtyDocs.ts` and this only+ * says WHICH.+ *+ * Until this existed the only save a driver could reach was `project.save` via+ * run_editor_command, which is context-aware: it saves the ACTIVE dock panel's+ * document and otherwise the scene. Driving it from outside meant an edit landed+ * in the scene file, or nowhere, depending on which tab the user last clicked.+ */+export async function saveAssetDocument(+ docId?: string,+): Promise<{ docId: string; path: string; saved: boolean }> {+ const doc = resolve(docId);+ if (!doc.filePath) {+ throw new Error(+ `asset document "${doc.docId}" has no file path — it has never been saved, and naming a new one `+ + 'is a Save As dialog that nothing here can answer',+ );+ }+ // A document nobody registered would report "did not save" for the same+ // reason a clean one does. That is an editor bug, not an answer.+ if (!DirtyRegistry.knows(doc.docId)) {+ throw new Error(`asset document "${doc.docId}" registered no save with the editor — this is a bug`);+ }+ // false = it was already clean, which is not a failure: the caller asked for+ // the file to match the document, and it does.+ const saved = await DirtyRegistry.saveDoc(doc.docId);+ return { docId: doc.docId, path: doc.filePath, saved };+}diff --git a/desktop/src/main.tsx b/desktop/src/main.tsxindex f65204193..3195a9d6c 100644--- a/desktop/src/main.tsx+++ b/desktop/src/main.tsx@@ -73,7 +73,7 @@ import { attachAgentBridge, agentDriving, subscribeAgent } from './store/AgentStimport { guardAutomationHook } from './engine/automationGate';import { activeMode } from './mode/activeMode';import {- openAssetDocuments, readAssetDocument, editAssetDocument, type AssetDocumentChange,+ openAssetDocuments, readAssetDocument, editAssetDocument, saveAssetDocument, type AssetDocumentChange,} from './document/assetDocumentOps';// Register the built-in settings (side effect) and replay persisted ones.import './settings';@@ -418,7 +418,17 @@ function buildEditorAutomation(): unknown {await openSceneAwaited(path);return documentState();}- openAssetOfType(type, path, path.split('/').pop() ?? path);+ await openAssetOfType(type, path, path.split('/').pop() ?? path);+ // Every editor that OWNS a document binds the file to it. A read or parse+ // failure inside one only toasts, which nobody here can see — so check the+ // binding landed instead of reporting an open that did not happen and+ // leaving the next call to say "no asset document is open".+ // Two types own no document: a material is edited in the shared Details+ // inspector (which loads the SELECTED asset), and audio is a preview.+ const documentless = type === 'material' || type === 'audio';+ if (!documentless && !openAssetDocuments().some((d) => d.path === path)) {+ throw new Error(`${path} did not open — the editor logged the reason (get_logs)`);+ }return documentState();},/**@@ -437,6 +447,7 @@ function buildEditorAutomation(): unknown {getAssetDocument: (docId?: string) => readAssetDocument(docId),editAssetDocument: (changes: AssetDocumentChange[], docId?: string, label?: string) =>editAssetDocument(changes, docId, label),+ saveAssetDocument: (docId?: string) => saveAssetDocument(docId),/** Leave Prefab Mode — the banner's "Back to Scene". Refuses on unsaved prefab* changes unless `discardChanges` (see openAsset). */exitPrefabMode: async (discardChanges = false) => {diff --git a/desktop/src/material/openMaterialGraph.ts b/desktop/src/material/openMaterialGraph.tsindex fb423a3bc..2f5e10918 100644--- a/desktop/src/material/openMaterialGraph.ts+++ b/desktop/src/material/openMaterialGraph.ts@@ -36,7 +36,15 @@ export async function openMaterialGraph(path: string): Promise<void> {}}-/** Write the graph + recompile its sibling `.esshader`. Throws on a graph that can't compile. */+/**+ * Write the graph + recompile its sibling `.esshader`.+ *+ * A failure both toasts AND rethrows. The toast is for the person who clicked+ * Save; the throw is for everyone who cannot see one — the quit-save, which must+ * not report a clean exit over a graph that never wrote, and a driver calling+ * save_asset_document, which would otherwise be told the save succeeded while+ * the compile that produces the shader had failed.+ */export async function saveMaterialGraph(path: string, graph: MaterialGraph): Promise<void> {try {const shader = compileMaterialGraph(graph); // throws on a broken graph — surfaced below@@ -46,6 +54,7 @@ export async function saveMaterialGraph(path: string, graph: MaterialGraph): ProToasts.push(t('mat.graphSaved'), 'info', 1400);} catch (e) {Toasts.push(t('mat.saveGraphFailed', { error: String(e) }), 'error');+ throw e;}}diff --git a/desktop/src/panels/ContentBrowser.tsx b/desktop/src/panels/ContentBrowser.tsxindex d43826b91..450dd424f 100644--- a/desktop/src/panels/ContentBrowser.tsx+++ b/desktop/src/panels/ContentBrowser.tsx@@ -461,7 +461,9 @@ export function ContentBrowser() {go(path);return;}- openAssetOfType(typeAt(path), path, name);+ // Awaitable for drivers; a double-click has nothing to wait for, and every+ // opener already reports its own failure as a toast.+ void openAssetOfType(typeAt(path), path, name).catch(() => {});};// After any fs mutation: re-read open directories + re-scan the asset registrydiff --git a/desktop/src/panels/MaterialGraphEditor.tsx b/desktop/src/panels/MaterialGraphEditor.tsxindex fbd49f2fd..2e3aeb010 100644--- a/desktop/src/panels/MaterialGraphEditor.tsx+++ b/desktop/src/panels/MaterialGraphEditor.tsx@@ -141,7 +141,9 @@ export function MaterialGraphEditor() {)}<span className="ng-doc-title">{filePath.split('/').pop()}</span><span style={{ flex: 1 }} />- <SaveButton dirty={dirty} onSave={() => void saveMaterialGraph(filePath, graph)} label={t('mat.save')} />+ {/* The failure already reached this user as a toast; the rethrow is for the+ callers who have no screen (quit-save, save_asset_document). */}+ <SaveButton dirty={dirty} onSave={() => void saveMaterialGraph(filePath, graph).catch(() => {})} label={t('mat.save')} /></>);diff --git a/desktop/src/project/assetOpen.ts b/desktop/src/project/assetOpen.tsindex 94e714cc1..35416b40a 100644--- a/desktop/src/project/assetOpen.ts+++ b/desktop/src/project/assetOpen.ts@@ -29,19 +29,24 @@ import { openBehaviorTree } from '@/bt/openBehaviorTree';* Open an asset by type — built-ins from the table below, contributed types from* their own registration (a plugin carries its open action on the type itself, since* it has no import cycle to design around). Returns false when nothing can open it.+ *+ * AWAITABLE, because most of these openers read the file before they have a+ * document: a caller that did not wait — the MCP `open_asset` door — returned+ * while the read was still in flight, so the very next call could be told that+ * nothing was open. A double-click has no such caller and simply ignores it.*/-export function openAssetOfType(type: AssetType, path: string, name: string): boolean {+export async function openAssetOfType(type: AssetType, path: string, name: string): Promise<boolean> {const builtin = ASSET_OPEN[type];if (builtin) {- builtin(path, name);+ await builtin(path, name);return true;}const contributed = assetTypeRegistry.get(type);if (contributed?.open) {- contributed.open(path);+ await contributed.open(path);return true;}- void openOutside(type, path);+ await openOutside(type, path);return true;}@@ -84,20 +89,23 @@ export function opensInEditor(type: AssetType): boolean {return !!ASSET_OPEN[type] || !!assetTypeRegistry.get(type)?.open;}-/** Open action per built-in asset type; types absent here aren't double-click-openable. */-export const ASSET_OPEN: Partial<Record<AssetType, (path: string, name: string) => void>> = {+/** Open action per built-in asset type; types absent here aren't double-click-openable.+ * An action that reads the file RETURNS its promise — see {@link openAssetOfType}. */+export const ASSET_OPEN: Partial<Record<AssetType, (path: string, name: string) => void | Promise<void>>> = {scene: async (path, name) => {if (!(await confirmDiscard(t('discard.openScene', { name })))) return;- void ProjectStore.openScene(path);+ await ProjectStore.openScene(path);},- prefab: (path) => void ProjectStore.openPrefab(path),+ prefab: (path) => ProjectStore.openPrefab(path),audio: (path) => toggleAudioPreview(path),- animation: (path) => void openAnimationClip(path),- animclip: (path) => void openFlipbook(path),- tileset: (path) => void openTileset(path),- material: (path) => void openMaterial(path),- materialgraph: (path) => void openMaterialGraph(path),- statemachine: (path) => void openStateMachine(path),- animatorcontroller: (path) => void openAnimatorController(path),- behaviortree: (path) => void openBehaviorTree(path),+ animation: (path) => openAnimationClip(path),+ animclip: (path) => openFlipbook(path),+ tileset: (path) => openTileset(path),+ // Synchronous: a material is edited in the shared Details inspector, which+ // loads it itself — there is no document to wait for here.+ material: (path) => openMaterial(path),+ materialgraph: (path) => openMaterialGraph(path),+ statemachine: (path) => openStateMachine(path),+ animatorcontroller: (path) => openAnimatorController(path),+ behaviortree: (path) => openBehaviorTree(path),};diff --git a/desktop/tests/asset-document-ops.test.ts b/desktop/tests/asset-document-ops.test.tsindex 6ddfbb2d5..910753f69 100644--- a/desktop/tests/asset-document-ops.test.ts+++ b/desktop/tests/asset-document-ops.test.ts@@ -10,8 +10,10 @@* rather than created, because these are typed documents whose editors* rely on their shape.*/-import { describe, it, expect } from 'vitest';-import { setByPath } from '@/document/assetDocumentOps';+import { describe, it, expect, afterEach } from 'vitest';+import { setByPath, saveAssetDocument } from '@/document/assetDocumentOps';+import { AssetDocument } from '@/document/AssetDocument';+import { DirtyRegistry } from '@/document/DirtyRegistry';const clip = () => ({fps: 12,@@ -71,3 +73,70 @@ describe('addressing an asset document by path', () => {expect(() => setByPath(clip(), '..', 1)).toThrow(/empty path/);});});++/** A stand-in for the eight real editors: only the AssetDocument shape matters here. */+class TestDoc extends AssetDocument<{ n: number }> {+ open(asset: { n: number }, path: string | null): void {+ this.openAsset(asset, path);+ }+ close(): void {+ this.closeAsset();+ }+}++describe('saving an open asset document', () => {+ const doc = new TestDoc('testdoc');++ afterEach(() => {+ doc.close();+ DirtyRegistry.clearAll();+ });++ const register = (save: () => Promise<void>) =>+ DirtyRegistry.register({ id: 'testdoc', isDirty: () => doc.dirty, save });++ it("goes through the document's own registered save", async () => {+ // Not a JSON write of what get_asset_document returns: a tileset and a+ // timeline serialize, and a material graph compiles a sibling `.esshader`.+ doc.open({ n: 1 }, 'fx/thing.json');+ doc.replaceAsset({ n: 2 }); // dirty+ const calls: string[] = [];+ register(async () => {+ calls.push('save');+ doc.markSaved();+ });++ await expect(saveAssetDocument()).resolves.toEqual({+ docId: 'testdoc', path: 'fx/thing.json', saved: true,+ });+ expect(calls).toEqual(['save']);+ expect(doc.dirty).toBe(false);+ });++ it('reports a clean document as "nothing to write", not as a failure', async () => {+ doc.open({ n: 1 }, 'fx/thing.json');+ register(async () => {+ throw new Error('a clean document must not be saved');+ });+ await expect(saveAssetDocument()).resolves.toMatchObject({ saved: false });+ });++ it('refuses a document whose save nothing registered', async () => {+ // Otherwise this is indistinguishable from "it was clean" — the caller is+ // told the file matches the document when nothing ever wrote it.+ doc.open({ n: 1 }, 'fx/thing.json');+ doc.replaceAsset({ n: 2 });+ await expect(saveAssetDocument()).rejects.toThrow(/registered no save/);+ });++ it('refuses an untitled document instead of raising a Save As nobody can answer', async () => {+ doc.open({ n: 1 }, null);+ doc.replaceAsset({ n: 2 });+ register(async () => {});+ await expect(saveAssetDocument()).rejects.toThrow(/no file path/);+ });++ it('names the document that is not open, when none is', async () => {+ await expect(saveAssetDocument()).rejects.toThrow(/no asset document is open/);+ });+});diff --git a/desktop/tests/editor-mcp-tools.test.ts b/desktop/tests/editor-mcp-tools.test.tsindex 75b3ed2e8..23bb449f4 100644--- a/desktop/tests/editor-mcp-tools.test.ts+++ b/desktop/tests/editor-mcp-tools.test.ts@@ -222,6 +222,23 @@ describe('editor MCP tool registry', () => {}});+ it('an asset editor has a save of its own — project.save is the ACTIVE panel', async () => {+ // run_editor_command('project.save') routes by whichever dock panel the user+ // last clicked: driven from outside, an edit to a material graph landed in+ // the scene file, or nowhere. This tool names the document instead.+ const driver = vi.fn() as unknown as { js: ReturnType<typeof vi.fn> } & ((...a: unknown[]) => unknown);+ driver.js = vi.fn(async () => ({ docId: 'materialgraph', path: 'fx/fire.esmatgraph', saved: true }));+ const save = toolNamed('save_asset_document');+ expect([!!save, irreversible(save)]).toEqual([true, true]); // it writes a file: stop and ask++ const res = await runTool(save, driver, { docId: 'materialgraph' });+ expect(driver.js).toHaveBeenCalledWith(expect.stringContaining('saveAssetDocument("materialgraph"'));+ expect(res.isError).toBeFalsy();++ await runTool(save, driver, {}); // no docId = the only one open+ expect(driver.js).toHaveBeenLastCalledWith(expect.stringContaining('saveAssetDocument(null ?? undefined)'));+ });+it('every resource maps to a surface method with a JSON mime', () => {for (const r of RESOURCES as Array<{ uri: string; method: string; mimeType: string }>) {expect(r.uri.startsWith('editor://')).toBe(true);