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): an agent can build a scene, not just poke at one
yhh1da847064b68
diff --git a/desktop/scripts/editor-mcp-tools.mjs b/desktop/scripts/editor-mcp-tools.mjsindex 402312d6c..223d75141 100644--- a/desktop/scripts/editor-mcp-tools.mjs+++ b/desktop/scripts/editor-mcp-tools.mjs@@ -112,6 +112,10 @@ export const TOOLS = [{ name: 'select',description: 'Select an entity (id=null clears the selection).',schema: obj({ id: { type: ['number', 'null'] } }, ['id']), method: 'select', args: (i) => [i.id] },+ { name: 'select_asset',+ description: "Select an asset by project-relative path — what clicking it in the Content Browser does. The Details panel then shows that asset's inspector (import settings, previews, the 9-slice border editor for textures). Pass null to clear.",+ schema: obj({ path: { type: ['string', 'null'] } }, ['path']),+ method: 'selectAsset', args: (i) => [i.path], root: 'editor' },{ name: 'get_selection',description: 'The primary selected entity id, or null.',schema: obj({}), method: 'getSelection', args: () => [] },@@ -128,9 +132,16 @@ export const TOOLS = [schema: obj({ frames: { type: 'number' }, dt: { type: 'number' } }),method: 'step', args: (i) => [i.frames, i.dt] },{ name: 'resize_viewport',- description: 'Resize the render canvas (the engine follows on the next stepped frame).',+ description: "Resize the render canvas's DRAWING BUFFER — the resolution the engine renders and capture_viewport reads. The engine follows on the next stepped frame. "+ + 'In the LIVE editor the canvas is laid out by its panel, so the next layout pass re-derives this from the panel size; to size the live viewport, use set_panel_size instead.',schema: obj({ width: { type: 'number' }, height: { type: 'number' } }, ['width', 'height']),method: 'resizeViewport', args: (i) => [i.width, i.height] },+ { name: 'set_panel_size', write: true,+ description: "Resize a docked panel (id: viewport, log, outliner, details, content...) — the live editor's real sizing door. The viewport canvas follows layout, so this is how you give the LIVE viewport a chosen size before a screenshot.",+ schema: obj({+ id: { type: 'string' }, width: { type: 'number' }, height: { type: 'number' },+ }, ['id']),+ method: 'setPanelSize', args: (i) => [i.id, { width: i.width, height: i.height }], root: 'editor' },{ name: 'capture_viewport',description: 'Render the current viewport and return it as a PNG image, so you can SEE what the editor drew. Step first for a settled frame.',schema: obj({}), js: () => CAPTURE_PNG_JS, image: true },@@ -188,6 +199,51 @@ export const TOOLS = [['destDir', 'sources']),js: (i) => `window.estella.project.importFiles(${JSON.stringify(i.destDir)}, ${JSON.stringify(i.sources)}).then((r) => window.__estellaEditor.refreshAssets().then(() => r))` },+ { name: 'apply_scene_ops', write: true,+ description: 'Author a whole subtree in ONE undoable batch — the tool to build scenes with (set_field one field per call does not scale past a few dozen nodes). '+ + '`ops` is an array executed in order, atomically: a throw anywhere rolls the WHOLE batch back. Op shapes: '+ + '{op:"create", ref?, name?, parent?, template?, components?, fields?, x?, y?} — `template` is an entity-template id (list_entity_templates, e.g. "ui-image"), '+ + 'or give `components` as ["Transform","UINode","UIVisual"] / [{type,data}]; '+ + '{op:"set", entity, fields}; {op:"add_component"|"remove_component", entity, component}; {op:"rename", entity, name}; {op:"parent", entity, parent}; {op:"delete", entity}. '+ + 'ENTITY ADDRESSING: an entity is a live numeric id, or "$name" naming an earlier create\'s `ref` — so a parent/child tree is one call with no round trip to learn ids. '+ + 'FIELDS is a flat map of "Component.key" → value, e.g. {"Transform.position.x": 10, "UIVisual.color": "#ff0000ff", "Text.content": "Hi"} — same coercion and validation as set_field. '+ + 'Returns { refs: {name: id}, created: [id], applied: n }. Check get_diagnostics afterwards.',+ schema: obj({+ ops: { type: 'array', description: 'the op program, executed in order as one undo step' },+ label: { type: 'string', description: 'undo-stack label (default "Apply scene ops")' },+ }, ['ops']),+ method: 'applyOps', args: (i) => [i.ops, i.label], root: 'editor' },+ { name: 'list_assets',+ description: 'Search the open project\'s asset registry. `match` is a case-insensitive SUBSTRING of the project-relative path (not a glob); `type` filters by asset type (texture, scene, prefab, audio, font, material, shader...). '+ + 'Returns { total, assets: [{ ref, path, name, type }] } — `total` is the full match count, `assets` is capped by `limit` (default 200). The `ref` is the stable @uuid: form to write into asset fields.',+ schema: obj({+ match: { type: 'string' }, type: { type: 'string' }, limit: { type: 'number' },+ }),+ method: 'listAssets', args: (i) => [{ match: i.match, type: i.type, limit: i.limit }], root: 'editor' },+ { name: 'get_import_settings',+ description: "An asset's .meta import settings, layered over its type's defaults — the Import Settings panel's data. Returns { type, settings }.",+ schema: obj({ path: { type: 'string' } }, ['path']),+ method: 'getImportSettings', args: (i) => [i.path], root: 'editor' },+ { name: 'set_import_settings', write: true,+ description: 'Patch an asset\'s .meta import settings and persist. Keys are DOTTED paths into the importer block, matching the inspector field keys — a texture\'s 9-slice border is '+ + '{"sliceBorder.left":12,"sliceBorder.right":12,"sliceBorder.top":12,"sliceBorder.bottom":12}; filter/wrap are {"filterMode":"nearest","wrapMode":"clamp"}. '+ + 'These live in IMPORT, not on a component: a UIVisual set to NineSlice takes its border from texture metadata, so this is what makes frames and buttons stretch correctly. '+ + 'Re-registers the asset and updates the live texture. Returns the resulting importer block.',+ schema: obj({ path: { type: 'string' }, patch: { type: 'object' } }, ['path', 'patch']),+ method: 'setImportSettings', args: (i) => [i.path, i.patch], root: 'editor' },+ { name: 'read_project_file',+ description: 'Read a text file by project-relative path — game scripts (src/*.ts), project.esproject, .meta files, any project text. Complements get_inspector: scenes are model state, behaviour is code.',+ schema: obj({ path: { type: 'string' } }, ['path']),+ js: (i) => `window.estella.fs.read(${JSON.stringify(i.path)})` },+ { name: 'write_project_file', write: true,+ description: 'Write a text file by project-relative path, CREATING or OVERWRITING it. This is how game scripts (src/*.ts) are authored — create_asset only makes .meta-carrying asset types and refuses to overwrite (it uniquifies to "name 2"). '+ + 'Writing project sources does not itself rebuild them; the editor picks the change up through its file watcher.',+ schema: obj({ path: { type: 'string' }, content: { type: 'string' } }, ['path', 'content']),+ js: (i) => `window.estella.fs.write(${JSON.stringify(i.path)}, ${JSON.stringify(i.content)})` },+ { name: 'list_project_files',+ description: 'Project-relative paths of every file under a project-relative directory (recursive). Use for source trees (src/) where list_assets — which only knows registered assets — sees nothing.',+ schema: obj({ dir: { type: 'string' } }, ['dir']),+ js: (i) => `window.estella.fs.listFiles(${JSON.stringify(i.dir)})` },{ name: 'set_project_physics', write: true,description: 'Patch the project physics feature (Project Settings → Physics), e.g. { "enabled": true }. Persists to the manifest; Play and exports boot it.',schema: obj({ patch: { type: 'object' } }, ['patch']),diff --git a/desktop/scripts/editor-mcp.mjs b/desktop/scripts/editor-mcp.mjsindex 70c9f2ca1..037694108 100644--- a/desktop/scripts/editor-mcp.mjs+++ b/desktop/scripts/editor-mcp.mjs@@ -14,9 +14,12 @@* In the dev repo this is `electron .`; from the installed* editor (this file ships bundled under app.asar.unpacked)* the exe is auto-detected, or pass --editor-exe <path>.- * --attach <file> connect to an already-running editor's endpoint via its+ * --attach [file] connect to an already-running editor's endpoint via its* discovery file (<userData>/mcp-endpoint.json) — drive the- * editor the user is looking at+ * editor the user is looking at. The path is optional: the+ * standard userData locations are probed. Resolution is+ * LAZY and re-done per call, so this server starts before+ * the editor does and survives an editor restart.** Split on purpose: an Electron main process never receives piped stdin on* Windows, so the MCP protocol must live in a plain-node process. The surface@@ -29,6 +32,7 @@import { spawn } from 'node:child_process';import { randomBytes } from 'node:crypto';import { existsSync, readFileSync } from 'node:fs';+import os from 'node:os';import path from 'node:path';import { createRequire } from 'node:module';import { fileURLToPath } from 'node:url';@@ -129,41 +133,93 @@ function spawnHost(mode, token) {});}-let port;-let token;-if (MODE === 'attach') {- // Connect to a running editor via its discovery file (written in --mcp mode).- const fileArg = argv[argv.indexOf('--attach') + 1];- const discovery = fileArg && !fileArg.startsWith('--') ? fileArg : process.env.ESTELLA_MCP_DISCOVERY;- if (!discovery) {- log('FATAL: --attach needs the discovery file path (<userData>/mcp-endpoint.json) or ESTELLA_MCP_DISCOVERY');- process.exit(1);- }- try {- ({ port, token } = JSON.parse(readFileSync(discovery, 'utf8')));- } catch (e) {- log(`FATAL: cannot read discovery file ${discovery}: ${e.message}`);- process.exit(1);+/** Where a `--mcp` editor advertises its endpoint. Electron's userData is+ * <appData>/<app name>: the dev app takes it from package.json (`@estella/editor`),+ * the installed one from electron-builder's productName (`Estella Editor`). */+function attachCandidates() {+ const explicit = argValue('--attach') ?? process.env.ESTELLA_MCP_DISCOVERY;+ if (explicit) return [explicit];+ const appData = process.platform === 'win32'+ ? (process.env.APPDATA ?? path.join(os.homedir(), 'AppData', 'Roaming'))+ : process.platform === 'darwin'+ ? path.join(os.homedir(), 'Library', 'Application Support')+ : (process.env.XDG_CONFIG_HOME ?? path.join(os.homedir(), '.config'));+ return [path.join('@estella', 'editor'), 'Estella Editor']+ .map((dir) => path.join(appData, dir, 'mcp-endpoint.json'));+}++/** The live endpoint from the first discovery file whose editor is still running,+ * or null. A crashed editor leaves its file behind, so the recorded pid is the+ * liveness check — attaching to a dead port would hang every call instead. */+function readEndpoint() {+ for (const file of attachCandidates()) {+ if (!existsSync(file)) continue;+ try {+ const { port: p, token: t, pid } = JSON.parse(readFileSync(file, 'utf8'));+ if (!p || !t) continue;+ if (pid) {+ try { process.kill(pid, 0); } catch { continue; } // stale file, editor is gone+ }+ return { port: p, token: t, file };+ } catch { /* torn or unreadable write — try the next candidate */ }}+ return null;+}++let endpoint = null;+if (MODE === 'attach') {+ // Resolution is deliberately LAZY: this server is spawned by the MCP client at+ // session start, typically BEFORE the user's editor is up. Failing here would+ // make attach mode unusable, so resolve per call instead — which also means an+ // editor restart (new port + token) is picked up without restarting the client.+ endpoint = readEndpoint();+ log(endpoint+ ? `attached to editor on 127.0.0.1:${endpoint.port} (${endpoint.file})`+ : `no editor yet — will attach on first call (looking for ${attachCandidates().join(' | ')})`);} else {- token = randomBytes(24).toString('hex');- port = await spawnHost(MODE, token).catch((e) => {+ const token = randomBytes(24).toString('hex');+ const port = await spawnHost(MODE, token).catch((e) => {log('FATAL', e.message);process.exit(1);});+ endpoint = { port, token };}process.stdin.on('close', () => process.exit(0));-log(`${MODE} host ready on 127.0.0.1:${port} (writes ${ALLOW_WRITES ? 'ENABLED' : 'disabled'})`);+log(`${MODE} host ready (writes ${ALLOW_WRITES ? 'ENABLED' : 'disabled'})`);++/** The endpoint to talk to, re-resolving in attach mode when we have none. */+function currentEndpoint() {+ if (!endpoint && MODE === 'attach') endpoint = readEndpoint();+ if (!endpoint) {+ throw new Error(+ 'no running editor to attach to — start the Estella editor with --mcp '+ + `(looked for ${attachCandidates().join(' | ')})`,+ );+ }+ return endpoint;+}async function post(body) {- const res = await fetch(`http://127.0.0.1:${port}/exec`, {- method: 'POST',- headers: { 'content-type': 'application/json', 'x-estella-mcp-token': token },- body: JSON.stringify(body),- });- const out = await res.json();- if (!out.ok) throw new Error(out.error);- return out.hasResult ? out.result : undefined;+ // A transport failure means the editor went away (restart/quit), not a tool+ // error: drop the cached endpoint and re-resolve once before giving up.+ for (let attempt = 0; ; attempt++) {+ const { port, token } = currentEndpoint();+ let res;+ try {+ res = await fetch(`http://127.0.0.1:${port}/exec`, {+ method: 'POST',+ headers: { 'content-type': 'application/json', 'x-estella-mcp-token': token },+ body: JSON.stringify(body),+ });+ } catch (e) {+ endpoint = MODE === 'attach' && attempt === 0 ? readEndpoint() : null;+ if (endpoint) continue; // editor restarted on a new port+ throw new Error(`editor endpoint unreachable on 127.0.0.1:${port} (${e.message})`);+ }+ const out = await res.json();+ if (!out.ok) throw new Error(out.error);+ return out.hasResult ? out.result : undefined;+ }}// The registry's driver: surface/editor method calls, renderer-code snippets,diff --git a/desktop/src/engine/sceneOps.ts b/desktop/src/engine/sceneOps.tsnew file mode 100644index 000000000..a9f004291--- /dev/null+++ b/desktop/src/engine/sceneOps.ts@@ -0,0 +1,175 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file sceneOps.ts — batched scene authoring: many edits, one transaction.+ *+ * The per-field write door (EditorControlSurface.setField) is shaped for the UI,+ * where a human changes one value at a time. Authoring a SCENE that way — a UI+ * panel is easily a hundred nodes with a dozen fields each — costs thousands of+ * round trips through the automation boundary, and litters the undo stack with+ * one step per field.+ *+ * `applySceneOps` takes a program instead: a list of ops that create entities,+ * parent them, add components and set fields, executed as ONE undoable step.+ * Ops name entities they create with a `ref`, and later ops address them as+ * `"$ref"` — so a whole subtree is expressible in a single call without the+ * caller round-tripping to learn each new id.+ *+ * It adds no editing truth of its own: every mutation goes through the same+ * EditorControlSurface doors the UI uses (so validation, coercion and the+ * reconciler behave identically), and the whole program runs inside one+ * `transact` — a throw anywhere rolls the entire batch back rather than leaving+ * a half-built subtree behind.+ */+import type { EntityId } from '@/types';+import type { PrefabData } from 'esengine';+import { EditorControlSurface } from './EditorSession';+import { prefabFromSpecs, sourceById } from './entitySources';++/** An entity address: a live id, or `"$ref"` naming an entity an earlier op created. */+export type EntityRef = number | string;++/** A component to seed a created entity with: `"UINode"` or `{ type, data }`. */+export type ComponentSpec = string | { type: string; data?: Record<string, unknown> };++export type SceneOp =+ | {+ op: 'create';+ /** Name this entity so later ops can address it as `"$<ref>"`. */+ ref?: string;+ name?: string;+ parent?: EntityRef | null;+ /** An entity-template id (see listEntityTemplates), e.g. `ui-image`. */+ template?: string;+ /** Explicit component list — the alternative to `template`. */+ components?: ComponentSpec[];+ /** Field writes applied to the new entity, as in the `set` op. */+ fields?: Record<string, unknown>;+ x?: number;+ y?: number;+ }+ | { op: 'set'; entity: EntityRef; fields: Record<string, unknown> }+ | { op: 'add_component'; entity: EntityRef; component: string }+ | { op: 'remove_component'; entity: EntityRef; component: string }+ | { op: 'rename'; entity: EntityRef; name: string }+ | { op: 'parent'; entity: EntityRef; parent: EntityRef | null }+ | { op: 'delete'; entity: EntityRef };++export interface SceneOpsResult {+ /** ref name → the entity id it was bound to. */+ refs: Record<string, EntityId>;+ /** Ids created by this batch, in creation order. */+ created: EntityId[];+ /** How many ops ran. */+ applied: number;+}++/**+ * Split a `"Component.key"` field path. Component names never contain a dot, but+ * keys do (`Transform.position.x`), so only the FIRST dot separates them.+ */+function splitFieldPath(path: string): { component: string; key: string } {+ const dot = path.indexOf('.');+ if (dot <= 0 || dot === path.length - 1) {+ throw new Error(`field "${path}" must be "Component.key" (e.g. "Transform.position.x")`);+ }+ return { component: path.slice(0, dot), key: path.slice(dot + 1) };+}++/**+ * Run `ops` as one undoable batch and return the ref bindings.+ *+ * Template lookups happen BEFORE the transaction because a template's `build`+ * may be async (prefab-backed widgets load their asset), while a transaction is+ * synchronous — resolving them up front keeps the mutation phase atomic.+ */+export async function applySceneOps(+ ops: readonly SceneOp[],+ label = 'Apply scene ops',+): Promise<SceneOpsResult> {+ if (!Array.isArray(ops)) throw new Error('applySceneOps: `ops` must be an array');++ // Phase 1 (async, no mutation): resolve every template to its PrefabData.+ const prefabs = new Map<string, PrefabData>();+ for (const op of ops) {+ if (op.op !== 'create' || !op.template || prefabs.has(op.template)) continue;+ const source = sourceById(op.template);+ if (!source?.build) throw new Error(`unknown entity template: ${op.template} (see listEntityTemplates)`);+ prefabs.set(op.template, await source.build({ parent: null }));+ }++ const refs: Record<string, EntityId> = {};+ const created: EntityId[] = [];++ const resolve = (ref: EntityRef | null | undefined, what: string): EntityId | null => {+ if (ref == null) return null;+ if (typeof ref === 'number') return ref as EntityId;+ const name = ref.startsWith('$') ? ref.slice(1) : ref;+ const id = refs[name];+ if (id == null) throw new Error(`${what} refers to unknown ref "${ref}" (defined so far: ${Object.keys(refs).join(', ') || 'none'})`);+ return id;+ };++ const setFields = (entity: EntityId, fields: Record<string, unknown>): void => {+ for (const [path, value] of Object.entries(fields)) {+ const { component, key } = splitFieldPath(path);+ // The declared inspector type wins inside setField; this argument is advisory.+ EditorControlSurface.setField(entity, component, key, 'string', value as never);+ }+ };++ // Phase 2 (sync): one transaction — a throw rolls the whole batch back.+ EditorControlSurface.transact(label, () => {+ ops.forEach((op, i) => {+ const at = `op[${i}] ${op.op}`;+ try {+ switch (op.op) {+ case 'create': {+ const parent = resolve(op.parent, at);+ const specs: ComponentSpec[] = op.components ?? ['Transform'];+ const prefab = op.template+ ? prefabs.get(op.template)!+ : prefabFromSpecs(+ op.name ?? 'Entity',+ specs.map((c) => (typeof c === 'string' ? { type: c } : c)),+ );+ const position = op.x != null && op.y != null ? { x: op.x, y: op.y } : undefined;+ const id = EditorControlSurface.create(prefab, { parent, position });+ if (id == null) throw new Error('entity creation returned no id');+ created.push(id);+ if (op.ref) refs[op.ref] = id;+ if (op.name) EditorControlSurface.renameEntity(id, op.name);+ if (op.fields) setFields(id, op.fields);+ break;+ }+ case 'set':+ setFields(resolve(op.entity, at)!, op.fields);+ break;+ case 'add_component':+ EditorControlSurface.addComponent(resolve(op.entity, at)!, op.component);+ break;+ case 'remove_component':+ EditorControlSurface.removeComponent(resolve(op.entity, at)!, op.component);+ break;+ case 'rename':+ EditorControlSurface.renameEntity(resolve(op.entity, at)!, op.name);+ break;+ case 'parent':+ EditorControlSurface.setParent(resolve(op.entity, at)!, resolve(op.parent, at));+ break;+ case 'delete':+ EditorControlSurface.deleteEntity(resolve(op.entity, at)!);+ break;+ default:+ throw new Error(`unknown op "${(op as { op: string }).op}"`);+ }+ } catch (e) {+ // Locate the failure for the caller: a 400-op program otherwise reports+ // only "component X is not on entity 12" with no clue which op wrote it.+ throw new Error(`${at}: ${(e as Error)?.message ?? String(e)}`);+ }+ });+ });++ return { refs, created, applied: ops.length };+}diff --git a/desktop/src/main.tsx b/desktop/src/main.tsxindex 47a3d3246..430c7c7e1 100644--- a/desktop/src/main.tsx+++ b/desktop/src/main.tsx@@ -53,6 +53,7 @@ import { applyFxPreview, initFxPreviewEditRestart } from './engine/fxPreview';import { commands } from './commands/registry';import { entitySources, sourceById, createFromSource, type TileGridConfig } from './engine/entitySources';import { createTilemapFromTileset, createCollisionLayer } from './tilemap/createTilemap';+import { applySceneOps, type SceneOp } from './engine/sceneOps';import { layerTilesetRefs, loadLayerTilesetModel } from './tilemap/layerTilesetModel';import { SceneCommands } from './engine/SceneCommands';import { useTilemapPaint } from './store/tilemapPaintStore';@@ -217,6 +218,25 @@ if (new URLSearchParams(location.search).has('automation')) {position: opts?.x != null && opts?.y != null ? { x: opts.x, y: opts.y } : undefined,});},+ /** Author a whole subtree in ONE undoable batch (create/parent/component/field+ * ops, with `"$ref"` addressing between them) — the door for scene authoring+ * at a scale where one-field-per-call is not viable. */+ applyOps: (ops: SceneOp[], label?: string) => applySceneOps(ops, label),+ /** Search the asset registry: case-insensitive substring over the project-relative+ * path, optional asset `type`, capped. A real project has thousands of assets, so+ * `total` reports the full match count even when `assets` is truncated. */+ listAssets: (opts?: { match?: string; type?: string; limit?: number }) => {+ const needle = opts?.match?.toLowerCase();+ const all = ProjectStore.listAssets().filter(+ (a) => (!opts?.type || a.type === opts.type) && (!needle || a.path.toLowerCase().includes(needle)),+ );+ return { total: all.length, assets: all.slice(0, opts?.limit ?? 200) };+ },+ /** An asset's `.meta` import settings, over its type's defaults. */+ getImportSettings: (path: string) => ProjectStore.getImportSettings(path),+ /** 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;diff --git a/desktop/src/project/ProjectStore.ts b/desktop/src/project/ProjectStore.tsindex 6281da279..af6dd5a7b 100644--- a/desktop/src/project/ProjectStore.ts+++ b/desktop/src/project/ProjectStore.ts@@ -2,7 +2,7 @@// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Teamimport { createStore } from 'zustand/vanilla';import { getComponent, getEditorType, Assets, migratePrefabData, extractPrefab, flattenPrefab, collectExternalEntityRefs, collapseInstance, applyDeltaToSource, buildVariant, validateOverrides, setTextureParams, TextureFilter, TextureWrap, Renderer, RETIRED_COMPONENT_TYPES, parseThemeOverrides, resolveAssetGroup, folderGroupMode, withFolderGroup, folderAlwaysInclude, withFolderAlwaysInclude, withActiveRemoteRoot } from 'esengine';-import { readTextureImportSettings } from './assetImporter';+import { readTextureImportSettings, importerDefaults, applyImporterEdit } from './assetImporter';import type { SceneData, PrefabData, ExtractEntity, ProcessedEntity, PhysicsPluginConfig, AudioProjectConfig, AssetsData, ThemeOverrides, StaleOverride, PrefabOverride, AddressableManifest, AssetGroupsConfig, AssetGroupMode } from 'esengine';import { EngineHost } from '@/engine/EngineHost';import { applyWidgetTheme } from '@/engine/widgetTheme';@@ -772,6 +772,49 @@ class ProjectStoreImpl {setTextureParams(handle, filter, filter, wrap, wrap);}+ /**+ * An asset's import settings: its `.meta` importer block layered over the+ * type's declared defaults, so a caller sees every knob (not just the ones+ * that happen to have been edited). `type` is the importer schema key —+ * `texture`, `audio`, `spine`, … — the vocabulary {@link setImportSettings}+ * writes against.+ */+ async getImportSettings(path: string): Promise<{ type: string; settings: Record<string, unknown> }> {+ const type = assetTypeOf(path.split('/').pop() ?? path);+ const stored = JSON.parse(await window.estella.fs.read(path + '.meta')).importer as+ | Record<string, unknown>+ | undefined;+ return { type, settings: { ...importerDefaults(type), ...(stored ?? {}) } };+ }++ /**+ * Patch an asset's `.meta` importer block and persist it — the programmatic+ * twin of the asset inspector's Import Settings panel, and the only way to+ * set things that live in import rather than on a component (a texture's+ * 9-slice border, a texture's filter/wrap, an audio stream flag).+ *+ * Keys are dotted paths into the block (`sliceBorder.left`), matching the+ * inspector's own field keys; the write goes through the same+ * {@link applyImporterEdit} the panel uses. Re-registers the asset and pushes+ * filter/wrap to the live texture handle so the viewport reflects it without+ * a scene reload. Returns the resulting block.+ */+ async setImportSettings(+ path: string,+ patch: Record<string, unknown>,+ ): Promise<Record<string, unknown>> {+ const meta = JSON.parse(await window.estella.fs.read(path + '.meta'));+ let importer = (meta.importer as Record<string, unknown>) ?? {};+ for (const [key, value] of Object.entries(patch)) {+ importer = applyImporterEdit(importer, key, value as never);+ }+ meta.importer = importer;+ await window.estella.fs.write(path + '.meta', JSON.stringify(meta, null, 2) + '\n');+ await this.refreshAssets();+ this.applyLiveTextureSettings(path);+ return importer;+ }+/** Resolve a serialized asset ref to a project-relative path for the engine* loader: a uuid ref (`@uuid:` or bare) → path (null if unknown); a plain* path passes through. */diff --git a/desktop/tests/editor-mcp-tools.test.ts b/desktop/tests/editor-mcp-tools.test.tsindex bd323c85d..628e5c2d7 100644--- a/desktop/tests/editor-mcp-tools.test.ts+++ b/desktop/tests/editor-mcp-tools.test.ts@@ -116,6 +116,50 @@ describe('editor MCP tool registry', () => {expect(res.content[0]).toEqual({ type: 'image', data: 'aWFtYXBuZw==', mimeType: 'image/png' });});+ it('apply_scene_ops forwards the op program to the editor door', async () => {+ const driver = vi.fn(async () => ({ refs: { root: 5 }, created: [5], applied: 1 }));+ const apply = TOOLS.find((t: { name: string }) => t.name === 'apply_scene_ops');+ const ops = [{ op: 'create', ref: 'root', name: 'Panel' }];+ const res = await runTool(apply, driver, { ops, label: 'Build' });+ expect(driver).toHaveBeenCalledWith('applyOps', [ops, 'Build'], 'editor');+ expect(JSON.parse(res.content[0].text).refs.root).toBe(5);+ });++ it('apply_scene_ops is a write tool and rejects a non-array program', async () => {+ const driver = vi.fn();+ const apply = TOOLS.find((t: { name: string }) => t.name === 'apply_scene_ops');+ expect(apply.write).toBe(true);+ const res = await runTool(apply, driver, { ops: 'create everything' });+ expect(res.isError).toBe(true);+ expect(driver).not.toHaveBeenCalled();+ });++ it('list_assets packs its filters into one options argument', async () => {+ const driver = vi.fn(async () => ({ total: 0, assets: [] }));+ const list = TOOLS.find((t: { name: string }) => t.name === 'list_assets');+ await runTool(list, driver, { match: 'Icon/', type: 'texture', limit: 20 });+ expect(driver).toHaveBeenCalledWith('listAssets', [{ match: 'Icon/', type: 'texture', limit: 20 }], 'editor');+ });++ it('set_import_settings passes the dotted patch through untouched', async () => {+ const driver = vi.fn(async () => ({ sliceBorder: { left: 12 } }));+ const set = TOOLS.find((t: { name: string }) => t.name === 'set_import_settings');+ const patch = { 'sliceBorder.left': 12, 'sliceBorder.right': 12 };+ await runTool(set, driver, { path: 'assets/ui/frame.png', patch });+ expect(driver).toHaveBeenCalledWith('setImportSettings', ['assets/ui/frame.png', patch], 'editor');+ });++ it('write_project_file targets the project fs door with an escaped payload', async () => {+ const driver = vi.fn() as unknown as { js: ReturnType<typeof vi.fn> } & ((...a: unknown[]) => unknown);+ driver.js = vi.fn(async () => undefined);+ const write = TOOLS.find((t: { name: string }) => t.name === 'write_project_file');+ await runTool(write, driver, { path: 'src/main.ts', content: 'const s = "hi";\n' });+ const code = driver.js.mock.calls[0][0];+ expect(code).toContain('window.estella.fs.write');+ // The content is JSON-encoded into the snippet — quotes/newlines must not break it.+ expect(code).toContain(JSON.stringify('const s = "hi";\n'));+ });+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);diff --git a/desktop/tests/scene-ops.test.ts b/desktop/tests/scene-ops.test.tsnew file mode 100644index 000000000..da5e6ad0f--- /dev/null+++ b/desktop/tests/scene-ops.test.ts@@ -0,0 +1,166 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file Regression net for applySceneOps — the batched scene-authoring door.+ *+ * sceneOps adds no editing truth: it is an interpreter that turns an op program+ * into calls on EditorControlSurface, inside one transaction. So the unit under+ * test is exactly that translation — ref addressing, "Component.key" splitting,+ * op ordering, and the failure contract (locate the op, roll the batch back).+ * The surface is a recording fake; the real one is covered by its own suite.+ */+import { describe, it, expect, beforeEach, vi } from 'vitest';++const calls = vi.hoisted(() => [] as Array<[string, ...unknown[]]>);+const state = vi.hoisted(() => ({ nextId: 100, createReturnsNull: false, throwOnField: '' }));++vi.mock('@/engine/EditorSession', () => ({+ EditorControlSurface: {+ transact: (label: string, fn: () => void) => {+ calls.push(['transact:begin', label]);+ try {+ fn();+ } catch (e) {+ calls.push(['transact:abort']);+ throw e;+ }+ calls.push(['transact:commit']);+ },+ create: (prefab: { name: string }, opts: { parent: number | null }) => {+ calls.push(['create', prefab.name, opts.parent]);+ return state.createReturnsNull ? null : state.nextId++;+ },+ setField: (entity: number, component: string, key: string, _t: string, value: unknown) => {+ if (state.throwOnField === `${component}.${key}`) throw new Error(`no field "${key}"`);+ calls.push(['setField', entity, component, key, value]);+ },+ renameEntity: (id: number, name: string) => calls.push(['rename', id, name]),+ addComponent: (id: number, c: string) => calls.push(['addComponent', id, c]),+ removeComponent: (id: number, c: string) => calls.push(['removeComponent', id, c]),+ setParent: (id: number, p: number | null) => calls.push(['setParent', id, p]),+ deleteEntity: (id: number) => calls.push(['delete', id]),+ },+}));++vi.mock('@/engine/entitySources', () => ({+ prefabFromSpecs: (name: string, specs: { type: string }[]) => ({ name, specs }),+ sourceById: (id: string) =>+ id === 'ui-image' ? { build: async () => ({ name: 'Image', specs: [] }) } : null,+}));++const { applySceneOps } = await import('@/engine/sceneOps');++beforeEach(() => {+ calls.length = 0;+ state.nextId = 100;+ state.createReturnsNull = false;+ state.throwOnField = '';+});++describe('applySceneOps', () => {+ it('runs the whole program inside ONE transaction', async () => {+ await applySceneOps([{ op: 'create' }, { op: 'create' }], 'Build panel');+ expect(calls[0]).toEqual(['transact:begin', 'Build panel']);+ expect(calls.at(-1)).toEqual(['transact:commit']);+ expect(calls.filter((c) => c[0] === 'transact:begin')).toHaveLength(1);+ });++ it('binds created entities to refs and resolves "$ref" as a parent', async () => {+ const res = await applySceneOps([+ { op: 'create', ref: 'root', name: 'Panel' },+ { op: 'create', ref: 'child', name: 'Label', parent: '$root' },+ ]);+ expect(res.refs).toEqual({ root: 100, child: 101 });+ expect(res.created).toEqual([100, 101]);+ expect(res.applied).toBe(2);+ expect(calls).toContainEqual(['create', 'Label', 100]);+ });++ it('accepts a live numeric id anywhere a ref is accepted', async () => {+ await applySceneOps([{ op: 'set', entity: 7, fields: { 'Text.content': 'hi' } }]);+ expect(calls).toContainEqual(['setField', 7, 'Text', 'content', 'hi']);+ });++ it('splits "Component.key" on the FIRST dot so nested keys survive', async () => {+ await applySceneOps([+ { op: 'set', entity: 1, fields: { 'Transform.position.x': 10, 'UIVisual.color': '#ff0000ff' } },+ ]);+ expect(calls).toContainEqual(['setField', 1, 'Transform', 'position.x', 10]);+ expect(calls).toContainEqual(['setField', 1, 'UIVisual', 'color', '#ff0000ff']);+ });++ it('rejects a field path that is not "Component.key"', async () => {+ await expect(applySceneOps([{ op: 'set', entity: 1, fields: { content: 'hi' } }]))+ .rejects.toThrow(/must be "Component.key"/);+ });++ it('builds from an explicit component list, defaulting to Transform', async () => {+ await applySceneOps([+ { op: 'create', name: 'Node', components: ['Transform', 'UINode', { type: 'UIVisual', data: { enabled: true } }] },+ { op: 'create', name: 'Bare' },+ ]);+ expect(calls).toContainEqual(['create', 'Node', null]);+ expect(calls).toContainEqual(['create', 'Bare', null]);+ });++ it('resolves an entity template before mutating, and rejects an unknown one', async () => {+ await applySceneOps([{ op: 'create', ref: 'img', template: 'ui-image', name: 'Icon' }]);+ expect(calls).toContainEqual(['create', 'Image', null]);+ expect(calls).toContainEqual(['rename', 100, 'Icon']);++ calls.length = 0;+ await expect(applySceneOps([{ op: 'create', template: 'nope' }])).rejects.toThrow(/unknown entity template/);+ // Rejected during the async resolve phase — nothing was mutated.+ expect(calls).toHaveLength(0);+ });++ it('applies create-time fields to the entity it just made', async () => {+ await applySceneOps([{ op: 'create', ref: 'n', fields: { 'Text.content': 'Alice' } }]);+ expect(calls).toContainEqual(['setField', 100, 'Text', 'content', 'Alice']);+ });++ it('dispatches the non-create ops to their surface doors', async () => {+ await applySceneOps([+ { op: 'add_component', entity: 5, component: 'UIVisual' },+ { op: 'remove_component', entity: 5, component: 'Sprite' },+ { op: 'rename', entity: 5, name: 'Renamed' },+ { op: 'parent', entity: 5, parent: null },+ { op: 'delete', entity: 5 },+ ]);+ expect(calls).toContainEqual(['addComponent', 5, 'UIVisual']);+ expect(calls).toContainEqual(['removeComponent', 5, 'Sprite']);+ expect(calls).toContainEqual(['rename', 5, 'Renamed']);+ expect(calls).toContainEqual(['setParent', 5, null]);+ expect(calls).toContainEqual(['delete', 5]);+ });++ it('locates the failing op and aborts the transaction (no half-built subtree)', async () => {+ state.throwOnField = 'Text.bogus';+ await expect(applySceneOps([+ { op: 'create', ref: 'a' },+ { op: 'set', entity: '$a', fields: { 'Text.bogus': 1 } },+ ])).rejects.toThrow(/op\[1\] set: no field "bogus"/);+ expect(calls).toContainEqual(['transact:abort']);+ expect(calls).not.toContainEqual(['transact:commit']);+ });++ it('names the unknown ref and what was defined so far', async () => {+ await expect(applySceneOps([+ { op: 'create', ref: 'a' },+ { op: 'create', parent: '$missing' },+ ])).rejects.toThrow(/unknown ref "\$missing" \(defined so far: a\)/);+ });++ it('fails loudly when entity creation returns no id', async () => {+ state.createReturnsNull = true;+ await expect(applySceneOps([{ op: 'create' }])).rejects.toThrow(/op\[0\] create: entity creation returned no id/);+ });++ it('rejects an unknown op name', async () => {+ await expect(applySceneOps([{ op: 'frobnicate' } as never])).rejects.toThrow(/unknown op "frobnicate"/);+ });++ it('rejects a non-array program', async () => {+ await expect(applySceneOps('nope' as never)).rejects.toThrow(/must be an array/);+ });+});diff --git a/docs/astro/src/content/docs/guides/mcp.mdx b/docs/astro/src/content/docs/guides/mcp.mdxindex dd8ce50df..688869088 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, forty tools in all.+exact pipelines the UI uses, fifty-four tools in all.<Aside type="tip">Everything an agent does goes through the editor's own command surface — creates@@ -66,38 +66,73 @@ refused. Grant writes deliberately.## Driving the editor you're looking at-To let an agent work inside an editor session you already have open, start the-editor with the endpoint enabled and point the server at its discovery file:+To let an agent work inside an editor session you already have open, use `--attach`+instead of `--editor`:<Steps>-1. Launch the editor with `--mcp` (from a terminal: `estella-editor --mcp`). It- writes a discovery file `mcp-endpoint.json` into the editor's user-data folder- (Windows: `%APPDATA%\Estella Editor\`; the exact path is printed on startup).--2. Configure your AI tool with `--attach` instead of `--editor`:+1. Configure your AI tool with `--attach`:```json- "args": ["<path-to>/editor-mcp.mjs", "--attach", "<path-to>/mcp-endpoint.json"]+ "args": ["<path-to>/editor-mcp.mjs", "--attach"]```+2. Launch the editor with `--mcp` (from a terminal: `estella-editor --mcp`). It+ writes a discovery file `mcp-endpoint.json` into its user-data folder, which+ `--attach` finds on its own — pass an explicit path only if you moved it.+3. The agent now drives the same window you see — selections, edits, play mode andall — while you watch and intervene.</Steps>+Order doesn't matter: the server resolves the editor **per call**, so you can start+your AI tool first and open the editor later, and restarting the editor mid-session+reconnects automatically rather than stranding the agent.+## What the agent can do| Area | Tools (excerpt) || --- | --- |-| Observe | `get_scene_tree`, `get_inspector`, `get_stats`, `capture_viewport` (PNG), `screenshot` (whole window, includes play), `world_component` (live-World probe) |-| Edit scenes | `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` |+| 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` |+| Game code | `read_project_file`, `write_project_file`, `list_project_files` || Run & ship | `toggle_play` + `get_play_state`, `export_game` (web / desktop / wechat / playable) |A typical agent loop: `open_project` → `open_scene` → `list_entity_templates` →-`create_entity` → `set_field` → `screenshot` to check its work → `save_scene` →-`toggle_play` → `screenshot` again → `export_game`.+`apply_scene_ops` → `get_diagnostics` → `screenshot` to check its work →+`save_scene` → `toggle_play` → `screenshot` again → `export_game`.++### Building scenes at scale++`set_field` writes one field per call, which is fine for a tweak and hopeless for a+scene: a single UI panel is easily a hundred nodes with a dozen fields each.+`apply_scene_ops` takes a **program** instead — creates, re-parents, component adds+and field writes, executed in order as **one undoable step**. Ops address entities+they create by name, so a whole subtree lands in one call:++```json+{+ "label": "Build HUD",+ "ops": [+ { "op": "create", "ref": "hud", "name": "HUD", "template": "ui-container" },+ { "op": "create", "ref": "coins", "name": "Coins", "template": "ui-text", "parent": "$hud",+ "fields": { "Text.content": "1440", "Text.fontSize": 28 } }+ ]+}+```++It is atomic: if any op fails, the error names the op that failed (`op[7] set: …`)+and the whole batch rolls back, so a bad program never leaves a half-built subtree+behind.++<Aside type="note">+Some things live in **import settings**, not on a component — a texture's 9-slice+border is the one that bites: a `UIVisual` set to NineSlice reads its border from+texture metadata, so a frame or button authored without `set_import_settings`+stretches its corners. `get_import_settings` shows every knob with its default.+</Aside>## From the repository (contributors)diff --git a/docs/astro/src/content/docs/zh-cn/guides/mcp.mdx b/docs/astro/src/content/docs/zh-cn/guides/mcp.mdxindex ef679f4b8..47570e660 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 自己的管线,共 40 个工具。+——走的都是 UI 自己的管线,共 54 个工具。<Aside type="tip">代理做的每件事都经过编辑器自己的命令面——创建可撤销、Play 模式不会弄脏编辑@@ -61,39 +61,70 @@ claude mcp add estella --env ESTELLA_MCP_ALLOW_WRITES=1 -- \## 驱动你正看着的编辑器-想让代理在你已经打开的编辑器会话里干活:以启用端点的方式启动编辑器,把服务器-指向它的发现文件即可:+想让代理在你已经打开的编辑器会话里干活,把 `--editor` 换成 `--attach` 即可:<Steps>-1. 用 `--mcp` 启动编辑器(终端里:`estella-editor --mcp`)。它会在编辑器的- user-data 目录写一个发现文件 `mcp-endpoint.json`(Windows:- `%APPDATA%\Estella Editor\`;确切路径启动时会打印出来)。--2. AI 工具的配置里用 `--attach` 代替 `--editor`:+1. AI 工具的配置里用 `--attach`:```json- "args": ["<path-to>/editor-mcp.mjs", "--attach", "<path-to>/mcp-endpoint.json"]+ "args": ["<path-to>/editor-mcp.mjs", "--attach"]```+2. 用 `--mcp` 启动编辑器(终端里:`estella-editor --mcp`)。它会往自己的+ user-data 目录写一个发现文件 `mcp-endpoint.json`,`--attach` 会自己找到它+ ——只有你把它挪了位置,才需要显式传路径。+3. 代理现在驱动的就是你眼前的这个窗口——选择、编辑、Play 全部同步——你可以一边看一边随时介入。</Steps>+启动顺序无所谓:服务器**每次调用时**才去解析编辑器,所以你可以先开 AI 工具、+后开编辑器;会话中途重启编辑器也会自动重连,不会把代理晾在那儿。+## 代理能做什么| 领域 | 工具(节选) || --- | --- |-| 观察 | `get_scene_tree`、`get_inspector`、`get_stats`、`capture_viewport`(PNG)、`screenshot`(整窗截图,含 Play 画面)、`world_component`(活 World 探针) |-| 编辑场景 | `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` |+| 观察 | `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` |+| 游戏代码 | `read_project_file`、`write_project_file`、`list_project_files` || 运行与发布 | `toggle_play` + `get_play_state`、`export_game`(web / desktop / wechat / playable) |典型的代理循环:`open_project` → `open_scene` → `list_entity_templates` →-`create_entity` → `set_field` → `screenshot` 检查成果 → `save_scene` →+`apply_scene_ops` → `get_diagnostics` → `screenshot` 检查成果 → `save_scene` →`toggle_play` → 再次 `screenshot` → `export_game`。+### 规模化搭建场景++`set_field` 一次只写一个字段——改一个值够用,搭一个场景就没戏了:一个 UI 面板+动辄上百个节点、每个十几个字段。`apply_scene_ops` 收的是一段**程序**:创建、+改父子、加组件、写字段按顺序执行,合成**一个可撤销步骤**。操作之间用名字互相+引用,所以整棵子树一次调用就能落地:++```json+{+ "label": "Build HUD",+ "ops": [+ { "op": "create", "ref": "hud", "name": "HUD", "template": "ui-container" },+ { "op": "create", "ref": "coins", "name": "Coins", "template": "ui-text", "parent": "$hud",+ "fields": { "Text.content": "1440", "Text.fontSize": 28 } }+ ]+}+```++它是原子的:任何一步失败,报错会指名是哪一步挂的(`op[7] set: …`),整批回滚+——一段写错的程序不会留下一棵搭到一半的子树。++<Aside type="note">+有些东西在**导入设置**里,不在组件上——最容易踩的是纹理的九宫格边框:+`UIVisual` 设成 NineSlice 后,边框是从纹理元数据读的,所以没配+`set_import_settings` 就搭出来的边框和按钮,四角会被拉伸变形。+`get_import_settings` 会把每个选项连同默认值一起列出来。+</Aside>+## 从源码仓库使用(贡献者)源码仓库里,`pnpm --filter @estella/editor editor:mcp` 用无头夹具宿主提供同一套