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(mcp): a driver can edit a prefab, not just make one
yhhc6077d10b91d
diff --git a/desktop/scripts/editor-mcp-editor-e2e.mjs b/desktop/scripts/editor-mcp-editor-e2e.mjsindex f58b2f4ea..f76d710db 100644--- a/desktop/scripts/editor-mcp-editor-e2e.mjs+++ b/desktop/scripts/editor-mcp-editor-e2e.mjs@@ -6,12 +6,13 @@* Spawns editor-mcp.mjs --editor (the real editor app with --mcp) against a TEMP* COPY of the platformer example and drives the full game-making loop over MCP:* open project → open scene → entity-template catalog → create entity → edit a- * field → verify it reached the live World → screenshot → save → play → stop.+ * field → verify it reached the live World → screenshot → save → prefab round trip+ * (instance → Prefab Mode → save the asset → back → revert → unpack) → play → stop.* Run from desktop/ after a dist build: node scripts/editor-mcp-editor-e2e.mjs* (ESTELLA_E2E_EXPORT=1 additionally runs a web export to the temp dir.)*/import { spawn } from 'node:child_process';-import { cp, mkdir, mkdtemp, rm, stat, writeFile } from 'node:fs/promises';+import { cp, mkdir, mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises';import os from 'node:os';import path from 'node:path';import { fileURLToPath } from 'node:url';@@ -66,14 +67,16 @@ child.stderr.on('data', (d) => process.stderr.write(d));const send = (msg) => child.stdin.write(JSON.stringify(msg) + '\n');let nextId = 0;-const rpc = (method, params, timeoutMs = 60_000) => new Promise((resolve, reject) => {+const rpc = (method, params, timeoutMs = 60_000, label = method) => new Promise((resolve, reject) => {const id = ++nextId;- const t = setTimeout(() => reject(new Error(`timeout waiting for ${method}`)), timeoutMs);+ const t = setTimeout(() => reject(new Error(`timeout waiting for ${label}`)), timeoutMs);waiters.set(id, (m) => { clearTimeout(t); resolve(m); });send({ jsonrpc: '2.0', id, method, params });});const call = async (name, args, timeoutMs) => {- const res = await rpc('tools/call', { name, arguments: args ?? {} }, timeoutMs);+ // Labelled with the tool name: a bare "timeout waiting for tools/call" leaves you+ // counting call sites to work out which step of the run wedged.+ const res = await rpc('tools/call', { name, arguments: args ?? {} }, timeoutMs, `tools/call ${name}`);if (res.result?.isError) throw new Error(`${name}: ${res.result?.content?.[0]?.text}`);return res.result?.content?.[0];};@@ -94,7 +97,8 @@ try {const list = await rpc('tools/list', {});const names = (list.result?.tools ?? []).map((t) => t.name);- for (const need of ['open_project', 'open_scene', 'list_entity_templates', 'create_entity', 'save_scene', 'screenshot', 'export_game'])+ for (const need of ['open_project', 'open_scene', 'list_entity_templates', 'create_entity', 'save_scene', 'screenshot', 'export_game',+ 'open_asset', 'get_document', 'exit_prefab_mode', 'edit_prefab', 'apply_prefab', 'revert_prefab', 'unpack_prefab', 'create_prefab_variant'])if (!names.includes(need)) await fail(`tools/list missing ${need}`);console.log(`tools/list OK — ${names.length} tools`);@@ -173,6 +177,74 @@ try {if (mtimeAfter <= mtimeBefore) await fail('save_scene did not rewrite the scene file');console.log('save_scene OK — scene file rewritten');+ // — Prefabs: the identity surface, end to end (make one → instance it → edit it in+ // Prefab Mode → save the ASSET → come back → revert → unpack) —+ // Every tool result is JSON-encoded, so a string ref comes back quoted.+ const prefabRef = JSON.parse((await call('create_prefab_from_entity', { entity: created }, 60_000)).text);+ const prefabAsset = JSON.parse((await call('list_assets', { type: 'prefab' })).text)+ .assets.find((a) => a.ref === prefabRef);+ if (!prefabAsset) await fail(`the new prefab ${prefabRef} is not in list_assets`);+ const instance = Number((await call('create_entity', { template: `prefab:${prefabAsset.path}` })).text);+ const instanceInfo = JSON.parse((await call('get_entity', { id: instance })).text);+ if (instanceInfo?.prefab?.ref !== prefabRef)+ await fail(`get_entity does not report the prefab link (${JSON.stringify(instanceInfo)})`);+ console.log(`prefab instance OK — get_entity reports ${prefabRef}`);++ await call('save_scene', {}, 60_000); // Prefab Mode refuses to discard unsaved work+ const prefabDoc = JSON.parse((await call('edit_prefab', { entity: instance }, 60_000)).text);+ if (prefabDoc.kind !== 'prefab' || prefabDoc.path !== prefabAsset.path)+ await fail(`edit_prefab did not enter Prefab Mode (${JSON.stringify(prefabDoc)})`);+ if (JSON.parse((await call('get_document')).text).kind !== 'prefab')+ await fail('get_document does not report Prefab Mode — a driver cannot tell what it is editing');+ const prefabTree = JSON.parse((await call('get_scene_tree')).text);+ if (prefabTree.length !== 1) await fail(`Prefab Mode should show the prefab alone (${JSON.stringify(prefabTree)})`);+ await call('set_field', { entity: prefabTree[0].id, component: 'Sprite', key: 'layer', type: 'number', value: 3 });+ await call('save_scene', {}, 60_000); // in Prefab Mode this writes the .esprefab+ const prefabFile = path.join(project, prefabAsset.path);+ if (!/"layer":\s*3/.test(await readFile(prefabFile, 'utf8')))+ await fail('save_scene in Prefab Mode did not write the edit into the .esprefab');+ const backDoc = JSON.parse((await call('exit_prefab_mode', {}, 60_000)).text);+ if (backDoc.kind !== 'scene') await fail(`exit_prefab_mode did not return to the scene (${JSON.stringify(backDoc)})`);+ console.log('prefab mode OK — edit_prefab → set_field → save wrote the asset → exit_prefab_mode');++ // Apply rewrites the shared asset for every instance, so it refuses until the+ // caller states the intent (a person is shown a diff dialog instead).+ let refused = false;+ try { await call('apply_prefab', { entity: instance, confirm: false }); } catch { refused = true; }+ if (!refused) await fail('apply_prefab committed without confirm');+ console.log('apply_prefab OK — refuses without confirm');++ // A UI prefab is opened inside an editing-environment Canvas so its percentage+ // boxes resolve. The environment must be invisible: no Outliner row, and not one+ // byte of it in the asset.+ const uiEntity = Number((await call('create_entity', { template: 'ui-image' })).text);+ const uiRef = JSON.parse((await call('create_prefab_from_entity', { entity: uiEntity }, 60_000)).text);+ const uiAsset = JSON.parse((await call('list_assets', { type: 'prefab' })).text)+ .assets.find((a) => a.ref === uiRef);+ if (!uiAsset) await fail(`the new UI prefab ${uiRef} is not in list_assets`);+ await call('save_scene', {}, 60_000);+ const uiFile = path.join(project, uiAsset.path);+ const uiAssetBefore = await readFile(uiFile, 'utf8');+ const uiDoc = JSON.parse((await call('open_asset', { path: uiAsset.path }, 60_000)).text);+ if (uiDoc.kind !== 'prefab') await fail(`open_asset did not enter Prefab Mode (${JSON.stringify(uiDoc)})`);+ const uiTree = JSON.parse((await call('get_scene_tree')).text);+ if (uiTree.length !== 1 || /canvas/i.test(uiTree[0].name))+ await fail(`the editing environment leaked into the Outliner (${JSON.stringify(uiTree)})`);+ await call('save_scene', {}, 60_000);+ if ((await readFile(uiFile, 'utf8')) !== uiAssetBefore)+ await fail('saving a hosted UI prefab changed the asset — the editing environment leaked into it');+ await call('exit_prefab_mode', {}, 60_000);+ console.log('ui prefab OK — hosted for layout, absent from the tree and from the asset');++ // The rest of the identity surface: revert re-syncs the instance (fresh ids),+ // unpack cuts the link for good.+ const reverted = Number((await call('revert_prefab', { entity: instance }, 60_000)).text);+ if (!Number.isFinite(reverted)) await fail('revert_prefab returned no fresh instance root');+ await call('unpack_prefab', { entity: reverted });+ if (JSON.parse((await call('get_entity', { id: reverted })).text)?.prefab)+ await fail('unpack_prefab left the prefab link in place');+ console.log('revert_prefab + unpack_prefab OK — re-synced, then detached');+await call('toggle_play', {}, 60_000);let play = null;for (let i = 0; i < 60; i++) {diff --git a/desktop/scripts/editor-mcp-tools.mjs b/desktop/scripts/editor-mcp-tools.mjsindex a3261db44..1d7276c4f 100644--- a/desktop/scripts/editor-mcp-tools.mjs+++ b/desktop/scripts/editor-mcp-tools.mjs@@ -55,7 +55,8 @@ export const TOOLS = [description: 'The scene entity tree (id, name, kind, children).',schema: obj({}), method: 'getSceneTree', args: () => [] },{ name: 'get_entity',- description: 'One entity: name, kind, and its component list.',+ description: 'One entity: name, kind, and its component list. A member of a prefab INSTANCE also carries '+ + '`prefab: { ref, prefabId, instanceRoot, isRoot }` — how to tell an instance from an ordinary entity, and what edit_prefab / apply_prefab / revert_prefab / unpack_prefab act on (resolve `ref` to a path with list_assets).',schema: obj({ id: { type: 'number' } }, ['id']), method: 'getEntity', args: (i) => [i.id] },{ name: 'get_inspector',description: "An entity's components and fields — the Details-panel data.",@@ -180,8 +181,44 @@ export const TOOLS = [schema: obj({ path: { type: 'string' }, discardChanges: { type: 'boolean' } }, ['path']),method: 'openScene', args: (i) => [i.path, i.discardChanges === true], root: 'editor' },{ name: 'save_scene', write: true,- description: 'Save the open scene to disk (the toolbar Save).',+ description: 'Save the open DOCUMENT to disk (the toolbar Save) — the scene, or, in Prefab Mode, the prefab being edited (see get_document).',schema: obj({}), method: 'save', args: () => [], root: 'editor' },+ { name: 'open_asset',+ description: 'Open an asset in the editor that owns its type, awaited (the Content Browser double-click): a PREFAB enters Prefab Mode — the prefab as its own editable entity tree, where every scene tool then acts on the prefab, and save_scene writes the asset for every instance; '+ + 'a scene becomes the document; anything else (statemachine, behaviortree, tileset, animclip, animation, material, materialgraph) opens its own editor panel. Returns the document afterwards, same shape as get_document. '+ + 'REFUSES, rather than prompting, when opening a scene/prefab would discard unsaved changes (pass discardChanges to throw them away), and refuses a type the editor has no editor for instead of handing the file to an external program.',+ schema: obj({ path: { type: 'string' }, discardChanges: { type: 'boolean' } }, ['path']),+ js: (i) => `window.__estellaEditor.openAsset(${JSON.stringify(i.path)}, ${i.discardChanges === true})` },+ { name: 'get_document',+ description: 'What the editor is editing right now: { kind: "scene" | "prefab", path, name, dirty } (+ isVariant / returnScene in Prefab Mode). '+ + 'CHECK THIS after open_asset — in Prefab Mode every scene read/write tool acts on the PREFAB, not on a scene, and `dirty` says whether anything is unsaved.',+ schema: obj({}), js: () => `window.__estellaEditor.documentState()` },+ { name: 'exit_prefab_mode',+ description: 'Leave Prefab Mode and go back to the scene you came from (the banner\'s "Back to Scene"). REFUSES on unsaved prefab changes unless discardChanges.',+ schema: obj({ discardChanges: { type: 'boolean' } }),+ js: (i) => `window.__estellaEditor.exitPrefabMode(${i.discardChanges === true})` },+ { name: 'edit_prefab',+ description: 'Open the prefab an INSTANCE came from, in Prefab Mode (the Outliner\'s "Edit Prefab") — no ref→path lookup needed. Same refusals as open_asset.',+ schema: obj({ entity: { type: 'number' }, discardChanges: { type: 'boolean' } }, ['entity']),+ js: (i) => `window.__estellaEditor.editPrefab(${Number(i.entity)}, ${i.discardChanges === true})` },+ { name: 'apply_prefab', write: true,+ description: 'Push an instance\'s overrides back into its prefab asset (the Outliner\'s "Apply to Prefab") — the base for EVERY instance is rewritten, and this instance\'s overrides clear. '+ + 'Property, name, visibility and component overrides plus structural add/remove. `confirm` must be true: a person is shown an itemized diff first, so a driver says it out loud instead (get_inspector marks the overridden fields).',+ schema: obj({ entity: { type: 'number' }, confirm: { type: 'boolean' } }, ['entity', 'confirm']),+ js: (i) => `window.__estellaEditor.applyPrefab(${Number(i.entity)}, ${i.confirm === true})` },+ { name: 'revert_prefab', write: true,+ description: 'Discard an instance\'s overrides and re-sync it to its prefab (the Outliner\'s "Revert to Prefab"), keeping its placement. Returns the fresh instance root\'s id — the old ids are gone (it is a delete + re-instantiate).',+ schema: obj({ entity: { type: 'number' } }, ['entity']),+ js: (i) => `window.__estellaEditor.revertPrefab(${Number(i.entity)})` },+ { name: 'unpack_prefab', write: true,+ description: 'Detach an instance (the Outliner\'s "Unpack Prefab"): its entities become ordinary scene entities and lose every prefab link, so later prefab edits no longer reach them. Undoable.',+ schema: obj({ entity: { type: 'number' } }, ['entity']),+ js: (i) => `window.__estellaEditor.unpackPrefab(${Number(i.entity)})` },+ { name: 'create_prefab_variant', write: true,+ description: 'Save a new `.esprefab` that INHERITS the instance\'s prefab and bakes in its current overrides (the Outliner\'s "Create Variant" — a prefab of a prefab), then re-link the instance to the variant. '+ + 'Written beside the base as "<base> Variant.esprefab"; returns the re-linked root\'s id. Deletions are not representable in a variant and are skipped.',+ schema: obj({ entity: { type: 'number' } }, ['entity']),+ js: (i) => `window.__estellaEditor.createPrefabVariant(${Number(i.entity)})` },{ name: 'create_scene_file', write: true,description: 'Create a blank scene FILE under a project-relative directory (does not switch to it); returns its path, immediately referenceable (the registry refresh happens before this resolves). '+ '`name` names it (the `.esscene` extension is added if absent); without one it is `scene.esscene`, which collides the moment you make a second.',diff --git a/desktop/src/engine/EditorControlSurface.ts b/desktop/src/engine/EditorControlSurface.tsindex beffa7934..5946312cb 100644--- a/desktop/src/engine/EditorControlSurface.ts+++ b/desktop/src/engine/EditorControlSurface.ts@@ -21,7 +21,6 @@ import type {InspectorComponent,InspectorFieldType,InspectorFieldValue,- NodeKind,SceneNode,} from '@/types';import type { SceneData, PrefabData, SubsystemStatus } from 'esengine';@@ -31,7 +30,7 @@ import { isRequiredEmpty } from './schema';import { ViewportController } from './ViewportController';import { PerfMonitor, type PerfSnapshot, type FrameSample, type SessionCapture } from './PerfMonitor';import type { SceneCommandsImpl, EditorTransaction } from './SceneCommands';-import type { SceneQueryImpl } from './SceneQuery';+import type { SceneQueryImpl, EntityInfo } from './SceneQuery';import type { SceneModelImpl } from './SceneModel';import type { EditorHistoryImpl } from './EditorHistory';import type { ReconcilerImpl } from './Reconciler';@@ -476,7 +475,7 @@ export class EditorControlSurfaceImpl {getSceneTree(): SceneNode[] {return this.s.query.readSceneTree();}- getEntity(id: EntityId): { name: string; kind: NodeKind; components: string[] } | null {+ getEntity(id: EntityId): EntityInfo | null {return this.s.query.readEntity(id);}getInspector(entity: EntityId): InspectorComponent[] {diff --git a/desktop/src/engine/SceneQuery.ts b/desktop/src/engine/SceneQuery.tsindex 4a40968d3..310fb5b27 100644--- a/desktop/src/engine/SceneQuery.ts+++ b/desktop/src/engine/SceneQuery.ts@@ -61,6 +61,16 @@ export function buildSceneTree(data: SceneData | null): SceneNode[] {return roots.map(build);}+/** One entity's identity: what it is, and (for a prefab instance) what it came from. */+export interface EntityInfo {+ name: string;+ kind: NodeKind;+ components: string[];+ /** Present only for an entity inside a prefab instance. `isRoot` marks the instance+ * root (the entity Apply / Revert / Unpack resolve to). */+ prefab?: { ref: string; prefabId: string; instanceRoot: EntityId; isRoot: boolean };+}+/** Name/kind/components for one entity in a SceneData. */export function buildEntityInfo(data: SceneData | null, id: EntityId): { name: string; kind: NodeKind; components: string[] } | null {const e = data?.entities.find((x) => x.id === id);@@ -189,9 +199,21 @@ export class SceneQueryImpl {return buildSceneTree(this.model.current);}- /** Inspect a single source entity (name, kind, which components it carries). */- readEntity(id: EntityId): { name: string; kind: NodeKind; components: string[] } | null {- return buildEntityInfo(this.model.current, id);+ /**+ * Inspect a single source entity (name, kind, which components it carries) plus its+ * prefab link when it is part of an instance — the one thing that made an instance+ * indistinguishable from an ordinary entity to a reader outside the Outliner (whose+ * warm tint and context menu are the only other place it shows). Resolve `ref`+ * to a path through the asset registry (MCP: `list_assets`).+ */+ readEntity(id: EntityId): EntityInfo | null {+ const info = buildEntityInfo(this.model.current, id);+ if (!info) return null;+ const tag = this.model.prefabTag(id);+ if (!tag) return info;+ const ref = tag.prefab ?? this.model.prefabTag(tag.instanceRoot)?.prefab;+ if (!ref) return info;+ return { ...info, prefab: { ref, prefabId: tag.prefabId, instanceRoot: tag.instanceRoot, isRoot: !!tag.prefab } };}/** Full editable inspector model for a source entity — fields resolved per component. */diff --git a/desktop/src/main.tsx b/desktop/src/main.tsxindex f25be2bdc..74c730fba 100644--- a/desktop/src/main.tsx+++ b/desktop/src/main.tsx@@ -63,7 +63,8 @@ import { PerfMonitor } from './engine/PerfMonitor';import { LogStore } from './store/LogStore';import { initFsWatch } from './project/fsWatch';import { initPlugins } from './plugins/init';-import { openAssetOfType } from './project/assetOpen';+import { openAssetOfType, opensInEditor } from './project/assetOpen';+import { DirtyRegistry } from './document/DirtyRegistry';import { initBackgroundThrottle } from './engine/backgroundThrottle';// Register the built-in settings (side effect) and replay persisted ones.import './settings';@@ -87,6 +88,38 @@ initPlugins();applyFxPreview(useEditorStore.getState().previewFx);initFxPreviewEditRestart();+/** The open document: a scene, or the prefab being edited in Prefab Mode. `dirty` is+ * the aggregate registry (scene + every open asset editor), the same truth the+ * unsaved-changes prompts read. */+function documentState(): { kind: 'scene' | 'prefab'; path: string | null; name: string | null; dirty: boolean; isVariant?: boolean; returnScene?: string | null } {+ const st = ProjectStore.getSnapshot();+ const pe = st?.prefabEdit ?? null;+ const dirty = DirtyRegistry.isDirty();+ if (pe) return { kind: 'prefab', path: pe.path, name: pe.name, dirty, isVariant: !!pe.isVariant, returnScene: pe.returnScene };+ return { kind: 'scene', path: st?.currentScene ?? null, name: st?.name ?? null, dirty };+}++/** Open a scene and resolve once it is ADOPTED and readable, so a driver never has to+ * poll get_scene_tree itself. Shared by the openScene and openAsset doors. */+async function openSceneAwaited(rel: string): Promise<void> {+ const v0 = EditorControlSurface.worldVersion();+ await ProjectStore.openScene(rel);+ const t0 = Date.now();+ while (EditorControlSurface.worldVersion() === v0 && Date.now() - t0 < 30_000) {+ await new Promise((r) => setTimeout(r, 100));+ }+}++/** Throw unless the entity belongs to a prefab instance — the identity operations+ * answer `null` for anything else, which reads to a driver as "it worked". */+function requireInstance(entity: number): void {+ const tag = SceneModel.prefabTag(entity);+ const ref = tag?.prefab ?? (tag ? SceneModel.prefabTag(tag.instanceRoot)?.prefab : undefined);+ if (!ref) {+ throw new Error(`entity ${entity} is not part of a prefab instance (get_entity reports the link as \`prefab\`)`);+ }+}+// Automation hook (screenshots / visual-regression): with `?automation=1`, expose the// minimum to drive the launcher→editor flow from a headless driver. Gated so the normal// editor never carries it; mirrors the headless render host's `window.__estellaHeadless`.@@ -138,12 +171,7 @@ if (new URLSearchParams(location.search).has('automation')) {'the open scene has unsaved changes — save_scene first, or pass discardChanges to throw them away',);}- const v0 = EditorControlSurface.worldVersion();- await ProjectStore.openScene(rel);- const t0 = Date.now();- while (EditorControlSurface.worldVersion() === v0 && Date.now() - t0 < 30_000) {- await new Promise((r) => setTimeout(r, 100));- }+ await openSceneAwaited(rel);},/** Resolves once the project's initial scene is in the tree (call after* open + enterEditor; the boot pipeline loads the last-opened scene). */@@ -291,10 +319,122 @@ if (new URLSearchParams(location.search).has('automation')) {/** Patch an asset's `.meta` import settings (dotted keys, e.g. `sliceBorder.left`). */setImportSettings: (path: string, patch: Record<string, unknown>) =>ProjectStore.setImportSettings(path, patch),- /** Double-click-open an asset by project path (FSM/BT/tileset/clip editors…). */- openAsset: (path: string) => {- const name = path.split('/').pop() ?? path;- openAssetOfType(ProjectStore.assetTypeAt(path), path, name);+ /**+ * Double-click-open an asset by project path, awaited: a prefab enters PREFAB+ * MODE, a scene becomes the document, everything else opens its own editor panel+ * (FSM / BT / tileset / clip / material…). Returns the document afterwards.+ *+ * Three things a driver needs that a double-click doesn't. No PROMPT can be left+ * standing: unsaved work is either refused here or discarded through the door's own+ * `discardChanges`, never handed to a modal with nobody there to answer it (which+ * hangs the call for good). Refusals that the UI reports as a toast — a nested+ * prefab, a variant of a non-flat base — become throws a driver can read. And a+ * type the editor has no editor for is refused instead of being handed to whatever+ * program the OS associates with it: "open this `.png`" means to author, not to pop+ * an image viewer on the user's desktop.+ */+ openAsset: async (path: string, discardChanges = false) => {+ const type = ProjectStore.assetTypeAt(path);+ if (!opensInEditor(type)) {+ throw new Error(+ `the editor has no editor for a '${type}' asset (${path}) — a double-click would hand it to an `+ + 'external program. Read or write it as text instead (read_project_file / write_project_file).',+ );+ }+ // A scene or prefab REPLACES the document, and both take `discardChanges` all the+ // way down. An asset editor prompts about ITS OWN document, which nothing here can+ // answer for — so it opens only from a clean state.+ const swapsDocument = type === 'scene' || type === 'prefab';+ if (DirtyRegistry.isDirty() && !(swapsDocument && discardChanges)) {+ throw new Error(swapsDocument+ ? `opening ${path} would discard unsaved changes — save first, or pass discardChanges to throw them away`+ : `save the open documents before opening ${path} — an asset editor asks about its own unsaved changes, `+ + 'and that prompt has nobody to answer it here',+ );+ }+ if (type === 'prefab') {+ await ProjectStore.openPrefab(path, { discardChanges: true });+ const doc = documentState();+ if (doc.kind !== 'prefab' || doc.path !== path) {+ throw new Error(+ `${path} did not open in Prefab Mode: a NESTED prefab, or a variant whose base isn't flat, is refused `+ + '(the editor logged the reason — get_logs)',+ );+ }+ return doc;+ }+ if (type === 'scene') {+ await openSceneAwaited(path);+ return documentState();+ }+ openAssetOfType(type, path, path.split('/').pop() ?? path);+ return documentState();+ },+ /**+ * What the editor is editing right now — the document every scene read/write+ * acts on: a scene, or a prefab when Prefab Mode is open. Without this a driver+ * that entered Prefab Mode had no way to tell (the tools kept answering, about a+ * different document), and no way to know whether `save` writes a scene or an asset.+ */+ documentState,+ /** Leave Prefab Mode — the banner's "Back to Scene". Refuses on unsaved prefab+ * changes unless `discardChanges` (see openAsset). */+ exitPrefabMode: async (discardChanges = false) => {+ if (!ProjectStore.getSnapshot()?.prefabEdit) {+ throw new Error('not editing a prefab — nothing to leave (see get_document)');+ }+ if (!discardChanges && DirtyRegistry.isDirty()) {+ throw new Error('the prefab has unsaved changes — save first, or pass discardChanges to throw them away');+ }+ await ProjectStore.exitPrefabMode({ discardChanges: true });+ return documentState();+ },+ /** Open the prefab an INSTANCE came from, in Prefab Mode (the Outliner's "Edit+ * Prefab") — the door that needs no ref→path lookup by the caller. */+ editPrefab: async (entity: number, discardChanges = false) => {+ requireInstance(entity);+ if (!discardChanges && DirtyRegistry.isDirty()) {+ throw new Error('editing the prefab would discard unsaved changes — save first, or pass discardChanges');+ }+ await ProjectStore.editPrefabOfInstance(entity, { discardChanges: true });+ const doc = documentState();+ if (doc.kind !== 'prefab') {+ throw new Error(+ 'the prefab did not open — a NESTED prefab, or a variant whose base is not flat, is refused in Prefab Mode',+ );+ }+ return doc;+ },+ /** Push an instance's overrides back into its prefab asset (the Outliner's "Apply+ * to Prefab"), rewriting the base for EVERY instance. `confirm` must be true: a+ * person sees an itemized diff first, so a driver states the intent instead. */+ applyPrefab: async (entity: number, confirm: boolean) => {+ requireInstance(entity);+ if (confirm !== true) {+ throw new Error(+ 'apply rewrites the shared prefab for every instance — pass confirm: true to commit. '+ + 'get_inspector on the instance lists what would be baked in (overridden fields are marked).',+ );+ }+ return ProjectStore.applyPrefabInstance(entity, { skipPreview: true });+ },+ /** Discard an instance's overrides and re-sync it to its prefab (the Outliner's+ * "Revert to Prefab"). Returns the fresh instance root's source id. */+ revertPrefab: async (entity: number) => {+ requireInstance(entity);+ return ProjectStore.revertPrefabInstance(entity);+ },+ /** Detach an instance: its entities become ordinary scene entities and lose every+ * prefab link (the Outliner's "Unpack Prefab"). Undoable. */+ unpackPrefab: (entity: number) => {+ requireInstance(entity);+ SceneCommands.unpackPrefabInstance(entity);+ },+ /** Save a new `.esprefab` that inherits the instance's prefab and bakes in its+ * overrides (the Outliner's "Create Variant"), then re-link the instance to it. */+ createPrefabVariant: async (entity: number) => {+ requireInstance(entity);+ return ProjectStore.createVariantFromInstance(entity);},reveal: (id: string) => dockApi.revealAndExpand(id),/** Open a registered panel by id, docking it where its def says (reveal onlydiff --git a/desktop/src/project/ProjectStore.ts b/desktop/src/project/ProjectStore.tsindex 6e5932cd7..9d4527a70 100644--- a/desktop/src/project/ProjectStore.ts+++ b/desktop/src/project/ProjectStore.ts@@ -1196,13 +1196,13 @@ class ProjectStoreImpl {* guard + flat-only refusal. No-op if the entity isn't a prefab instance or its* asset can't be resolved.*/- async editPrefabOfInstance(id: number): Promise<void> {+ async editPrefabOfInstance(id: number, opts?: { discardChanges?: boolean }): Promise<void> {const tag = SceneModel.prefabTag(id);const ref = tag?.prefab ?? (tag ? SceneModel.prefabTag(tag.instanceRoot)?.prefab : undefined);if (!ref) return;const info = this.assetInfo(ref);if (!info) return;- await this.openPrefab(info.path);+ await this.openPrefab(info.path, opts);}/**@@ -1244,8 +1244,12 @@ class ProjectStoreImpl {* override, and baking them would strip the prefab's own metadata. Live* propagation to *other* in-scene instances still isn't immediate; those* siblings re-derive from the new base on next load.+ *+ * `skipPreview` commits without the diff dialog — for a caller that has already+ * stated the intent in the call itself (the MCP door makes that explicit) rather+ * than a click that needs one last look at what it is about to rewrite.*/- async applyPrefabInstance(sourceId: number): Promise<number | null> {+ async applyPrefabInstance(sourceId: number, opts?: { skipPreview?: boolean }): Promise<number | null> {const tag = SceneModel.prefabTag(sourceId);const instanceRoot = tag?.instanceRoot ?? sourceId;const ref = SceneModel.prefabTag(instanceRoot)?.prefab;@@ -1296,8 +1300,10 @@ class ProjectStoreImpl {const nameByPrefabId = new Map(processed.map((e) => [e.prefabEntityId, e.name]));const nameOf = (id: string): string =>nameByPrefabId.get(id) ?? oldPrefab.entities.find((e) => e.prefabEntityId === id)?.name ?? id;- const ok = await previewApply(name, { overrides, added, removed }, nameOf);- if (!ok) return instanceRoot;+ if (!opts?.skipPreview) {+ const ok = await previewApply(name, { overrides, added, removed }, nameOf);+ if (!ok) return instanceRoot;+ }const newPrefab = applyDeltaToSource(oldPrefab, { overrides, added, removed });@@ -2257,12 +2263,16 @@ class ProjectStoreImpl {* base into a variant delta, preserving basePrefab). Nested prefabs — and* variants of a nested / variant base — are still refused (re-nesting on save* is unsolved). The caller guards unsaved changes.+ *+ * `discardChanges` skips the unsaved-changes prompt — for a caller that already+ * decided (the automation door says it in the call). Without it a programmatic+ * open puts up a modal with nobody there to answer, which never resolves.*/- async openPrefab(path: string): Promise<void> {+ async openPrefab(path: string, opts?: { discardChanges?: boolean }): Promise<void> {const st = this.state;if (!st) return;const leaf = path.split('/').pop() ?? path;- if (!(await confirmDiscard(t('discard.openPrefab', { name: leaf })))) return;+ if (!opts?.discardChanges && !(await confirmDiscard(t('discard.openPrefab', { name: leaf })))) return;const uuid = this.pathToUuid.get(path);const ref = uuid ? UUID_PREFIX + uuid : null;const prefab = ref ? await this.loadPrefabAsset(ref) : null;@@ -2450,10 +2460,11 @@ class ProjectStoreImpl {}/** Leave Prefab Mode and return to the scene that was open (or a blank one),- * restoring the editor view the user left it at. */- async exitPrefabMode(): Promise<void> {+ * restoring the editor view the user left it at. `discardChanges` skips the+ * unsaved-changes prompt (see {@link openPrefab}). */+ async exitPrefabMode(opts?: { discardChanges?: boolean }): Promise<void> {if (!this.prefabSession) return;- if (!(await confirmDiscard(t('discard.exitPrefab')))) return;+ if (!opts?.discardChanges && !(await confirmDiscard(t('discard.exitPrefab')))) return;const { returnScene: back, returnView, returnSelection } = this.prefabSession;this.prefabSession = null;const st = this.state;diff --git a/desktop/src/project/assetOpen.ts b/desktop/src/project/assetOpen.tsindex fa01ab0d8..94e714cc1 100644--- a/desktop/src/project/assetOpen.ts+++ b/desktop/src/project/assetOpen.ts@@ -74,6 +74,16 @@ async function openOutside(type: AssetType, path: string): Promise<void> {});}+/**+ * Whether the EDITOR itself opens this type — a built-in editor below, or a+ * contributed type that brought its own action. False means a double-click ends up+ * in {@link openOutside}, handing the file to a program outside the editor: fine for+ * a person who asked for it, not something a driver should be able to trigger.+ */+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>> = {scene: async (path, name) => {diff --git a/desktop/tests/editor-control-surface.test.ts b/desktop/tests/editor-control-surface.test.tsindex 0b9f5f842..cd441a460 100644--- a/desktop/tests/editor-control-surface.test.ts+++ b/desktop/tests/editor-control-surface.test.ts@@ -96,6 +96,24 @@ describe.skipIf(!HAS_WASM)('EditorControlSurface (headless World)', () => {expect(host.world.has(S.model.runtimeFor(id)!, Sprite)).toBe(true);});+ it('getEntity reports the prefab link, so an instance is not indistinguishable from any entity', () => {+ const prefab = migratePrefabData({+ version: '1.0', name: 'Coin', rootEntityId: 'root',+ entities: [+ { prefabEntityId: 'root', name: 'Coin', parent: null, children: ['art'], components: [{ type: 'Transform', data: {} }], visible: true },+ { prefabEntityId: 'art', name: 'Art', parent: 'root', children: [], components: [{ type: 'Transform', data: {} }, { type: 'Sprite', data: {} }], visible: true },+ ],+ }).data as PrefabData;+ const root = S.surface.create(prefab, { parent: null, linkPrefabRef: '@uuid:coin-uuid' })!;+ const child = S.surface.getSceneTree()[0].children![0].id;++ // The root carries the asset ref; a member resolves it through its instance root.+ expect(S.surface.getEntity(root)?.prefab).toMatchObject({ ref: '@uuid:coin-uuid', isRoot: true, instanceRoot: root });+ expect(S.surface.getEntity(child)?.prefab).toMatchObject({ ref: '@uuid:coin-uuid', isRoot: false, instanceRoot: root });+ // An ordinary entity says nothing at all — absent, not a false link.+ expect(S.surface.getEntity(S.surface.addEntity()!)?.prefab).toBeUndefined();+ });+it('setField writes a component field; surface undo reverts it', () => {const id = S.surface.addEntity()!; // source idconst e = S.model.runtimeFor(id)!; // runtime World entitydiff --git a/desktop/tests/editor-mcp-tools.test.ts b/desktop/tests/editor-mcp-tools.test.tsindex fe83fb4ff..306554ef2 100644--- a/desktop/tests/editor-mcp-tools.test.ts+++ b/desktop/tests/editor-mcp-tools.test.ts@@ -215,3 +215,52 @@ describe('open_scene guards unsaved work', () => {expect(res.content[0].text).toMatch(/unsaved changes/);});});++describe('the prefab-mode doors', () => {+ const tool = (name: string) => TOOLS.find((t: { name: string }) => t.name === name);+ const jsDriver = () => {+ const js = vi.fn().mockResolvedValue(undefined);+ return Object.assign(vi.fn(), { js });+ };++ it('open_asset carries the path and the discard flag, refusing by default', async () => {+ const driver = jsDriver();+ await runTool(tool('open_asset'), driver, { path: 'assets/prefabs/Panel.esprefab' });+ expect(driver.js).toHaveBeenCalledWith(expect.stringContaining('openAsset("assets/prefabs/Panel.esprefab", false)'));++ driver.js.mockClear();+ await runTool(tool('open_asset'), driver, { path: 'assets/prefabs/Panel.esprefab', discardChanges: true });+ expect(driver.js).toHaveBeenCalledWith(expect.stringContaining(', true)'));+ });++ it('apply_prefab cannot be called without saying confirm out loud', async () => {+ const driver = jsDriver();+ // `confirm` is required by the schema: an omission never reaches the editor.+ const res = await runTool(tool('apply_prefab'), driver, { entity: 7 });+ expect(res.isError).toBe(true);+ expect(driver.js).not.toHaveBeenCalled();++ // Present but false still reaches the editor, which refuses there (one place+ // owns the rule) — what must not happen is a silent apply.+ await runTool(tool('apply_prefab'), driver, { entity: 7, confirm: false });+ expect(driver.js).toHaveBeenCalledWith(expect.stringContaining('applyPrefab(7, false)'));+ });++ it('every prefab door that rewrites an asset or the scene is write-gated', () => {+ for (const name of ['apply_prefab', 'revert_prefab', 'unpack_prefab', 'create_prefab_variant']) {+ expect(tool(name).write).toBe(true);+ }+ // Reading the document and leaving Prefab Mode write nothing.+ expect(tool('get_document').write).toBeUndefined();+ expect(tool('exit_prefab_mode').write).toBeUndefined();+ });++ it('surfaces the "not an instance" refusal instead of a silent no-op', async () => {+ const driver = Object.assign(vi.fn(), {+ js: vi.fn().mockRejectedValue(new Error('entity 3 is not part of a prefab instance')),+ });+ const res = await runTool(tool('unpack_prefab'), driver, { entity: 3 });+ expect(res.isError).toBe(true);+ expect(res.content[0].text).toMatch(/not part of a prefab instance/);+ });+});diff --git a/docs/astro/src/content/docs/guides/mcp.mdx b/docs/astro/src/content/docs/guides/mcp.mdxindex 58f88a9bf..3b89bda6d 100644--- a/docs/astro/src/content/docs/guides/mcp.mdx+++ b/docs/astro/src/content/docs/guides/mcp.mdx@@ -10,7 +10,7 @@ tool — Claude Code, Cursor, or your own agent — can drive the real editor: ocreate projects, open scenes, spawn entities from the same Create-menu catalog youuse, edit component fields, verify the result in the live engine World, enter playmode, take screenshots to *see* what it built, and export the finished game — the-exact pipelines the UI uses, fifty-four tools in all.+exact pipelines the UI uses, sixty-five tools in all.<Aside type="tip">Everything an agent does goes through the editor's own command surface — creates@@ -96,7 +96,8 @@ reconnects automatically rather than stranding the agent.| --- | --- || Observe | `get_scene_tree`, `get_inspector`, `get_stats`, `get_diagnostics`, `capture_viewport` (PNG), `screenshot` (whole window, includes play), `world_component` (live-World probe) || Edit scenes | `apply_scene_ops` (batch authoring), `create_entity` (the Create-menu catalog via `list_entity_templates`), `set_field`, `set_entity_xy`, `set_parent`, `duplicate_entity`, `undo` / `redo` |-| Projects & assets | `create_project` / `open_project`, `open_scene`, `save_scene`, `create_scene_file`, `create_asset`, `import_assets`, `list_assets`, `get_import_settings` / `set_import_settings` |+| Projects & assets | `create_project` / `open_project`, `open_scene`, `open_asset` (any asset in its own editor), `get_document`, `save_scene`, `create_scene_file`, `create_asset`, `import_assets`, `list_assets`, `get_import_settings` / `set_import_settings` |+| Prefabs | `create_prefab_from_entity`, `edit_prefab` / `exit_prefab_mode` (Prefab Mode), `apply_prefab`, `revert_prefab`, `unpack_prefab`, `create_prefab_variant` || Game code | `read_project_file`, `write_project_file`, `list_project_files` || Run & ship | `toggle_play` + `get_play_state`, `export_game` (web / desktop / wechat / playable) |@@ -104,6 +105,18 @@ A typical agent loop: `open_project` → `open_scene` → `list_entity_templates`apply_scene_ops` → `get_diagnostics` → `screenshot` to check its work →`save_scene` → `toggle_play` → `screenshot` again → `export_game`.+### Editing a prefab++`open_asset` on a `.esprefab` (or `edit_prefab` on an instance) enters **Prefab Mode**:+from then on every scene tool acts on the **prefab**, and `save_scene` writes the asset+for every instance. `get_document` says which document is open — check it after opening,+and before assuming a save writes a scene. `exit_prefab_mode` goes back.++Where a person gets a dialog, an agent gets an answer it can act on: opening something+that would discard unsaved work is **refused** unless you pass `discardChanges`, and+`apply_prefab` — which rewrites the base for every instance — requires `confirm: true`+instead of the itemized diff a person confirms.+### Building scenes at scale`set_field` writes one field per call, which is fine for a tweak and hopeless for adiff --git a/docs/astro/src/content/docs/zh-cn/guides/mcp.mdx b/docs/astro/src/content/docs/zh-cn/guides/mcp.mdxindex 45edd6fe6..4da6fcde1 100644--- a/docs/astro/src/content/docs/zh-cn/guides/mcp.mdx+++ b/docs/astro/src/content/docs/zh-cn/guides/mcp.mdx@@ -9,7 +9,7 @@ Estella 编辑器支持 **Model Context Protocol (MCP)**。任何支持 MCP 的Claude Code、Cursor,或你自己写的代理——都能驱动真实的编辑器:打开或创建项目、打开场景、用与你相同的"创建"菜单目录生成实体、编辑组件字段、在活的引擎 World里验证结果、进入 Play 模式、截图*亲眼看到*它搭出来的东西,并把成品游戏导出-——走的都是 UI 自己的管线,共 54 个工具。+——走的都是 UI 自己的管线,共 65 个工具。<Aside type="tip">代理做的每件事都经过编辑器自己的命令面——创建可撤销、Play 模式不会弄脏编辑@@ -89,7 +89,8 @@ claude mcp add estella --env ESTELLA_MCP_ALLOW_WRITES=1 -- \| --- | --- || 观察 | `get_scene_tree`、`get_inspector`、`get_stats`、`get_diagnostics`、`capture_viewport`(PNG)、`screenshot`(整窗截图,含 Play 画面)、`world_component`(活 World 探针) || 编辑场景 | `apply_scene_ops`(批量搭建)、`create_entity`(配合 `list_entity_templates` 的创建目录)、`set_field`、`set_entity_xy`、`set_parent`、`duplicate_entity`、`undo` / `redo` |-| 项目与资产 | `create_project` / `open_project`、`open_scene`、`save_scene`、`create_scene_file`、`create_asset`、`import_assets`、`list_assets`、`get_import_settings` / `set_import_settings` |+| 项目与资产 | `create_project` / `open_project`、`open_scene`、`open_asset`(把任意资产在它自己的编辑器里打开)、`get_document`、`save_scene`、`create_scene_file`、`create_asset`、`import_assets`、`list_assets`、`get_import_settings` / `set_import_settings` |+| 预制体 | `create_prefab_from_entity`、`edit_prefab` / `exit_prefab_mode`(Prefab Mode)、`apply_prefab`、`revert_prefab`、`unpack_prefab`、`create_prefab_variant` || 游戏代码 | `read_project_file`、`write_project_file`、`list_project_files` || 运行与发布 | `toggle_play` + `get_play_state`、`export_game`(web / desktop / wechat / playable) |@@ -97,6 +98,17 @@ claude mcp add estella --env ESTELLA_MCP_ALLOW_WRITES=1 -- \`apply_scene_ops` → `get_diagnostics` → `screenshot` 检查成果 → `save_scene` →`toggle_play` → 再次 `screenshot` → `export_game`。+### 编辑预制体++对 `.esprefab` 调 `open_asset`(或对实例调 `edit_prefab`)就进入 **Prefab Mode**:+从此每个场景工具作用的都是**那个预制体**,`save_scene` 写的是资产——每个实例都会跟着变。+`get_document` 告诉你当前开着哪个文档:打开之后先查它,别默认保存写的是场景。+`exit_prefab_mode` 回到原来的场景。++人看到对话框的地方,代理拿到的是能据此行动的答复:会丢掉未保存改动的打开一律**被拒绝**,+除非你传 `discardChanges`;而 `apply_prefab`(它会重写每个实例的基)要求 `confirm: true`+——人是靠那张逐条 diff 确认的,代理则把意图直接说出来。+### 规模化搭建场景`set_field` 一次只写一个字段——改一个值够用,搭一个场景就没戏了:一个 UI 面板