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): let an AI agent connect from Settings, not only from a launch flag
yhhcede2ad8a97f
diff --git a/desktop/electron/main.ts b/desktop/electron/main.tsindex fca168636..e34d9de1e 100644--- a/desktop/electron/main.ts+++ b/desktop/electron/main.ts@@ -43,7 +43,7 @@ import { buildPlayRealm } from './buildPlayRealm';import { ensureSdkTypes } from './syncSdkTypes';import { ensureProjectShaderTwins } from './shaderTwins';import { installCrashCapture, logsDir } from './resilience';-import { mcpMode, startMcpEndpoint } from './mcpEndpoint';+import { mcpMode, startMcpEndpoint, stopMcpEndpoint, mcpEndpointStatus } from './mcpEndpoint';import {discoverPlugins, compilePlugin, isTrusted, trustPlugin, revokeTrust, isDisabled, setPluginEnabled,PROJECT_PLUGIN_DIR, USER_PLUGIN_DIR,@@ -632,6 +632,13 @@ ipcMain.handle('app:installUpdate', async () => {ipcMain.handle('diagnostics:openLogs', () => shell.openPath(logsDir()));ipcMain.on('engine:status', (_e, status: string) => console.log('[engine]', status));+// — The MCP endpoint an external agent attaches to (mcpEndpoint.ts) —+// Driven by the editor setting, so an editor started by double-clicking it can+// serve `--attach` at all; `--mcp` keeps its own way in and outranks the setting.+ipcMain.handle('mcp:status', () => mcpEndpointStatus());+ipcMain.handle('mcp:setEnabled', (_e, on: boolean) =>+ on ? startMcpEndpoint(() => win) : stopMcpEndpoint());+// — Custom window controls (frameless Windows/Linux; macOS uses native traffic lights) —ipcMain.handle('window:minimize', () => win?.minimize());ipcMain.handle('window:toggleMaximize', () => {diff --git a/desktop/electron/mcpEndpoint.ts b/desktop/electron/mcpEndpoint.tsindex 440e85b73..ad780bf3a 100644--- a/desktop/electron/mcpEndpoint.ts+++ b/desktop/electron/mcpEndpoint.ts@@ -1,111 +1,173 @@// SPDX-License-Identifier: Apache-2.0// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team/**- * @file mcpEndpoint.ts — the live editor's MCP exec endpoint (`--mcp` mode).+ * @file mcpEndpoint.ts — the live editor's MCP exec endpoint.** Starts the shared loopback /exec seam against the REAL editor window, so the- * MCP front (scripts/editor-mcp.mjs --editor / --attach) can drive the full app:- * scene calls resolve on `window.__estellaEditor.surface` (the same- * EditorControlSurface the UI uses), editor-level calls (project open, scenes,- * play, entity templates) on `window.__estellaEditor`, renderer-code snippets run- * verbatim, and `op: screenshot` captures the composited window main-side — the- * only way to see into the play realm's OOPIF.+ * MCP front (scripts/editor-mcp.mjs --editor / --attach) can drive the full app.+ * The calls themselves land through createSurfaceDriver (surfaceDriver.ts), which+ * every consumer shares; this file owns only the transport around it — token,+ * discovery file, and the ready line.** The token comes from the spawning front (ESTELLA_MCP_TOKEN) or is generated for* a user-launched editor; either way the endpoint is advertised in a discovery* file under userData (mcp-endpoint.json) that `--attach` reads, and a* `MCP_HOST_READY {"port":N}` line on stdout for the spawn flow.+ *+ * TWO ways in, and the difference is who may close it:+ *+ * FORCED `--mcp` / ESTELLA_MCP=1 — the spawn flow (`editor-mcp.mjs --editor`)+ * launches the editor this way and then talks to the port it reads off+ * stdout. That conversation is the reason this process exists, so a+ * forced endpoint stays up for the session; {@link stopMcpEndpoint} is+ * a no-op against it rather than a way to hang up on your own caller.+ * OPT-IN the editor setting (agents.mcpEnabled), for the ordinary case: an+ * editor started by double-clicking it. `--attach` needs a discovery+ * file, and a user who never passes command-line flags had no way to+ * produce one — the endpoint existed but only for people who launched+ * the app from a terminal.+ *+ * Start/stop are therefore idempotent and re-entrant: a setting toggled twice, or+ * toggled in an editor already forced open, must not double-listen or double-write+ * the discovery file.*/import { app, BrowserWindow } from 'electron';import { randomBytes } from 'node:crypto';import { writeFileSync, rmSync } from 'node:fs';import path from 'node:path';+import type { Server } from 'node:http';// Plain .mjs, shared with the headless host (scripts/editor-mcp-host.mjs) —// esbuild bundles it into the main bundle.// @ts-expect-error untyped shared moduleimport { createExecEndpoint } from '../scripts/mcp-exec-endpoint.mjs';+import { createSurfaceDriver } from './surfaceDriver';const log = (...a: unknown[]) => process.stderr.write(`[editor-mcp-endpoint] ${a.join(' ')}\n`);-/** True when this editor process should expose the MCP exec endpoint. */+/** What the endpoint is doing right now — the whole of what the UI renders. */+export interface McpEndpointStatus {+ running: boolean;+ /** Loopback port, once listening. */+ port: number | null;+ /** The discovery file `--attach` reads, once advertised. */+ discoveryFile: string | null;+ /** Opened by `--mcp`/ESTELLA_MCP: on for the session, not the setting's to close. */+ forced: boolean;+ /** Why the last start failed, if it did (cleared by a start that works). */+ error: string | null;+}++/** True when this editor process was LAUNCHED to expose the endpoint. */export function mcpMode(): boolean {return process.argv.includes('--mcp') || process.env.ESTELLA_MCP === '1';}+// One token per process, not per start: the spawning front passes it in the+// environment and holds it for the session, so regenerating it on a restart+// would lock out the very client that launched us.+const TOKEN = process.env.ESTELLA_MCP_TOKEN || randomBytes(24).toString('hex');++let server: Server | null = null;+let starting: Promise<McpEndpointStatus> | null = null;+let port: number | null = null;+let discoveryFile: string | null = null;+let lastError: string | null = null;+let cleanupHooked = false;++/** The discovery file's path — same for every start, so a stale one is overwritten. */+function discoveryPath(): string {+ return path.join(app.getPath('userData'), 'mcp-endpoint.json');+}++export function mcpEndpointStatus(): McpEndpointStatus {+ return { running: server !== null, port, discoveryFile, forced: mcpMode(), error: lastError };+}+/**- * Start the endpoint against the editor window. `getWin` re-resolves per call so- * a recreated window keeps working. Idempotent-ish: call once after the first- * window exists.+ * Start the endpoint against the editor window and advertise it. `getWin`+ * re-resolves per call so a recreated window keeps working.+ *+ * Idempotent: already listening (or mid-start) hands back the same endpoint+ * rather than a second listener. Never throws — a failure to bind is reported+ * through {@link McpEndpointStatus.error}, because the caller is a settings+ * toggle and an unhandled rejection there would take the toggle with it.*/-export async function startMcpEndpoint(getWin: () => BrowserWindow | null): Promise<void> {- const token = process.env.ESTELLA_MCP_TOKEN || randomBytes(24).toString('hex');-- // executeJavaScript rejects a thrown error with an opaque "Script failed to- // execute" — wrap the expression so the real message crosses the boundary- // (surface errors like `component "X" is not on entity 5` are the automation- // client's actual feedback, not a debugging detail).- const carryError = (expr: string) =>- `(async () => { try { return { v: await (${expr}) }; } catch (e) { return { __estellaExecError: (e && e.message) || String(e) }; } })()`;- const unwrap = (res: unknown) => {- const r = res as { v?: unknown; __estellaExecError?: string } | null;- if (r && typeof r === 'object' && r.__estellaExecError !== undefined) throw new Error(r.__estellaExecError);- return r?.v;- };+export async function startMcpEndpoint(+ getWin: () => BrowserWindow | null,+): Promise<McpEndpointStatus> {+ if (server) return mcpEndpointStatus();+ if (starting) return starting;- const exec = async (code: string) => {- const win = getWin();- if (!win) throw new Error('no editor window');- // A call can arrive before the renderer finished booting (the endpoint comes- // up with the window) — wait out the initial load instead of failing it.- if (win.webContents.isLoading()) {- await new Promise<void>((resolve) => win.webContents.once('did-finish-load', () => resolve()));+ starting = (async (): Promise<McpEndpointStatus> => {+ const driver = createSurfaceDriver(getWin);+ try {+ server = await createExecEndpoint({+ token: TOKEN,+ run: async ({ method, args, root, js, op, code, frame }: {+ method?: string; args?: unknown[]; root?: string; js?: string; op?: string;+ code?: string; frame?: number;+ }) => {+ if (op) return driver.op(op, { code, frame });+ if (js) return driver.js(js);+ return driver(method as string, args ?? [], root);+ },+ });+ port = (server!.address() as { port: number }).port;+ lastError = null;+ } catch (e) {+ server = null;+ port = null;+ lastError = String((e as Error)?.message ?? e);+ log('could not start the exec endpoint:', lastError);+ return mcpEndpointStatus();}- return unwrap(await win.webContents.executeJavaScript(carryError(code), true));- };- const server = await createExecEndpoint({- token,- run: async ({ method, args, root, js, op, code, frame }: {- method?: string; args?: unknown[]; root?: string; js?: string; op?: string;- code?: string; frame?: number;- }) => {- if (op === 'screenshot') {- const win = getWin();- if (!win) throw new Error('no editor window');- const image = await win.webContents.capturePage();- return image.toPNG().toString('base64');+ // Advertise for --attach; the token in the file is what authorizes a local+ // client, so the file lives in userData (per-user, not world-readable temp).+ const file = discoveryPath();+ try {+ writeFileSync(file, JSON.stringify({ port, token: TOKEN, pid: process.pid }) + '\n');+ discoveryFile = file;+ // Once per process: a toggled setting can start/stop many times, and one+ // will-quit listener per start would leak them onto the app.+ if (!cleanupHooked) {+ cleanupHooked = true;+ app.on('will-quit', removeDiscoveryFile);}- if (op === 'play_probe') {- // The play realm is an estella:// OOPIF — only a main-process frame eval- // reaches it (the SHOT_PLAY_EVAL idiom; window.__estellaPlay is the probe).- const win = getWin();- if (!win) throw new Error('no editor window');- const playFrames = win.webContents.mainFrame.frames.filter((f) => f.url.startsWith('estella://'));- const playFrame = playFrames[frame ?? 0];- if (!playFrame) throw new Error(`no play realm at index ${frame ?? 0} (${playFrames.length} running — enter play first)`);- return unwrap(await playFrame.executeJavaScript(carryError(code ?? 'true')));- }- if (js) return exec(js);- const target = root === 'editor' ? 'window.__estellaEditor' : 'window.__estellaEditor.surface';- return exec(`${target}.${method}(${(args ?? [])- .map((a) => (a === undefined ? 'undefined' : JSON.stringify(a)))- .join(',')})`);- },- });+ } catch (e) {+ // A live endpoint nobody can discover still serves --editor (which reads the+ // port off stdout), so this degrades rather than fails.+ log('could not write discovery file:', String(e));+ discoveryFile = null;+ }- const port = (server.address() as { port: number }).port;+ // The spawn flow (editor-mcp.mjs --editor) reads this exact line.+ process.stdout.write(`MCP_HOST_READY ${JSON.stringify({ port })}\n`);+ log(`exec endpoint on 127.0.0.1:${port} (discovery: ${discoveryFile ?? 'unavailable'})`);+ return mcpEndpointStatus();+ })().finally(() => { starting = null; });- // Advertise for --attach; the token in the file is what authorizes a local- // client, so the file lives in userData (per-user, not world-readable temp).- const discovery = path.join(app.getPath('userData'), 'mcp-endpoint.json');+ return starting;+}++function removeDiscoveryFile(): void {try {- writeFileSync(discovery, JSON.stringify({ port, token, pid: process.pid }) + '\n');- app.on('will-quit', () => { try { rmSync(discovery); } catch { /* already gone */ } });- } catch (e) {- log('could not write discovery file:', String(e));- }+ rmSync(discoveryPath());+ } catch { /* already gone */ }+ discoveryFile = null;+}- // The spawn flow (editor-mcp.mjs --editor) reads this exact line.- process.stdout.write(`MCP_HOST_READY ${JSON.stringify({ port })}\n`);- log(`exec endpoint on 127.0.0.1:${port} (discovery: ${discovery})`);+/**+ * Close the endpoint and retract its discovery file, so `--attach` stops finding+ * a port nobody is listening on. A FORCED endpoint is left alone — see the file+ * header: the process was launched to serve it.+ */+export function stopMcpEndpoint(): McpEndpointStatus {+ if (mcpMode() || !server) return mcpEndpointStatus();+ server.close();+ server = null;+ port = null;+ removeDiscoveryFile();+ log('exec endpoint closed');+ return mcpEndpointStatus();}diff --git a/desktop/electron/preload.ts b/desktop/electron/preload.tsindex 34d215d7e..fa55780ec 100644--- a/desktop/electron/preload.ts+++ b/desktop/electron/preload.ts@@ -19,6 +19,7 @@ import type { DiscoveredPlugin, CompiledPlugin } from './pluginHost';import type { ScaffoldPluginOptions, ScaffoldPluginResult } from './pluginScaffold';import type { PluginPackageInfo, InstallPluginResult } from './pluginPackage';import type { NativeTemplateEntry, InstallResult } from './nativeTemplates';+import type { McpEndpointStatus } from './mcpEndpoint';// The privileged bridge the renderer is allowed to touch. Keep this surface small// and explicit — anything the editor needs from the OS or Node goes through here.@@ -81,6 +82,17 @@ const api = {openLogs: (): Promise<void> => ipcRenderer.invoke('diagnostics:openLogs'),},+ // — The MCP endpoint an external AI agent attaches to. Off unless asked for:+ // the setting drives it (persisted per user, replayed at boot), and `--mcp`+ // opens it for the whole session regardless (mcpEndpoint.ts). —+ mcp: {+ /** What the endpoint is doing now — port, discovery file, why it failed. */+ status: (): Promise<McpEndpointStatus> => ipcRenderer.invoke('mcp:status'),+ /** Open/close it; resolves with the resulting status (never throws on a bind+ * failure — the reason comes back in `error`). */+ setEnabled: (on: boolean): Promise<McpEndpointStatus> => ipcRenderer.invoke('mcp:setEnabled', on),+ },+// — Project / workspace (RC12 §E7) —project: {/** Show a directory picker and open the chosen Estella project (null if cancelled). */diff --git a/desktop/scripts/editor-mcp.mjs b/desktop/scripts/editor-mcp.mjsindex 037694108..d6fe4779b 100644--- a/desktop/scripts/editor-mcp.mjs+++ b/desktop/scripts/editor-mcp.mjs@@ -20,6 +20,9 @@* 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.+ * That editor has to be serving one: Settings > AI Agents >+ * "Allow AI agents to connect" (remembered), or a `--mcp`+ * launch (that session only).** 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@@ -192,7 +195,8 @@ 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 '+ 'no running editor to attach to — in the Estella editor, turn on '+ + 'Settings > AI Agents > "Allow AI agents to connect" (or launch it with --mcp) '+ `(looked for ${attachCandidates().join(' | ')})`,);}diff --git a/desktop/src/components/SettingsDialog.tsx b/desktop/src/components/SettingsDialog.tsxindex f7d12301d..4a1df71d1 100644--- a/desktop/src/components/SettingsDialog.tsx+++ b/desktop/src/components/SettingsDialog.tsx@@ -7,7 +7,7 @@* registered descriptors, picking a control by `type`. Search filters across* sections; a reset arrow shows when a value differs from its default.*/-import { useEffect, useRef, useState } from 'react';+import { useEffect, useRef, useState, useSyncExternalStore } from 'react';import type { PointerEvent as ReactPointerEvent } from 'react';import { createPortal } from 'react-dom';import { useShallow } from 'zustand/react/shallow';@@ -527,6 +527,16 @@ function Control({ setting }: { setting: Setting }) {}}+// What the setting's backing is actually doing right now, under the description.+// Subscribed rather than read once: the state it reports (a port that opened, an+// error that came back) lands after the click that asked for it.+const NEVER_CHANGES = () => () => {};++function StatusLine({ status }: { status: NonNullable<Setting['status']> }) {+ const text = useSyncExternalStore(status.subscribe ?? NEVER_CHANGES, status.read, status.read);+ return text ? <div className="sd set-status">{text}</div> : null;+}+function Row({ setting }: { setting: Setting }) {const isChanged = useSettings((s) => s.isChanged(setting.id));const reset = useSettings((s) => s.reset);@@ -535,6 +545,7 @@ function Row({ setting }: { setting: Setting }) {<div><div className="sn">{setting.label}</div>{setting.description && <div className="sd">{setting.description}</div>}+ {setting.status && <StatusLine status={setting.status} />}</div><div className="set-ctrl"><Control setting={setting} />diff --git a/desktop/src/i18n/messages/settings.ts b/desktop/src/i18n/messages/settings.tsindex 3fe067620..4fe55bf2d 100644--- a/desktop/src/i18n/messages/settings.ts+++ b/desktop/src/i18n/messages/settings.ts@@ -38,11 +38,16 @@ export const settingsMessages = defineMessages({'set.section.console': { en: 'Console', zh: '控制台' },'set.section.renderer': { en: 'Renderer', zh: '渲染器' },'set.section.externalTools': { en: 'External Tools', zh: '外部工具' },+ 'set.section.agents': { en: 'AI Agents', zh: 'AI 代理' },'toast.programMissing': {en: 'Could not find {program} — it may have been moved or uninstalled',zh: '找不到 {program},可能已被移动或卸载',},'toast.programFailed': { en: 'Could not start {program}', zh: '无法启动 {program}' },+ 'toast.mcpFailed': {+ en: 'Could not open the port for AI agents: {message}',+ zh: '无法为 AI 代理开启端口:{message}',+ },'toast.openFailed': { en: 'No program is set up to open this file', zh: '没有可打开该文件的程序' },'set.externalTools.placeholder': { en: 'Automatic — the system default', zh: '自动 — 使用系统默认程序' },'set.externalTools.autoNamed': { en: 'Automatic ({program})', zh: '自动({program})' },@@ -88,6 +93,23 @@ export const settingsMessages = defineMessages({'set.group.background': { en: 'Background', zh: '后台' },'set.group.console': { en: 'Console', zh: '控制台' },'set.group.renderer': { en: 'Renderer', zh: '渲染器' },+ 'set.group.agents': { en: 'External Agents', zh: '外部代理' },++ // — AI Agents —+ 'set.agents.mcpEnabled': { en: 'Allow AI agents to connect', zh: '允许 AI 代理连接' },+ 'set.agents.mcpEnabled.desc': {+ en: 'Serve this editor over MCP on a local-only port, so an agent set up with --attach can drive the project you have open. Off means nothing is listening.',+ zh: '通过 MCP 在仅限本机的端口上开放此编辑器,让配置了 --attach 的代理能够操作你正打开的项目。关闭时不会有任何监听。',+ },+ 'set.agents.mcp.listening': {+ en: 'Listening on 127.0.0.1:{port} — agents configured with --attach will find it.',+ zh: '正在监听 127.0.0.1:{port}——配置了 --attach 的代理即可找到它。',+ },+ 'set.agents.mcp.forced': {+ en: 'Listening on 127.0.0.1:{port}, opened by the --mcp launch flag. It stays open for this session.',+ zh: '正在监听 127.0.0.1:{port},由启动参数 --mcp 开启。本次会话期间将保持开启。',+ },+ 'set.agents.mcp.error': { en: 'Could not open the port: {message}', zh: '无法开启端口:{message}' },'set.project.display.screenPresets': { en: 'Screen presets', zh: '屏幕预设' },'set.project.display.screenPresets.desc': {en: 'Extra screens the viewport and Game view can simulate, on top of the built-in devices. Reusing a built-in id (iphone, ipad, 1080p, 720p) replaces it.',diff --git a/desktop/src/settings/editorSettings.ts b/desktop/src/settings/editorSettings.tsindex c24a18fca..f5df37e12 100644--- a/desktop/src/settings/editorSettings.ts+++ b/desktop/src/settings/editorSettings.ts@@ -17,6 +17,7 @@ import { commands } from '@/commands';import { setUseLessCpuInBackground } from '@/engine/backgroundThrottle';import { EngineHost } from '@/engine/EngineHost';import { Toasts } from '@/store/Toasts';+import { mcpStatus, setMcpEnabled, subscribeMcp } from '@/store/McpStore';import { t, editorLocale, systemDefaultLocale, EDITOR_LOCALES, LANGUAGE_SETTING_ID } from '@/i18n';const root = () => document.documentElement.style;@@ -31,6 +32,7 @@ settingsRegistry.registerSection({ id: 'renderer', label: t('set.section.rendere// The rows under it are registered by externalPrograms.ts — one per program slot,// so a contributed slot appears here without this file knowing it exists.settingsRegistry.registerSection({ id: 'externalTools', label: t('set.section.externalTools'), category: 'editor', order: 7 });+settingsRegistry.registerSection({ id: 'agents', label: t('set.section.agents'), category: 'editor', order: 8 });// ── Appearance (store-owned, applied via CSS) ───────────────────────────────// The session renders in the locale resolved at boot from this same persisted@@ -229,6 +231,46 @@ settingsRegistry.register({effect: (v) => LogStore.setCap(v),});+// ── AI Agents (main-owned endpoint, driven from here) ───────────────────────+// An external agent reaches this editor through the MCP endpoint main can expose,+// and `--attach` finds it through the discovery file the endpoint writes. An+// editor launched the ordinary way — by double-clicking it — wrote no such file,+// so the only way to let an agent in was a command-line flag, which is not+// something a GUI user has any reason to know exists. This is that flag, as a+// setting: persisted per user and replayed at boot, so it survives a restart the+// way `--mcp` never could.+//+// Reports rather than assumes: the effect resolves with what main actually did,+// and the status line renders THAT — an editor started with `--mcp` shows itself+// already open (and stays open, the toggle notwithstanding), a port that could+// not bind shows why. Only failures toast; success is the line right there, and+// the boot replay would otherwise greet every launch with a notification.+function mcpStatusLine(): string | null {+ const s = mcpStatus();+ if (s.error) return t('set.agents.mcp.error', { message: s.error });+ if (!s.running || s.port === null) return null;+ return s.forced+ ? t('set.agents.mcp.forced', { port: String(s.port) })+ : t('set.agents.mcp.listening', { port: String(s.port) });+}++settingsRegistry.register({+ id: 'agents.mcpEnabled',+ type: 'boolean',+ scope: 'editor',+ section: 'agents',+ group: t('set.group.agents'),+ label: t('set.agents.mcpEnabled'),+ description: t('set.agents.mcpEnabled.desc'),+ default: false,+ effect: (on) => {+ void setMcpEnabled(on).then((s) => {+ if (s.error) Toasts.push(t('toast.mcpFailed', { message: s.error }), 'error');+ });+ },+ status: { read: mcpStatusLine, subscribe: subscribeMcp },+});+// ── Keyboard Shortcuts (editable, bound to the command registry overrides) ───// Each keybound command gets a row; the value is the effective chord, bound to// the registry so rebinding persists + takes effect, and reset clears the override.diff --git a/desktop/src/settings/types.ts b/desktop/src/settings/types.tsindex 630c9bf0d..56bfc0a2e 100644--- a/desktop/src/settings/types.ts+++ b/desktop/src/settings/types.ts@@ -47,6 +47,19 @@ interface BaseSetting<T> {bind?: { get: () => T; set: (value: T) => void };/** One-way push to runtime for store-owned settings (on set + on hydrate). */effect?: (value: T) => void;+ /**+ * A live line under the description reporting what the setting's backing is+ * ACTUALLY doing — "listening on 127.0.0.1:51234", "no encoder found". For+ * settings whose effect can fail or resolve asynchronously, where the checkbox+ * alone says what was asked for and not what happened.+ *+ * `read` must return an equal string for an unchanged state (the row reads it+ * through useSyncExternalStore, which compares with Object.is — a plain string+ * satisfies that, an object rebuilt per call would loop). `subscribe` re-renders+ * the row when the backing changes; omit it for a value that only moves when+ * some other setting does.+ */+ status?: { read: () => string | null; subscribe?: (fn: () => void) => () => void };}export interface BooleanSetting extends BaseSetting<boolean> {diff --git a/desktop/src/store/McpStore.ts b/desktop/src/store/McpStore.tsnew file mode 100644index 000000000..225581cf6--- /dev/null+++ b/desktop/src/store/McpStore.ts@@ -0,0 +1,56 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file McpStore.ts+ * @brief The editor's MCP endpoint, as the UI sees it.+ *+ * Main owns the endpoint itself (electron/mcpEndpoint.ts) — it holds the+ * listener, the token and the discovery file. This is a read model of it:+ * the settings row renders from here, and the setting's `effect` drives+ * the toggle through it, so the two never disagree about whether an agent+ * can currently attach.+ *+ * A vanilla store, not a hook: the settings registry is plain data and its+ * `status` hook is read outside React (SettingsDialog subscribes it to a+ * row through useSyncExternalStore).+ */+import { createStore } from 'zustand/vanilla';+import type { McpEndpointStatus } from '../../electron/mcpEndpoint';++export type { McpEndpointStatus };++/** Before main has answered, "off" is the honest reading — nothing is listening+ * that we know of, and the first refresh is one IPC round-trip away. */+const UNKNOWN: McpEndpointStatus = {+ running: false, port: null, discoveryFile: null, forced: false, error: null,+};++interface McpState {+ status: McpEndpointStatus;+}++const store = createStore<McpState>(() => ({ status: UNKNOWN }));++/** The endpoint's state as last read from main. */+export const mcpStatus = (): McpEndpointStatus => store.getState().status;++/** Re-render on any change (useSyncExternalStore / plain subscriber). */+export const subscribeMcp = (fn: () => void): (() => void) => store.subscribe(fn);++/** Ask main what the endpoint is doing and adopt the answer. */+export async function refreshMcpStatus(): Promise<McpEndpointStatus> {+ const status = await window.estella.mcp.status();+ store.setState({ status });+ return status;+}++/**+ * Open or close the endpoint. Resolves with the resulting status — including a+ * refused start, which comes back as `error` rather than a rejection, so a+ * settings toggle can report it without a try/catch around the whole effect.+ */+export async function setMcpEnabled(on: boolean): Promise<McpEndpointStatus> {+ const status = await window.estella.mcp.setEnabled(on);+ store.setState({ status });+ return status;+}diff --git a/desktop/src/theme/settings.css b/desktop/src/theme/settings.cssindex d16aed8fc..f47fa3c7b 100644--- a/desktop/src/theme/settings.css+++ b/desktop/src/theme/settings.css@@ -121,6 +121,16 @@}.set-row .sn { font-size: var(--fs-sm); color: var(--text); }.set-row .sd { font-size: var(--fs-xs); color: var(--text-mute); margin-top: 2px; line-height: 1.4; }+/* What the setting's backing is actually doing (a port that opened, an error that+ came back) — distinguished from the static description by the accent rule, so a+ glance separates "what this does" from "what it is doing". */+.set-row .set-status {+ margin-top: 4px;+ padding-left: 7px;+ border-left: 2px solid var(--star-line, var(--acc));+ color: var(--text);+ font-variant-numeric: tabular-nums;+}.set-row.changed .sn::after {content: '';display: inline-block;diff --git a/desktop/tests/mcp-endpoint.test.ts b/desktop/tests/mcp-endpoint.test.tsnew file mode 100644index 000000000..7be6f415d--- /dev/null+++ b/desktop/tests/mcp-endpoint.test.ts@@ -0,0 +1,161 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+//+// The MCP exec endpoint's lifecycle. It has two ways in that must not fight:+//+// FORCED (`--mcp` / ESTELLA_MCP=1) — the spawn flow launched this editor to+// serve one client and is talking to the port it read off stdout. Stopping+// that endpoint would hang up on the caller, so the setting cannot.+// OPT-IN (the editor setting) — the ordinary double-clicked editor, which+// otherwise advertises nothing and so can never be `--attach`ed to.+//+// Both go through the same start/stop, which therefore has to be idempotent: a+// setting is toggled by a human, twice, faster than a port binds.+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';+import { mkdtempSync, existsSync, readFileSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import path from 'node:path';++let userData: string;+const closed = vi.fn();+const created = vi.fn();+let bindError: Error | null = null;+let nextPort = 51234;++vi.mock('electron', () => ({+ app: {+ getPath: () => userData,+ on: () => {},+ },+}));++// The loopback seam itself is covered by its own host tests; here it stands in as+// "a listener that bound (or didn't)", which is all this file's logic turns on.+vi.mock('../scripts/mcp-exec-endpoint.mjs', () => ({+ createExecEndpoint: async (opts: { token: string }) => {+ created(opts.token);+ if (bindError) throw bindError;+ return { address: () => ({ port: nextPort }), close: closed };+ },+}));++vi.mock('../electron/surfaceDriver', () => ({+ createSurfaceDriver: () => Object.assign(() => undefined, { op: () => undefined, js: () => undefined }),+}));++async function load() {+ vi.resetModules();+ return import('../electron/mcpEndpoint');+}++const win = () => null;+const discovery = () => path.join(userData, 'mcp-endpoint.json');++beforeEach(() => {+ userData = mkdtempSync(path.join(tmpdir(), 'estella-mcp-userdata-'));+ closed.mockReset();+ created.mockReset();+ bindError = null;+ nextPort = 51234;+ process.env.ESTELLA_MCP_TOKEN = 'test-token';+ delete process.env.ESTELLA_MCP;+ process.argv = process.argv.filter((a) => a !== '--mcp');+});++afterEach(() => {+ delete process.env.ESTELLA_MCP_TOKEN;+ delete process.env.ESTELLA_MCP;+ rmSync(userData, { recursive: true, force: true });+});++describe('the MCP endpoint lifecycle', () => {+ it('is closed until something asks for it', async () => {+ const { mcpEndpointStatus } = await load();+ expect(mcpEndpointStatus()).toMatchObject({ running: false, port: null, discoveryFile: null });+ expect(existsSync(discovery())).toBe(false);+ });++ it('starting advertises the port + token in the discovery file --attach reads', async () => {+ const { startMcpEndpoint } = await load();+ const status = await startMcpEndpoint(win);++ expect(status).toMatchObject({ running: true, port: 51234, error: null });+ expect(status.discoveryFile).toBe(discovery());+ expect(JSON.parse(readFileSync(discovery(), 'utf8'))).toMatchObject({ port: 51234, token: 'test-token' });+ });++ it('starting twice keeps ONE listener — a toggle is clicked, not transacted', async () => {+ const { startMcpEndpoint } = await load();+ const [a, b] = await Promise.all([startMcpEndpoint(win), startMcpEndpoint(win)]);+ const c = await startMcpEndpoint(win);++ expect(created).toHaveBeenCalledTimes(1);+ expect([a.port, b.port, c.port]).toEqual([51234, 51234, 51234]);+ });++ it('stopping closes the listener AND retracts the discovery file', async () => {+ const { startMcpEndpoint, stopMcpEndpoint, mcpEndpointStatus } = await load();+ await startMcpEndpoint(win);+ expect(existsSync(discovery())).toBe(true);++ const status = stopMcpEndpoint();++ expect(closed).toHaveBeenCalledTimes(1);+ expect(status).toMatchObject({ running: false, port: null, discoveryFile: null });+ // Left behind, --attach would keep finding a port nobody is listening on and+ // every call would fail at the connection instead of saying "no editor".+ expect(existsSync(discovery())).toBe(false);+ expect(mcpEndpointStatus().running).toBe(false);+ });++ it('reopens after a stop', async () => {+ const { startMcpEndpoint, stopMcpEndpoint } = await load();+ await startMcpEndpoint(win);+ stopMcpEndpoint();+ nextPort = 51999;++ expect(await startMcpEndpoint(win)).toMatchObject({ running: true, port: 51999 });+ expect(JSON.parse(readFileSync(discovery(), 'utf8'))).toMatchObject({ port: 51999, token: 'test-token' });+ });++ it('reports a refused bind instead of throwing — the caller is a settings toggle', async () => {+ const { startMcpEndpoint } = await load();+ bindError = new Error('EADDRINUSE');++ const status = await startMcpEndpoint(win);++ expect(status).toMatchObject({ running: false, port: null });+ expect(status.error).toMatch(/EADDRINUSE/);+ // A failed start must not leave a discovery file pointing at nothing.+ expect(existsSync(discovery())).toBe(false);+ });++ it('clears a previous error once a start works', async () => {+ const { startMcpEndpoint } = await load();+ bindError = new Error('EADDRINUSE');+ await startMcpEndpoint(win);+ bindError = null;++ expect(await startMcpEndpoint(win)).toMatchObject({ running: true, error: null });+ });++ describe('when the editor was LAUNCHED to serve it (--mcp)', () => {+ beforeEach(() => { process.env.ESTELLA_MCP = '1'; });++ it('reports itself forced, so the UI can say who opened it', async () => {+ const { startMcpEndpoint } = await load();+ expect(await startMcpEndpoint(win)).toMatchObject({ running: true, forced: true });+ });++ it('refuses to stop — the spawning client is mid-conversation with this port', async () => {+ const { startMcpEndpoint, stopMcpEndpoint } = await load();+ await startMcpEndpoint(win);++ const status = stopMcpEndpoint();++ expect(closed).not.toHaveBeenCalled();+ expect(status).toMatchObject({ running: true, port: 51234, forced: true });+ expect(existsSync(discovery())).toBe(true);+ });+ });+});diff --git a/docs/astro/src/content/docs/guides/mcp.mdx b/docs/astro/src/content/docs/guides/mcp.mdxindex ee2992a8c..e7204036b 100644--- a/docs/astro/src/content/docs/guides/mcp.mdx+++ b/docs/astro/src/content/docs/guides/mcp.mdx@@ -77,9 +77,14 @@ instead of `--editor`:"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.+2. Turn on **Settings → AI Agents → Allow AI agents to connect**. The editor opens+ a local-only port and 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. The row reports the port it is listening on, and the setting is+ remembered, so an editor you start by double-clicking it is ready from then on.++ Launching from a terminal with `--mcp` (`estella-editor --mcp`) does the same+ thing for one session, and outranks the setting while it lasts.3. The agent now drives the same window you see — selections, edits, play mode andall — while you watch and intervene.diff --git a/docs/astro/src/content/docs/zh-cn/guides/mcp.mdx b/docs/astro/src/content/docs/zh-cn/guides/mcp.mdxindex 007e672a9..ab16169c7 100644--- a/docs/astro/src/content/docs/zh-cn/guides/mcp.mdx+++ b/docs/astro/src/content/docs/zh-cn/guides/mcp.mdx@@ -71,9 +71,13 @@ claude mcp add estella --env ESTELLA_MCP_ALLOW_WRITES=1 -- \"args": ["<path-to>/editor-mcp.mjs", "--attach"]```-2. 用 `--mcp` 启动编辑器(终端里:`estella-editor --mcp`)。它会往自己的- user-data 目录写一个发现文件 `mcp-endpoint.json`,`--attach` 会自己找到它- ——只有你把它挪了位置,才需要显式传路径。+2. 打开**设置 → AI 代理 → 允许 AI 代理连接**。编辑器会开启一个仅限本机的端口,+ 并往自己的 user-data 目录写一个发现文件 `mcp-endpoint.json`,`--attach` 会自己+ 找到它——只有你把它挪了位置,才需要显式传路径。那一行会显示当前监听的端口;+ 这个开关会被记住,所以此后你双击图标启动的编辑器同样是就绪状态。++ 在终端里用 `--mcp` 启动(`estella-editor --mcp`)效果相同,只对当次会话生效,+ 且在该会话内优先于这个设置。3. 代理现在驱动的就是你眼前的这个窗口——选择、编辑、Play 全部同步——你可以一边看一边随时介入。