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): main holds the agent conversation, the window holds a mirror of it
esengine9691fa4710cb
diff --git a/desktop/electron/agent/host.ts b/desktop/electron/agent/host.tsnew file mode 100644index 000000000..2198560bb--- /dev/null+++ b/desktop/electron/agent/host.ts@@ -0,0 +1,196 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file host.ts+ * @brief Main's owner of the live agent conversation: one session, one turn at+ * a time, and the stream the editor window renders from.+ *+ * The session lives here for the same reason the MCP endpoint does — it holds+ * something the window cannot be trusted with (the API key) and must survive a+ * renderer that reloads mid-turn. The window keeps a MIRROR (store/AgentStore.ts)+ * built from the messages this pushes, so the transcript and the session cannot+ * disagree about what happened.+ *+ * Two invariants the rest of the editor is allowed to rely on:+ *+ * 1. An accepted `send` ALWAYS ends with exactly one `turn_end`. runTurn takes+ * its checkpoint before its own try block, so a turn can reject before it+ * ever starts (no editor window, no automation hook); a UI left in "running"+ * by that has no way back short of a restart.+ * 2. A pending confirmation is always answered. Abort, session reset and a+ * finished turn all resolve it as declined — a kernel awaiting a promise+ * nobody will settle is a hang, not an error anyone can see.+ */+import { runTurn, agentTools } from './kernel';+import { SYSTEM_PROMPT, editorContext } from './prompt';+import type { AgentEvent, AgentProvider, AgentSession, ConfirmRequest } from './types';+import type { SurfaceDriver } from '../surfaceDriver';++export type AgentPhase = 'idle' | 'running' | 'awaiting_confirm';++/** The conversation as the editor window is allowed to see it. */+export interface AgentStatus {+ /** A credential is configured, so a session can be created at all. */+ ready: boolean;+ /** Open — follow-ups continue it, and the transcript below is about it. */+ conversation: boolean;+ phase: AgentPhase;+ /** The model of the running session, once there is one. */+ model: string | null;+ /** Why the last attempt did not happen. Cleared by one that does. */+ error: string | null;+}++/** One push to the window: a transcript event, or the mirror's new state. */+export type AgentMessage =+ | { kind: 'event'; event: AgentEvent }+ | { kind: 'status'; status: AgentStatus };++export interface AgentHostDeps {+ /** The one driver every consumer shares (surfaceDriver.ts). */+ driver: SurfaceDriver;+ /** To the window. Must tolerate there not being one. */+ push(message: AgentMessage): void;+ /** Whether a credential exists — the status bit, without decrypting it. */+ ready(): boolean;+ /** Build the provider, or throw with a sentence the user can act on. */+ provider(): AgentProvider;+}++export interface AgentHost {+ status(): AgentStatus;+ /** Start a turn. Returns the resulting status — including a refusal, which is+ * an `error` on it rather than a rejection. Does not wait for the turn. */+ send(text: string): AgentStatus;+ /** Abort the running turn. Idempotent, and a no-op when nothing runs. */+ stop(): void;+ /** Answer a pending confirmation. Unknown ids are ignored — the turn it+ * belonged to may have been aborted between the ask and the click. */+ confirm(callId: string, allow: boolean): void;+ /** Drop the conversation and start over; the next turn re-reads the key. */+ reset(): AgentStatus;+}++export function createAgentHost(deps: AgentHostDeps): AgentHost {+ let session: AgentSession | null = null;+ let model: string | null = null;+ let phase: AgentPhase = 'idle';+ let error: string | null = null;+ let running: AbortController | null = null;+ const pending = new Map<string, (allow: boolean) => void>();++ const status = (): AgentStatus => ({+ ready: deps.ready(),+ conversation: session !== null,+ phase,+ model,+ error,+ });++ const pushStatus = (): void => deps.push({ kind: 'status', status: status() });+ const emit = (event: AgentEvent): void => deps.push({ kind: 'event', event });++ /** Settle every outstanding ask as declined. See invariant 2. */+ const settlePending = (): void => {+ for (const resolve of pending.values()) resolve(false);+ pending.clear();+ };++ const confirm = (request: ConfirmRequest): Promise<boolean> =>+ new Promise<boolean>((resolve) => {+ pending.set(request.callId, resolve);+ phase = 'awaiting_confirm';+ pushStatus();+ });++ const send = (text: string): AgentStatus => {+ if (phase !== 'idle') {+ error = 'the agent is still working on the previous message';+ pushStatus();+ return status();+ }+ if (!session) {+ try {+ const provider = deps.provider();+ session = provider.createSession({ system: SYSTEM_PROMPT, tools: agentTools() });+ model = provider.model;+ } catch (e) {+ error = (e as Error)?.message ?? String(e);+ pushStatus();+ return status();+ }+ }++ error = null;+ phase = 'running';+ const controller = new AbortController();+ running = controller;+ pushStatus();++ void (async () => {+ try {+ // Gathered here rather than in the kernel: what the editor is showing is+ // this host's business, and a kernel that read the editor for itself+ // would be a second definition of "what the agent knows".+ const context = await editorContext(deps.driver).catch(() => null);+ await runTurn(+ { driver: deps.driver, session: session!, confirm, emit },+ text,+ context,+ controller.signal,+ );+ } catch (e) {+ // Invariant 1: runTurn rejected, so it emitted no turn_end of its own.+ // The reason goes on the status rather than into the transcript — this+ // path is reached BEFORE the turn starts (runTurn takes its checkpoint+ // outside its own try), so there is no turn for it to be part of.+ error = (e as Error)?.message ?? String(e);+ emit({ type: 'turn_end', steps: 0, mark: null, reason: 'error' });+ } finally {+ settlePending();+ // A turn that was superseded by a reset must not walk the phase back:+ // reset already put it at idle for a conversation this one is no longer+ // part of.+ if (running === controller) {+ running = null;+ phase = 'idle';+ pushStatus();+ }+ }+ })();++ return status();+ };++ return {+ status,+ send,+ stop: () => {+ running?.abort();+ // The kernel may be parked on a confirmation, which an aborted signal does+ // not interrupt — it is waiting on us, not on the model.+ settlePending();+ },+ confirm: (callId, allow) => {+ const resolve = pending.get(callId);+ if (!resolve) return;+ pending.delete(callId);+ resolve(allow);+ if (pending.size === 0 && phase === 'awaiting_confirm') {+ phase = 'running';+ pushStatus();+ }+ },+ reset: () => {+ running?.abort();+ running = null;+ settlePending();+ session = null;+ model = null;+ phase = 'idle';+ error = null;+ pushStatus();+ return status();+ },+ };+}diff --git a/desktop/electron/agent/kernel.ts b/desktop/electron/agent/kernel.tsindex baa2fcb3b..9a9178d06 100644--- a/desktop/electron/agent/kernel.ts+++ b/desktop/electron/agent/kernel.ts@@ -72,7 +72,7 @@ export async function runTurn(): Promise<{ mark: unknown; steps: number }> {const { driver, session, emit } = deps;const mark = await driver('mark', []);- emit({ type: 'turn_start' });+ emit({ type: 'turn_start', prompt: text });let reason: Extract<AgentEvent, { type: 'turn_end' }>['reason'] = 'end_turn';try {@@ -122,7 +122,7 @@ export async function runTurn(if (signal.aborted) reason = 'aborted';const steps = Number(await driver('stepsSince', [mark]).catch(() => 0)) || 0;- emit({ type: 'turn_end', steps, reason });+ emit({ type: 'turn_end', steps, mark, reason });return { mark, steps };}diff --git a/desktop/electron/agent/prompt.ts b/desktop/electron/agent/prompt.tsnew file mode 100644index 000000000..12854c9ac--- /dev/null+++ b/desktop/electron/agent/prompt.ts@@ -0,0 +1,75 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file prompt.ts+ * @brief What the built-in agent is told about where it is: the standing+ * system prompt, and the per-turn note about what the editor is showing.+ *+ * Two texts because they are billed differently. The system prompt sits at the+ * front of the cached prefix and must therefore never change between turns; the+ * editor's state changes every turn and so goes in as `{role:'system'}` context+ * AFTER the history, where appending it leaves the cache intact (see+ * anthropic.ts). Anything that varies belongs in the second one.+ *+ * The prompt does not list the tools — the catalog already describes each one to+ * the model, and a prose restatement is a second description to keep in sync.+ * It says what the tools cannot: which of them the user has to approve, and what+ * counts as done here.+ */+import type { SurfaceDriver } from '../surfaceDriver';++export const SYSTEM_PROMPT = `You are the agent built into Estella, a 2D game editor. You are working inside the editor the user is looking at, on the project they have open, through the same operations the editor's own UI performs. Your edits appear in their viewport as you make them.++How work lands here:++- Edits go through the tools. There is no file-level path to the scene: a scene is a live World, and writing its file behind the editor's back would be overwritten by the next save.+- Anything that only mutates the scene is undoable, and the whole turn is bracketed by one undo checkpoint, so you do not need permission for it. Make the edit rather than describing the edit you would make.+- A few tools reach past what Undo can take back — writing a file, rewriting project settings, running code you wrote. Those stop and ask the user. If they decline, do not retry: work around it, or say what you need and why.+- After you change the scene you will be shown any problems the editor now flags. Silence means it is clean. Fix what you broke before reporting the work as done.++Working style:++- Look before you edit. get_scene_tree, get_inspector and get_document cost one round trip and are the difference between editing the right entity and editing a plausible one.+- You can see the result: capture_viewport renders what the user is looking at. Use it when the question is visual — layout, whether something is on screen, why the scene looks wrong.+- Prefer one apply_scene_ops over many small calls when building something: it is one undo step for the user and one round trip for you.+- Units are the editor's: 1 world unit = 1 design pixel. Y is up in the world, and UI is laid out top-down.+- Say what you did in a sentence or two. The user watched it happen — a summary of every call is noise. Speak the user's language: answer in the language they wrote to you in.`;++/**+ * What the editor is showing right now, or null when nothing worth saying.+ *+ * Deliberately small: it is re-sent every turn, and the model can ask for+ * anything more with a tool. Failures are swallowed — an editor mid-reload with+ * no scene open is a normal state, not a reason to fail the turn before it+ * starts.+ */+export async function editorContext(driver: SurfaceDriver): Promise<string | null> {+ const lines: string[] = [];+ try {+ const doc = await driver.js('window.__estellaEditor.documentState()') as {+ kind: string; path: string | null; name: string | null; dirty: boolean;+ } | null;+ if (doc?.path) {+ lines.push(`The editor is editing the ${doc.kind} ${doc.path}${doc.dirty ? ' (unsaved changes)' : ''}.`);+ // Prefab Mode makes every scene tool act on the prefab instead. A model+ // that thinks it is in a scene will "fix" the wrong document and the edits+ // will land in every instance of that prefab.+ if (doc.kind === 'prefab') lines.push('You are in Prefab Mode: the scene tools act on this prefab, not on a scene.');+ }+ } catch { /* no project open yet */ }++ try {+ const ids = await driver('getSelectionIds', []) as number[];+ if (ids?.length) {+ const names = await Promise.all(ids.slice(0, 8).map(async (id) => {+ const e = await driver('getEntity', [id]) as { name?: string } | null;+ return e?.name ? `${e.name} (id ${id})` : `id ${id}`;+ }));+ const more = ids.length > names.length ? `, and ${ids.length - names.length} more` : '';+ // The user's selection is what "this entity" means in their next sentence.+ lines.push(`Selected right now: ${names.join(', ')}${more}.`);+ }+ } catch { /* no scene */ }++ return lines.length ? lines.join('\n') : null;+}diff --git a/desktop/electron/agent/types.ts b/desktop/electron/agent/types.tsindex 0a17158dc..d836a8225 100644--- a/desktop/electron/agent/types.ts+++ b/desktop/electron/agent/types.ts@@ -83,16 +83,24 @@ export interface ConfirmRequest {input: Record<string, unknown>;}-/** What the editor renders. A superset of what the provider emitted. */+/**+ * What the editor renders. A superset of what the provider emitted.+ *+ * Self-describing on purpose: the editor's read model is rebuilt from this+ * stream alone (store/AgentStore.ts), across an IPC boundary where "the sender+ * also knows the prompt" stops being true. Hence `turn_start` carrying what was+ * asked and `turn_end` carrying the checkpoint, rather than the receiver pairing+ * events with state it kept on the side.+ */export type AgentEvent =| StepEvent- | { type: 'turn_start' }+ | { type: 'turn_start'; prompt: string }| { type: 'tool_start'; call: ToolCall; effect: NonNullable<CatalogTool['effect']> }| { type: 'tool_end'; id: string; ok: boolean; summary: string }| { type: 'awaiting_confirm'; request: ConfirmRequest }- /** The turn is over. `steps` is what a single Undo would take back, and 0 is- * the signal not to offer one. */- | { type: 'turn_end'; steps: number; reason: 'end_turn' | 'aborted' | 'error' | 'refusal' }+ /** The turn is over. `steps` is what a single Undo would take back — 0 is the+ * signal not to offer one — and `mark` is where it would take it back to. */+ | { type: 'turn_end'; steps: number; mark: unknown; reason: 'end_turn' | 'aborted' | 'error' | 'refusal' }| { type: 'error'; message: string };/** Everything the kernel needs from outside, so it runs under a test with nonediff --git a/desktop/electron/main.ts b/desktop/electron/main.tsindex c7ce815e2..be462d95f 100644--- a/desktop/electron/main.ts+++ b/desktop/electron/main.ts@@ -44,7 +44,11 @@ import { ensureSdkTypes } from './syncSdkTypes';import { ensureProjectShaderTwins } from './shaderTwins';import { installCrashCapture, logsDir } from './resilience';import { mcpMode, startMcpEndpoint, stopMcpEndpoint, mcpEndpointStatus } from './mcpEndpoint';-import { secretStatus, setSecret, clearSecret } from './secrets';+import { secretStatus, setSecret, clearSecret, readSecret } from './secrets';+import { createSurfaceDriver } from './surfaceDriver';+import { createAgentHost } from './agent/host';+import { createAnthropicProvider } from './agent/anthropic';+import { AGENT_API_KEY } from '../src/settings/secretIds';import {discoverPlugins, compilePlugin, isTrusted, trustPlugin, revokeTrust, isDisabled, setPluginEnabled,PROJECT_PLUGIN_DIR, USER_PLUGIN_DIR,@@ -648,6 +652,28 @@ ipcMain.handle('secret:status', (_e, id: string) => secretStatus(id));ipcMain.handle('secret:set', (_e, id: string, value: string) => setSecret(id, value));ipcMain.handle('secret:clear', (_e, id: string) => clearSecret(id));+// — The built-in agent (agent/host.ts) —+// Main owns the conversation because it owns the key, and because a renderer+// reload mid-turn must not take the turn with it. It drives the editor through+// the SAME surface driver the MCP endpoint uses; the window keeps a mirror.+const agentHost = createAgentHost({+ driver: createSurfaceDriver(() => win),+ push: (message) => win?.webContents.send('agent:message', message),+ ready: () => secretStatus(AGENT_API_KEY).configured,+ provider: () => {+ const apiKey = readSecret(AGENT_API_KEY);+ // Phrased for the person who will read it in the transcript, and it names+ // where to fix it — a bare "401" or "missing apiKey" does neither.+ if (!apiKey) throw new Error('No API key is configured. Add one in Settings › AI Agents.');+ return createAnthropicProvider({ apiKey });+ },+});+ipcMain.handle('agent:status', () => agentHost.status());+ipcMain.handle('agent:send', (_e, text: string) => agentHost.send(text));+ipcMain.handle('agent:stop', () => agentHost.stop());+ipcMain.handle('agent:confirm', (_e, callId: string, allow: boolean) => agentHost.confirm(callId, allow));+ipcMain.handle('agent:reset', () => agentHost.reset());+// — 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/preload.ts b/desktop/electron/preload.tsindex 005acae17..5fa5b98a4 100644--- a/desktop/electron/preload.ts+++ b/desktop/electron/preload.ts@@ -21,6 +21,7 @@ import type { PluginPackageInfo, InstallPluginResult } from './pluginPackage';import type { NativeTemplateEntry, InstallResult } from './nativeTemplates';import type { McpEndpointStatus } from './mcpEndpoint';import type { SecretStatus } from './secrets';+import type { AgentStatus, AgentMessage } from './agent/host';// 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.@@ -106,6 +107,27 @@ const api = {clear: (id: string): Promise<SecretStatus> => ipcRenderer.invoke('secret:clear', id),},+ // — The built-in agent. Main owns the conversation (electron/agent/host.ts);+ // this is the window's way to talk to it and to hear what it is doing. —+ agent: {+ status: (): Promise<AgentStatus> => ipcRenderer.invoke('agent:status'),+ /** Start a turn; resolves with the resulting status, refusals included. */+ send: (text: string): Promise<AgentStatus> => ipcRenderer.invoke('agent:send', text),+ stop: (): Promise<void> => ipcRenderer.invoke('agent:stop'),+ /** Answer the pending confirmation for an irreversible tool. */+ confirm: (callId: string, allow: boolean): Promise<void> =>+ ipcRenderer.invoke('agent:confirm', callId, allow),+ /** Drop the conversation and start a new one. */+ reset: (): Promise<AgentStatus> => ipcRenderer.invoke('agent:reset'),+ /** Transcript events + status changes, in the order they happened; returns+ * an unsubscribe. One channel because the two must not be reordered. */+ onMessage: (cb: (message: AgentMessage) => void): (() => void) => {+ const h = (_e: unknown, message: AgentMessage) => cb(message);+ ipcRenderer.on('agent:message', h);+ return () => ipcRenderer.removeListener('agent:message', h);+ },+ },+// — Project / workspace (RC12 §E7) —project: {/** Show a directory picker and open the chosen Estella project (null if cancelled). */diff --git a/desktop/src/main.tsx b/desktop/src/main.tsxindex 3d4dd5598..42ad575f7 100644--- a/desktop/src/main.tsx+++ b/desktop/src/main.tsx@@ -67,6 +67,7 @@ import { openAssetOfType, opensInEditor } from './project/assetOpen';import { DirtyRegistry } from './document/DirtyRegistry';import { initBackgroundThrottle } from './engine/backgroundThrottle';import { mcpStatus, subscribeMcp } from './store/McpStore';+import { attachAgentBridge, agentDriving, subscribeAgent } from './store/AgentStore';import { guardAutomationHook } from './engine/automationGate';// Register the built-in settings (side effect) and replay persisted ones.import './settings';@@ -482,14 +483,21 @@ function buildEditorAutomation(): unknown {};}-// The launch flag holds for the session; the setting can open and close the-// endpoint at any moment, including a boot replay that lands after this module-// ran. McpStore already mirrors what main is doing, so watching it is enough —-// this needs no channel of its own.+// Three ways a driver is authorized. The launch flag holds for the session; the+// MCP setting can open and close the endpoint at any moment, including a boot+// replay that lands after this module ran; and the BUILT-IN agent is a driver+// too — it reaches this window through the same `window.__estellaEditor`, so a+// conversation that cannot see the hook is an agent whose every tool call fails.+// Both stores already mirror what main is doing, so watching them is enough.const LAUNCH_AUTOMATION = new URLSearchParams(location.search).has('automation');+attachAgentBridge();guardAutomationHook(- () => LAUNCH_AUTOMATION || mcpStatus().running,- subscribeMcp,+ () => LAUNCH_AUTOMATION || mcpStatus().running || agentDriving(),+ (fn) => {+ const offMcp = subscribeMcp(fn);+ const offAgent = subscribeAgent(fn);+ return () => { offMcp(); offAgent(); };+ },() => { (window as unknown as { __estellaEditor?: unknown }).__estellaEditor = buildEditorAutomation(); },() => { delete (window as unknown as { __estellaEditor?: unknown }).__estellaEditor; },);diff --git a/desktop/src/store/AgentStore.ts b/desktop/src/store/AgentStore.tsnew file mode 100644index 000000000..456b7c2ab--- /dev/null+++ b/desktop/src/store/AgentStore.ts@@ -0,0 +1,280 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file AgentStore.ts+ * @brief The built-in agent's conversation, as the editor renders it.+ *+ * Main owns the session (electron/agent/host.ts) — the key, the model+ * calls, the turn loop. This is its mirror, and the projection: main+ * pushes a flat stream of what happened, and {@link applyAgentEvent}+ * folds it into the runs the drawer draws. The fold lives here rather+ * than in main because it is a rendering decision (what a "row" is, when+ * two deltas are one paragraph), and rather than in a component because+ * a projection with a state machine in it should be testable without one.+ *+ * Rebuilt from the events alone: nothing here pairs a message with state+ * kept on the side, so a reload that re-reads the stream lands in the+ * same place.+ */+import { create } from 'zustand';+import type { AgentStatus, AgentMessage } from '../../electron/agent/host';+import type { AgentEvent, ConfirmRequest } from '../../electron/agent/types';++export type { AgentStatus, AgentEvent };++export type AgentEffect = 'read' | 'undoable' | 'irreversible';++/**+ * Where a call is. `queued` is the model having asked for it while an earlier+ * one still runs — the doc's "parallel, greyed, not three spinners" — and+ * `stopped` is a row the turn ended underneath, which is neither a failure nor+ * a success and should not be painted as either.+ */+export type ToolState = 'queued' | 'running' | 'awaiting' | 'ok' | 'error' | 'declined' | 'stopped';++const TERMINAL: ReadonlySet<ToolState> = new Set<ToolState>(['ok', 'error', 'declined', 'stopped']);++export interface AgentToolEntry {+ kind: 'tool';+ id: string;+ name: string;+ input: Record<string, unknown>;+ /** Known once it actually starts; the model's request does not say. */+ effect: AgentEffect | null;+ state: ToolState;+ /** The result, shortened for one row. */+ summary: string | null;+ /** Why it needs saying out loud, while it is awaiting an answer. */+ reason: string | null;+}++export interface AgentProseEntry {+ kind: 'text' | 'thinking';+ text: string;+}++export interface AgentErrorEntry {+ kind: 'error';+ message: string;+}++export type AgentEntry = AgentProseEntry | AgentToolEntry | AgentErrorEntry;++export type TurnReason = 'end_turn' | 'aborted' | 'error' | 'refusal';++export interface AgentTurn {+ /** Position in the conversation; stable, so React keys are too. */+ id: number;+ prompt: string;+ entries: AgentEntry[];+ inputTokens: number;+ outputTokens: number;+ /** What one Undo would take back, once the turn ended. 0 means don't offer it. */+ steps: number;+ /** Where that Undo would go back to (EditorHistory.undoToMark). */+ mark: unknown | null;+ /** null while the turn is still running. */+ reason: TurnReason | null;+}++const IDLE: AgentStatus = {+ ready: false, conversation: false, phase: 'idle', model: null, error: null,+};++interface AgentState {+ status: AgentStatus;+ turns: AgentTurn[];+ /**+ * A conversation is open in THIS window. Tracked separately from+ * `status.conversation` because the automation hook is published off it and+ * has to be up before main can call back in — see {@link sendAgentMessage}.+ */+ driving: boolean;+}++export const useAgent = create<AgentState>(() => ({ status: IDLE, turns: [], driving: false }));++/** The run still taking events, if any. Only the last one can be open. */+const openTurn = (turns: readonly AgentTurn[]): AgentTurn | null => {+ const last = turns[turns.length - 1];+ return last && last.reason === null ? last : null;+};++const patchLast = (turns: readonly AgentTurn[], patch: Partial<AgentTurn>): AgentTurn[] =>+ turns.map((t, i) => (i === turns.length - 1 ? { ...t, ...patch } : t));++const withEntries = (turns: readonly AgentTurn[], entries: AgentEntry[]): AgentTurn[] =>+ patchLast(turns, { entries });++/** Append a delta to the trailing paragraph of the same kind, or start one. */+function appendProse(entries: readonly AgentEntry[], kind: 'text' | 'thinking', delta: string): AgentEntry[] {+ const last = entries[entries.length - 1];+ if (last?.kind === kind) {+ return [...entries.slice(0, -1), { kind, text: last.text + delta }];+ }+ return [...entries, { kind, text: delta }];+}++/** Rewrite the tool row `id` — a no-op if the turn never saw it asked for. */+function patchTool(entries: readonly AgentEntry[], id: string, patch: Partial<AgentToolEntry>): AgentEntry[] {+ return entries.map((e) => (e.kind === 'tool' && e.id === id ? { ...e, ...patch } : e));+}++/**+ * Fold one event into the runs. Pure: same turns + same event ⇒ same result, so+ * the projection is a unit test rather than something only an editor can show.+ *+ * Events for a turn that is not open are dropped rather than opening one. The+ * host can end a turn that never started (its checkpoint is taken before its own+ * try block), and inventing a run to hold that would put an empty row in the+ * transcript for something the user never asked.+ */+export function applyAgentEvent(turns: readonly AgentTurn[], event: AgentEvent): AgentTurn[] {+ if (event.type === 'turn_start') {+ return [...turns, {+ id: turns.length,+ prompt: event.prompt,+ entries: [],+ inputTokens: 0,+ outputTokens: 0,+ steps: 0,+ mark: null,+ reason: null,+ }];+ }++ const open = openTurn(turns);+ if (!open) return turns as AgentTurn[];++ switch (event.type) {+ case 'text':+ case 'thinking':+ return withEntries(turns, appendProse(open.entries, event.type, event.delta));++ case 'tool_call':+ return withEntries(turns, [...open.entries, {+ kind: 'tool',+ id: event.call.id,+ name: event.call.name,+ input: event.call.input,+ effect: null,+ state: 'queued',+ summary: null,+ reason: null,+ }]);++ case 'tool_start':+ return withEntries(turns, patchTool(open.entries, event.call.id, {+ state: 'running', effect: event.effect,+ }));++ case 'awaiting_confirm':+ return withEntries(turns, patchTool(open.entries, event.request.callId, {+ state: 'awaiting', reason: event.request.reason,+ }));++ case 'tool_end':+ return withEntries(turns, open.entries.map((e) => {+ if (e.kind !== 'tool' || e.id !== event.id) return e;+ // A row the user already declined stays declined: the kernel reports the+ // decline as an ordinary failed call, and painting it as an error would+ // blame the tool for the user's answer.+ const state: ToolState = e.state === 'declined' ? 'declined' : event.ok ? 'ok' : 'error';+ return { ...e, state, summary: event.summary };+ }));++ case 'usage':+ return patchLast(turns, {+ inputTokens: open.inputTokens + event.inputTokens,+ outputTokens: open.outputTokens + event.outputTokens,+ });++ case 'error':+ return withEntries(turns, [...open.entries, { kind: 'error', message: event.message }]);++ case 'turn_end':+ return patchLast(turns, {+ reason: event.reason,+ steps: event.steps,+ mark: event.mark,+ // Nothing will report on these now. Neither failed nor succeeded.+ entries: open.entries.map((e) =>+ (e.kind === 'tool' && !TERMINAL.has(e.state) ? { ...e, state: 'stopped' as const } : e)),+ });++ // The turn's outcome arrives as turn_end's reason; the raw stop is the+ // provider's business.+ case 'stop':+ return turns as AgentTurn[];+ }+}++/**+ * A conversation main still holds means this window is driving, whatever it+ * remembers — a renderer that reloaded mid-conversation would otherwise leave+ * the automation hook down under a session that is still alive.+ */+function adoptStatus(status: AgentStatus): void {+ useAgent.setState((s) => ({ status, driving: s.driving || status.conversation }));+}++export function applyAgentMessage(message: AgentMessage): void {+ if (message.kind === 'status') {+ adoptStatus(message.status);+ return;+ }+ useAgent.setState((s) => ({ turns: applyAgentEvent(s.turns, message.event) }));+}++/** Subscribe to main and adopt what it is already doing. Returns an unsubscribe. */+export function attachAgentBridge(): () => void {+ const off = window.estella?.agent?.onMessage(applyAgentMessage) ?? (() => {});+ void window.estella?.agent?.status().then(adoptStatus);+ return off;+}++export async function sendAgentMessage(text: string): Promise<void> {+ // Before the IPC, not after: main drives this window through+ // `window.__estellaEditor`, which is published only while a driver is+ // authorized (engine/automationGate.ts) and this store is what says so for the+ // built-in agent. Waiting for main's status to come back would race the first+ // tool call of the turn we are starting.+ useAgent.setState({ driving: true });+ const status = await window.estella?.agent?.send(text);+ if (status) adoptStatus(status);+}++export function stopAgentTurn(): void {+ void window.estella?.agent?.stop();+}++/**+ * Answer a pending confirmation. The row moves on the click rather than on+ * main's echo — the person just decided, and a row that sits on "waiting for+ * you" afterwards reads as a click that did not land.+ */+export function confirmAgentCall(callId: string, allow: boolean): void {+ useAgent.setState((s) => {+ const open = openTurn(s.turns);+ if (!open) return {};+ return {+ turns: patchLast(s.turns, {+ entries: patchTool(open.entries, callId, { state: allow ? 'running' : 'declined', reason: null }),+ }),+ };+ });+ void window.estella?.agent?.confirm(callId, allow);+}++/** Drop the conversation — a new one starts with the next message. */+export async function resetAgentSession(): Promise<void> {+ useAgent.setState({ turns: [], driving: false });+ const status = await window.estella?.agent?.reset();+ if (status) useAgent.setState({ status }); // not adoptStatus: reset just ended it+}++/** Whether an agent conversation authorizes the automation hook (main.tsx). */+export const agentDriving = (): boolean => useAgent.getState().driving;+export const subscribeAgent = (fn: () => void): (() => void) => useAgent.subscribe(fn);++export type { ConfirmRequest };diff --git a/desktop/tests/agent-host.test.ts b/desktop/tests/agent-host.test.tsnew file mode 100644index 000000000..c4760be78--- /dev/null+++ b/desktop/tests/agent-host.test.ts@@ -0,0 +1,191 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file The main-side owner of the agent conversation: what it refuses, what it+ * pushes to the window, and the two invariants the editor's mirror is+ * built on — every accepted send ends in exactly one turn_end, and every+ * confirmation is eventually answered.+ *+ * Pure TS: a fake provider, a fake driver, no Electron and no network.+ */+import { describe, it, expect, beforeEach, vi } from 'vitest';+import { createAgentHost, type AgentHost, type AgentMessage, type AgentStatus } from '../electron/agent/host';+import type { AgentProvider, AgentSession, StepEvent, ToolCall } from '../electron/agent/types';++const call = (name: string): ToolCall => ({ id: `c-${name}`, name, input: {} });+const asks = (...calls: ToolCall[]): StepEvent[] =>+ [...calls.map((c) => ({ type: 'tool_call' as const, call: c })), { type: 'stop' as const, reason: 'tool_use' as const }];+const ends = (): StepEvent[] => [{ type: 'stop', reason: 'end_turn' }];++/** A provider that replays scripted steps and counts how often it was built. */+function fakeProvider(steps: StepEvent[][]): AgentProvider {+ let at = 0;+ const session: AgentSession = {+ pushUser: () => {},+ pushContext: () => {},+ pushToolResults: () => {},+ step: async function* () {+ for (const ev of steps[at] ?? [{ type: 'stop', reason: 'end_turn' }]) yield ev;+ at++;+ },+ };+ return { id: 'fake', model: 'fake-model', createSession: () => session };+}++describe('the agent host', () => {+ let messages: AgentMessage[];+ let built: number;+ let keyed: boolean;+ let markFails: string | null;+ let driver: ReturnType<typeof vi.fn> & { js: unknown; op: unknown };++ /** The turn is over when the host says so — turn_end is emitted a microtask+ * earlier, from inside the kernel, before the host has settled anything. */+ const settled = (h: AgentHost): Promise<void> =>+ vi.waitFor(() => expect(h.status().phase).toBe('idle'));++ const host = (steps: StepEvent[][] = [ends()]): AgentHost => createAgentHost({+ driver: driver as never,+ push: (m) => messages.push(m),+ ready: () => keyed,+ provider: () => {+ built++;+ if (!keyed) throw new Error('No API key is configured. Add one in Settings › AI Agents.');+ return fakeProvider(steps);+ },+ });++ const events = () => messages.flatMap((m) => (m.kind === 'event' ? [m.event] : []));+ const statuses = (): AgentStatus[] => messages.flatMap((m) => (m.kind === 'status' ? [m.status] : []));+ const kinds = () => events().map((e) => e.type);++ beforeEach(() => {+ messages = [];+ built = 0;+ keyed = true;+ markFails = null;+ driver = vi.fn(async (method: string) => {+ if (method === 'mark') {+ if (markFails) throw new Error(markFails);+ return { seq: 1 };+ }+ if (method === 'stepsSince') return 2;+ if (method === 'getDiagnostics') return [];+ if (method === 'getSelectionIds') return [];+ return null;+ }) as never;+ (driver as { js: unknown }).js = vi.fn(async () => null);+ (driver as { op: unknown }).op = vi.fn(async () => null);+ });++ it('refuses without a credential, and names where to fix it', async () => {+ keyed = false;+ const h = host();+ const status = h.send('build me a menu');+ expect(status.error).toContain('Settings');+ expect(status.phase).toBe('idle');+ expect(kinds()).not.toContain('turn_start');+ });++ it('runs a turn and comes back to idle', async () => {+ const h = host();+ expect(h.send('hi').phase).toBe('running');+ await settled(h);+ expect(kinds()).toEqual(['turn_start', 'stop', 'turn_end']);+ expect(h.status().model).toBe('fake-model');+ });++ // The conversation is the point of a session: a follow-up that built a second+ // one would drop everything said so far and re-bill the whole prefix.+ it('keeps one session across follow-ups, and drops it on reset', async () => {+ const h = host([ends(), ends()]);+ h.send('first');+ await settled(h);+ h.send('second');+ await settled(h);+ expect(built).toBe(1);+ expect(h.status().conversation).toBe(true);++ expect(h.reset().conversation).toBe(false);+ h.send('third');+ await settled(h);+ expect(built).toBe(2); // re-reads the key, so a changed one takes effect+ });++ it('takes one message at a time', async () => {+ const h = host();+ h.send('first');+ const second = h.send('second');+ expect(second.error).toContain('still working');+ await settled(h);+ expect(kinds().filter((k) => k === 'turn_start')).toHaveLength(1);+ });++ // runTurn takes its checkpoint BEFORE its own try block, so it can reject+ // without ever starting. A window left on "running" by that has no way back.+ it('ends the turn even when it never started', async () => {+ markFails = 'no editor window';+ const h = host();+ h.send('hi');+ await settled(h);+ expect(events().filter((e) => e.type === 'turn_end')).toHaveLength(1);+ expect(events().at(-1)).toMatchObject({ type: 'turn_end', reason: 'error' });+ expect(h.status()).toMatchObject({ phase: 'idle', error: 'no editor window' });+ });++ describe('a tool that has to be confirmed', () => {+ it('parks the conversation until the person answers', async () => {+ const h = host([asks(call('save_scene')), ends()]);+ h.send('save it');+ await vi.waitFor(() => expect(h.status().phase).toBe('awaiting_confirm'));+ expect(statuses().at(-1)?.phase).toBe('awaiting_confirm');++ h.confirm('c-save_scene', true);+ await settled(h);+ expect(events().some((e) => e.type === 'tool_end' && e.ok)).toBe(true);+ });++ it('tells the model a decline is an answer, not a failure to retry', async () => {+ const h = host([asks(call('save_scene')), ends()]);+ h.send('save it');+ await vi.waitFor(() => expect(h.status().phase).toBe('awaiting_confirm'));+ h.confirm('c-save_scene', false);+ await settled(h);+ expect(events().some((e) => e.type === 'tool_end' && e.summary === 'declined')).toBe(true);+ });++ // Aborting does not interrupt a promise that is waiting on the USER; the+ // kernel would sit there forever, and the turn would never end.+ it('is answered by Stop rather than left hanging', async () => {+ const h = host([asks(call('save_scene')), ends()]);+ h.send('save it');+ await vi.waitFor(() => expect(h.status().phase).toBe('awaiting_confirm'));+ h.stop();+ await settled(h);+ expect(events().at(-1)).toMatchObject({ type: 'turn_end' });+ });++ it('is answered by a reset too', async () => {+ const h = host([asks(call('save_scene')), ends()]);+ h.send('save it');+ await vi.waitFor(() => expect(h.status().phase).toBe('awaiting_confirm'));+ h.reset();+ await vi.waitFor(() => expect(events().at(-1)).toMatchObject({ type: 'turn_end' }));+ expect(h.status().phase).toBe('idle');+ });++ it('ignores an answer to a call nobody is waiting on', async () => {+ const h = host();+ expect(() => h.confirm('c-gone', true)).not.toThrow();+ });+ });++ // The mirror renders from these, so a state it never hears about is one the+ // window shows wrong until something else happens to push.+ it('pushes a status on every transition', async () => {+ const h = host();+ h.send('hi');+ await settled(h);+ expect(statuses().map((s) => s.phase)).toEqual(['running', 'idle']);+ });+});diff --git a/desktop/tests/agent-kernel.test.ts b/desktop/tests/agent-kernel.test.tsindex ef3d508bb..8d8c66d23 100644--- a/desktop/tests/agent-kernel.test.ts+++ b/desktop/tests/agent-kernel.test.ts@@ -71,8 +71,10 @@ describe('the agent turn', () => {const out = await runTurn(deps(s), 'hi', null, new AbortController().signal);expect(out.mark).toEqual({ seq: 7 });expect(out.steps).toBe(3);- expect(events.at(0)).toEqual({ type: 'turn_start' });- expect(events.at(-1)).toEqual({ type: 'turn_end', steps: 3, reason: 'end_turn' });+ // Both carry what the editor's read model needs and cannot infer across IPC:+ // what was asked, and the point an Undo would go back to.+ expect(events.at(0)).toEqual({ type: 'turn_start', prompt: 'hi' });+ expect(events.at(-1)).toEqual({ type: 'turn_end', steps: 3, mark: { seq: 7 }, reason: 'end_turn' });});it('runs an undoable edit without asking — the checkpoint is the approval', async () => {diff --git a/desktop/tests/agent-transcript.test.ts b/desktop/tests/agent-transcript.test.tsnew file mode 100644index 000000000..7a84ebacf--- /dev/null+++ b/desktop/tests/agent-transcript.test.ts@@ -0,0 +1,152 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file Folding main's event stream into the runs the drawer draws. Pure, so it+ * is tested here rather than by looking at an editor: the projection is+ * where a streamed delta becomes a paragraph, a requested call becomes a+ * queued row, and a turn that ended underneath its own tools stops+ * claiming they are still running.+ */+import { describe, it, expect } from 'vitest';+import { applyAgentEvent, type AgentTurn, type AgentToolEntry } from '../src/store/AgentStore';+import type { AgentEvent, ToolCall } from '../electron/agent/types';++const fold = (...events: AgentEvent[]): AgentTurn[] =>+ events.reduce<AgentTurn[]>((turns, e) => applyAgentEvent(turns, e), []);++const started = (prompt = 'add a pause menu'): AgentEvent => ({ type: 'turn_start', prompt });+const ended = (over: Partial<{ steps: number; mark: unknown; reason: 'end_turn' | 'aborted' | 'error' | 'refusal' }> = {}): AgentEvent =>+ ({ type: 'turn_end', steps: 0, mark: null, reason: 'end_turn', ...over });+const call = (name: string): ToolCall => ({ id: `c-${name}`, name, input: { a: 1 } });+const tools = (t: AgentTurn): AgentToolEntry[] => t.entries.filter((e): e is AgentToolEntry => e.kind === 'tool');++describe('the transcript projection', () => {+ it('opens a run per turn, carrying what was asked', () => {+ const turns = fold(started('one'), ended(), started('two'));+ expect(turns.map((t) => t.prompt)).toEqual(['one', 'two']);+ expect(turns.map((t) => t.reason)).toEqual(['end_turn', null]);+ });++ it('gathers a streamed answer into one paragraph', () => {+ const [turn] = fold(+ started(),+ { type: 'text', delta: 'The scene ' },+ { type: 'text', delta: 'has 58 entities.' },+ );+ expect(turn.entries).toEqual([{ kind: 'text', text: 'The scene has 58 entities.' }]);+ });++ // Reasoning and answer are different rows; concatenating them would put the+ // thinking inside the sentence the user is meant to read.+ it('keeps thinking and answer apart, and reopens a paragraph per switch', () => {+ const [turn] = fold(+ started(),+ { type: 'thinking', delta: 'look at the UI layer' },+ { type: 'text', delta: 'Building it now.' },+ { type: 'thinking', delta: 'now the panel' },+ );+ expect(turn.entries.map((e) => e.kind)).toEqual(['thinking', 'text', 'thinking']);+ });++ // The doc's "parallel, greyed, not three spinners": asked-for is not running.+ it('shows a requested call as queued until it actually starts', () => {+ const asked = fold(started(), { type: 'tool_call', call: call('set_field') });+ expect(tools(asked[0])[0]).toMatchObject({ state: 'queued', effect: null, name: 'set_field' });++ const running = applyAgentEvent(asked, { type: 'tool_start', call: call('set_field'), effect: 'undoable' });+ expect(tools(running[0])[0]).toMatchObject({ state: 'running', effect: 'undoable' });+ });++ it('carries a call through to its result', () => {+ const [turn] = fold(+ started(),+ { type: 'tool_call', call: call('add_entity') },+ { type: 'tool_start', call: call('add_entity'), effect: 'undoable' },+ { type: 'tool_end', id: 'c-add_entity', ok: true, summary: '7 created' },+ );+ expect(tools(turn)[0]).toMatchObject({ state: 'ok', summary: '7 created' });+ });++ it('marks a failed call as failed', () => {+ const [turn] = fold(+ started(),+ { type: 'tool_call', call: call('set_field') },+ { type: 'tool_end', id: 'c-set_field', ok: false, summary: 'no such component' },+ );+ expect(tools(turn)[0].state).toBe('error');+ });++ it('waits on the person, and says why', () => {+ const [turn] = fold(+ started(),+ { type: 'tool_call', call: call('save_scene') },+ { type: 'tool_start', call: call('save_scene'), effect: 'irreversible' },+ {+ type: 'awaiting_confirm',+ request: { callId: 'c-save_scene', tool: 'save_scene', reason: 'writes outside the scene', input: {} },+ },+ );+ expect(tools(turn)[0]).toMatchObject({ state: 'awaiting', reason: 'writes outside the scene' });+ });++ // The kernel reports a decline as an ordinary failed call, because that is what+ // the MODEL is told. Painting it red would blame the tool for the user's answer.+ it('leaves a declined call declined rather than calling it an error', () => {+ const declined = fold(+ started(),+ { type: 'tool_call', call: call('save_scene') },+ ).map((t) => ({+ ...t,+ entries: t.entries.map((e) => (e.kind === 'tool' ? { ...e, state: 'declined' as const } : e)),+ }));+ const after = applyAgentEvent(declined, { type: 'tool_end', id: 'c-save_scene', ok: false, summary: 'declined' });+ expect(tools(after[0])[0].state).toBe('declined');+ });++ it('adds up usage across the turn\'s several model calls', () => {+ const [turn] = fold(+ started(),+ { type: 'usage', inputTokens: 1200, outputTokens: 80 },+ { type: 'usage', inputTokens: 1400, outputTokens: 30 },+ );+ expect(turn).toMatchObject({ inputTokens: 2600, outputTokens: 110 });+ });++ it('records what one Undo would take back, and where to', () => {+ const [turn] = fold(started(), ended({ steps: 7, mark: { seq: 12 } }));+ expect(turn).toMatchObject({ steps: 7, mark: { seq: 12 }, reason: 'end_turn' });+ });++ // Stop lands while calls are in flight. Leaving them "running" is a transcript+ // that says work is still happening after the turn is over.+ it('stops claiming a call is running once the turn ends under it', () => {+ const [turn] = fold(+ started(),+ { type: 'tool_call', call: call('set_field') },+ { type: 'tool_start', call: call('set_field'), effect: 'undoable' },+ { type: 'tool_call', call: call('add_entity') },+ { type: 'tool_end', id: 'c-set_field', ok: true, summary: 'ok' },+ ended({ reason: 'aborted' }),+ );+ expect(tools(turn).map((t) => t.state)).toEqual(['ok', 'stopped']);+ });++ it('puts an error into the run it happened in', () => {+ const [turn] = fold(started(), { type: 'error', message: 'rate limited' }, ended({ reason: 'error' }));+ expect(turn.entries).toEqual([{ kind: 'error', message: 'rate limited' }]);+ });++ // The host ends a turn that never started (runTurn takes its checkpoint before+ // its own try block). Inventing a run to hold that would put a promptless row+ // in the transcript for something the user never asked for.+ it('drops events that belong to no open run', () => {+ expect(fold(ended())).toEqual([]);+ expect(fold({ type: 'text', delta: 'stray' })).toEqual([]);+ expect(fold(started(), ended(), { type: 'text', delta: 'late' })[0].entries).toEqual([]);+ });++ it('leaves the runs alone for a raw stop — the outcome arrives with turn_end', () => {+ const before = fold(started());+ expect(applyAgentEvent(before, { type: 'stop', reason: 'tool_use' })).toEqual(before);+ });+});diff --git a/desktop/tests/automation-gate.test.ts b/desktop/tests/automation-gate.test.tsindex c01ac0884..241165892 100644--- a/desktop/tests/automation-gate.test.ts+++ b/desktop/tests/automation-gate.test.ts@@ -16,15 +16,16 @@ describe('the automation hook gate', () => {let listeners: Array<() => void>;let running: boolean;let launchFlag: boolean;+ let driving: boolean;- /** Stands in for McpStore: notify, and the gate re-reads. */+ /** Stands in for McpStore / AgentStore: notify, and the gate re-reads. */const subscribe = (fn: () => void) => {listeners.push(fn);return () => { listeners = listeners.filter((l) => l !== fn); };};const notify = () => listeners.forEach((l) => l());const guard = () => guardAutomationHook(- () => launchFlag || running, subscribe, publish, retract,+ () => launchFlag || running || driving, subscribe, publish, retract,);beforeEach(() => {@@ -33,6 +34,7 @@ describe('the automation hook gate', () => {listeners = [];running = false;launchFlag = false;+ driving = false;});it('publishes nothing for an ordinary editor', () => {@@ -87,6 +89,30 @@ describe('the automation hook gate', () => {expect(retract).not.toHaveBeenCalled();});+ // The built-in agent reaches this window through the same hook. A conversation+ // that cannot see it is an agent whose every tool call fails with a TypeError —+ // the exact regression this file exists for, arriving by a third door.+ it('publishes for the built-in agent, with no endpoint listening', () => {+ guard();+ driving = true;+ notify();+ expect(publish).toHaveBeenCalledTimes(1);+ });++ it('keeps the hook while EITHER a client or the built-in agent is driving', () => {+ running = true;+ guard();+ driving = true;+ notify();+ running = false; // the setting went off mid-conversation+ notify();+ expect(retract).not.toHaveBeenCalled();++ driving = false;+ notify();+ expect(retract).toHaveBeenCalledTimes(1);+ });+it('stops watching when the realm is torn down', () => {const stop = guard();stop();