Skip to content

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.

feat(editor): a conversation is kept with the project, memory and all

esengine90aa1aecee1b
diff --git a/desktop/electron/agent/anthropic.ts b/desktop/electron/agent/anthropic.ts
index 3210dbc99..65eefc986 100644
--- a/desktop/electron/agent/anthropic.ts
+++ b/desktop/electron/agent/anthropic.ts
@@ -276,13 +276,30 @@ function firstText(message: Message | undefined): string {
return flat.length > 200 ? `${flat.slice(0, 197)}…` : flat;
}
+/** What a conversation's memory looks like on disk. Versioned: a shape this
+ * does not recognise is refused rather than half-read. */
+interface SessionMemory {
+ v: 1;
+ messages: Message[];
+ turnStarts: number[];
+ dropped: number;
+ folded: string[];
+ lastInputTokens: number;
+}
+
+const isSessionMemory = (value: unknown): value is SessionMemory => {
+ const m = value as Partial<SessionMemory> | null;
+ return !!m && m.v === 1 && Array.isArray(m.messages) && Array.isArray(m.turnStarts)
+ && typeof m.dropped === 'number' && Array.isArray(m.folded);
+};
+
class AnthropicSession implements AgentSession {
- private readonly messages: Message[] = [];
+ private messages: Message[] = [];
/** Context waiting for a legal spot — see {@link flushContext}. */
private readonly pending: string[] = [];
/** Where each person's turn starts. A tool result is a `user` message too, so
* counting roles would not find them. */
- private readonly turnStarts: number[] = [];
+ private turnStarts: number[] = [];
/** Runs folded away by {@link compactOldest}. Turn coordinates count from the
* start of the CONVERSATION, so they must survive their messages. */
private dropped = 0;
@@ -303,6 +320,36 @@ class AnthropicSession implements AgentSession {
return this.dropped + this.turnStarts.length;
}
+ /**
+ * Everything the model remembers, and nothing about how it got there.
+ *
+ * `pending` is deliberately absent: it holds context gathered for a turn that
+ * has not been sent, which describes an editor state that will be re-gathered
+ * anyway. Restoring it would replay a stale reading of the scene as if it were
+ * current — the one thing the per-turn context exists to avoid.
+ */
+ serialize(): SessionMemory {
+ return {
+ v: 1,
+ messages: this.messages,
+ turnStarts: this.turnStarts,
+ dropped: this.dropped,
+ folded: this.folded,
+ lastInputTokens: this.lastInputTokens,
+ };
+ }
+
+ /** Put a serialized memory back. Anything else leaves the session empty —
+ * see AgentProvider.createSession on why that beats refusing. */
+ restore(memory: unknown): void {
+ if (!isSessionMemory(memory)) return;
+ this.messages = memory.messages;
+ this.turnStarts = memory.turnStarts;
+ this.dropped = memory.dropped;
+ this.folded = memory.folded;
+ this.lastInputTokens = memory.lastInputTokens ?? 0;
+ }
+
pushUser(text: string): void {
this.turnStarts.push(this.messages.length);
this.messages.push({ role: 'user', content: text });
@@ -524,11 +571,15 @@ export function createAnthropicProvider(options: AnthropicOptions): AgentProvide
model,
// The same condition toolResultContent substitutes on — one fact, one place.
acceptsImages: dialect === 'anthropic',
- createSession: ({ system, tools }) => new AnthropicSession(
- client,
- { model, effort, dialect, contextWindow: options.contextWindow || DEFAULT_CONTEXT_WINDOW },
- system,
- tools,
- ),
+ createSession: ({ system, tools }, memory) => {
+ const session = new AnthropicSession(
+ client,
+ { model, effort, dialect, contextWindow: options.contextWindow || DEFAULT_CONTEXT_WINDOW },
+ system,
+ tools,
+ );
+ if (memory !== undefined) session.restore(memory);
+ return session;
+ },
};
}
diff --git a/desktop/electron/agent/host.ts b/desktop/electron/agent/host.ts
index bdaf85223..c9fec4743 100644
--- a/desktop/electron/agent/host.ts
+++ b/desktop/electron/agent/host.ts
@@ -57,6 +57,22 @@ export interface AgentHostDeps {
ready(): boolean;
/** Build the provider, or throw with a sentence the user can act on. */
provider(): AgentProvider;
+ /**
+ * Keep this conversation, or forget it. Absent (no project open) means the
+ * conversation is not persisted, which is a fine state to be in — it is not
+ * an error, and the host carries on either way.
+ */
+ persist?(conversation: PersistedConversation): void;
+}
+
+/** A conversation as the host hands it over to be kept. See agent/store.ts. */
+export interface PersistedConversation {
+ id: string;
+ startedAt: number;
+ model: string;
+ endpoint: string;
+ events: readonly AgentEvent[];
+ memory: unknown;
}
export interface AgentHost {
@@ -71,6 +87,8 @@ export interface AgentHost {
confirm(callId: string, answer: ConfirmAnswer, declined?: readonly number[]): void;
/** Drop the conversation and start over; the next turn re-reads the key. */
reset(): AgentStatus;
+ /** Put a saved conversation back — transcript and memory both. */
+ resume(conversation: PersistedConversation): AgentStatus;
/**
* Ask the `n`-th turn again, discarding it and everything after. The point of
* having it: a bad answer three turns in should cost you that answer, not the
@@ -100,6 +118,35 @@ export interface AgentHost {
export function createAgentHost(deps: AgentHostDeps): AgentHost {
let session: AgentSession | null = null;
let model: string | null = null;
+ // Names the conversation on disk. Minted when a session is, so a reset starts
+ // a new file rather than overwriting the one the user may want back.
+ let conversationId: string | null = null;
+ let startedAt = 0;
+ let endpoint = '';
+ /** Memory handed to the next session this creates — see {@link AgentHost.resume}. */
+ let resuming: unknown;
+
+ /** Sortable and filename-safe. Time first so a directory listing reads
+ * chronologically even before anything parses it. */
+ const newId = (): string =>
+ `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
+
+ /**
+ * Hand the conversation over to be kept. Called when a turn ends rather than
+ * on every event: a run is the unit anyone would want back, and the stream
+ * carries one event per token.
+ */
+ const keep = (): void => {
+ if (!deps.persist || !conversationId || !session) return;
+ deps.persist({
+ id: conversationId,
+ startedAt,
+ model: model ?? '',
+ endpoint,
+ events: log,
+ memory: session.serialize(),
+ });
+ };
let acceptsImages = true;
let phase: AgentPhase = 'idle';
let error: string | null = null;
@@ -164,9 +211,12 @@ export function createAgentHost(deps: AgentHostDeps): AgentHost {
if (!session) {
try {
const provider = deps.provider();
- session = provider.createSession({ system: SYSTEM_PROMPT, tools: agentTools() });
+ session = provider.createSession({ system: SYSTEM_PROMPT, tools: agentTools() }, resuming);
model = provider.model;
acceptsImages = provider.acceptsImages;
+ endpoint = provider.id;
+ if (!conversationId) { conversationId = newId(); startedAt = Date.now(); }
+ resuming = undefined;
} catch (e) {
error = (e as Error)?.message ?? String(e);
pushStatus();
@@ -206,6 +256,9 @@ export function createAgentHost(deps: AgentHostDeps): AgentHost {
emit({ type: 'turn_end', steps: 0, mark: null, reason: 'error' });
} finally {
settlePending();
+ // The run is over either way — errors included, since a conversation
+ // that ended badly is still one you may want back.
+ if (running === controller) keep();
// 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.
@@ -248,6 +301,10 @@ export function createAgentHost(deps: AgentHostDeps): AgentHost {
settlePending();
session = null;
model = null;
+ // A new conversation is a new file. The old one keeps whatever it had at
+ // its last turn — it was saved then, and nothing here takes that back.
+ conversationId = null;
+ resuming = undefined;
phase = 'idle';
error = null;
log.length = 0;
@@ -257,6 +314,36 @@ export function createAgentHost(deps: AgentHostDeps): AgentHost {
pushStatus();
return status();
},
+ /**
+ * Continue a saved conversation: its transcript for the window, its memory
+ * for the model.
+ *
+ * The session is not built here — it is built by the next `send`, from the
+ * provider the endpoint resolves to THEN. Building it now would pin the
+ * conversation to whatever provider happens to be configured at the moment
+ * of clicking, which is not the same thing as the moment of asking.
+ */
+ resume: (conversation) => {
+ running?.abort();
+ running = null;
+ settlePending();
+ session = null;
+ model = conversation.model;
+ conversationId = conversation.id;
+ startedAt = conversation.startedAt;
+ endpoint = conversation.endpoint;
+ resuming = conversation.memory;
+ phase = 'idle';
+ error = null;
+ log.length = 0;
+ log.push(...conversation.events);
+ // Reset first so a window holding another conversation drops it, then
+ // replay: the same pair an attaching window gets, in the same order.
+ deps.push({ kind: 'event', event: { type: 'conversation_reset' } });
+ for (const event of conversation.events) deps.push({ kind: 'event', event });
+ pushStatus();
+ return status();
+ },
transcript: () => log,
};
}
diff --git a/desktop/electron/agent/store.ts b/desktop/electron/agent/store.ts
new file mode 100644
index 000000000..9c7f95be2
--- /dev/null
+++ b/desktop/electron/agent/store.ts
@@ -0,0 +1,171 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file store.ts
+ * @brief Agent conversations on disk, under `<root>/.esengine/agent/`.
+ *
+ * A conversation used to live only in main's memory: quitting the editor threw
+ * away everything that had been said, and there was no way back to yesterday's
+ * work. It is project-local for the same reason autosave is — what was asked and
+ * what it did are about THIS project — and it sits beside the other things in
+ * `.esengine`, which is a build artifact directory nobody commits.
+ *
+ * TWO THINGS ARE SAVED, and the difference matters. The EVENT STREAM is what the
+ * window replays to draw the transcript. The MEMORY is what the model needs to
+ * carry on, in the provider's own format. Saving only the first would give you a
+ * conversation you can read and cannot continue — the transcript would say the
+ * agent knows what you discussed, and it would not.
+ *
+ * Screenshots are dropped on the way to disk. A frame the agent looked at is
+ * hundreds of kilobytes of base64, and a run with a few of them would dominate
+ * the file; what it SAW is worth much less afterwards than what it did, which
+ * the tool result already says. The row keeps its result and loses its picture.
+ */
+import { writeFile, readFile, mkdir, readdir, rm, stat } from 'node:fs/promises';
+import path from 'node:path';
+import { WORKSPACE_DIR } from '../../src/project/format';
+import type { AgentEvent } from './types';
+
+const AGENT_SUBDIR = 'agent';
+const FORMAT = 1;
+
+/** One conversation as it sits on disk. */
+export interface StoredConversation {
+ v: number;
+ id: string;
+ startedAt: number;
+ updatedAt: number;
+ /** What was asked first — the conversation's name in a list. */
+ title: string;
+ /**
+ * Which model and endpoint this memory was produced by. A memory belongs to
+ * its author: reasoning blocks go back to the model that wrote them. Resuming
+ * under a different one is refused rather than attempted.
+ */
+ model: string;
+ endpoint: string;
+ events: AgentEvent[];
+ /** Opaque provider state — see AgentSession.serialize. */
+ memory: unknown;
+}
+
+/** A conversation without its contents, for listing. */
+export type ConversationSummary = Pick<
+ StoredConversation, 'id' | 'startedAt' | 'updatedAt' | 'title' | 'model'
+> & { turns: number };
+
+const dirFor = (root: string): string => path.join(root, WORKSPACE_DIR, AGENT_SUBDIR);
+const fileFor = (root: string, id: string): string => path.join(dirFor(root), `${id}.json`);
+
+/** Ids are ours, but they name a file — so anything that could leave the
+ * directory is refused rather than sanitised into something else's path. */
+const isSafeId = (id: string): boolean => /^[A-Za-z0-9_-]{1,64}$/.test(id);
+
+/**
+ * The event stream as it should be kept: without the frames.
+ *
+ * `image` is the only field that carries bulk, and it is on tool_end, whose
+ * `summary` already says what the call answered.
+ */
+function withoutImages(events: readonly AgentEvent[]): AgentEvent[] {
+ return events.map((e) => {
+ if (e.type !== 'tool_end' || !e.image) return e;
+ const { image, ...rest } = e;
+ void image;
+ return rest as AgentEvent;
+ });
+}
+
+/** The first thing the person asked, clipped to something a list can show. */
+function titleOf(events: readonly AgentEvent[]): string {
+ for (const e of events) {
+ if (e.type === 'turn_start' && e.prompt.trim()) {
+ const one = e.prompt.trim().replace(/\s+/g, ' ');
+ return one.length > 80 ? `${one.slice(0, 79)}…` : one;
+ }
+ }
+ return '';
+}
+
+const countTurns = (events: readonly AgentEvent[]): number =>
+ events.reduce((n, e) => n + (e.type === 'turn_start' ? 1 : 0), 0);
+
+/** Write a conversation, replacing whatever was under that id. */
+export async function saveConversation(
+ root: string,
+ conversation: Omit<StoredConversation, 'v' | 'title' | 'updatedAt' | 'events'>
+ & { events: readonly AgentEvent[] },
+): Promise<void> {
+ if (!isSafeId(conversation.id)) return;
+ const stored: StoredConversation = {
+ ...conversation,
+ v: FORMAT,
+ title: titleOf(conversation.events),
+ updatedAt: Date.now(),
+ events: withoutImages(conversation.events),
+ };
+ await mkdir(dirFor(root), { recursive: true });
+ await writeFile(fileFor(root, conversation.id), `${JSON.stringify(stored)}\n`, 'utf8');
+}
+
+/** One conversation in full, or null when it is absent or unreadable. */
+export async function loadConversation(
+ root: string,
+ id: string,
+): Promise<StoredConversation | null> {
+ if (!isSafeId(id)) return null;
+ try {
+ const parsed = JSON.parse(await readFile(fileFor(root, id), 'utf8')) as StoredConversation;
+ // A file written by a newer editor is not something this one can read
+ // halfway: refusing leaves it intact for the editor that can.
+ return parsed?.v === FORMAT ? parsed : null;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Every conversation this project has, newest first.
+ *
+ * Reads each file to summarise it. That is fine at this scale — a project
+ * accumulates conversations at human speed — and it keeps the directory itself
+ * the index, so a file deleted by hand is simply gone rather than a dangling row.
+ */
+export async function listConversations(root: string): Promise<ConversationSummary[]> {
+ let names: string[];
+ try {
+ names = await readdir(dirFor(root));
+ } catch {
+ return [];
+ }
+ const out: ConversationSummary[] = [];
+ for (const name of names) {
+ if (!name.endsWith('.json')) continue;
+ const stored = await loadConversation(root, name.slice(0, -5));
+ if (!stored) continue;
+ out.push({
+ id: stored.id,
+ startedAt: stored.startedAt,
+ updatedAt: stored.updatedAt,
+ title: stored.title,
+ model: stored.model,
+ turns: countTurns(stored.events),
+ });
+ }
+ return out.sort((a, b) => b.updatedAt - a.updatedAt);
+}
+
+/** Forget one. Missing is success — the caller wanted it gone. */
+export async function deleteConversation(root: string, id: string): Promise<void> {
+ if (!isSafeId(id)) return;
+ await rm(fileFor(root, id), { force: true });
+}
+
+/** Whether this project has any saved conversation at all. */
+export async function hasConversations(root: string): Promise<boolean> {
+ try {
+ return (await stat(dirFor(root))).isDirectory() && (await readdir(dirFor(root))).length > 0;
+ } catch {
+ return false;
+ }
+}
diff --git a/desktop/electron/agent/types.ts b/desktop/electron/agent/types.ts
index 2ff2d78e4..7920f0230 100644
--- a/desktop/electron/agent/types.ts
+++ b/desktop/electron/agent/types.ts
@@ -105,6 +105,16 @@ export interface AgentSession {
rewindTo(n: number): void;
/** Run one model call. */
step(signal: AbortSignal): AsyncIterable<StepEvent>;
+ /**
+ * The model's memory of this conversation, as JSON, so it can be put back.
+ *
+ * Opaque on purpose. What a model remembers is in the provider's wire format
+ * — reasoning blocks that must return byte-identical, a prefix the cache
+ * matches on — and the moment anything above here could read it, the kernel
+ * and the host would be reasoning about that format, which is what this
+ * contract exists to keep out of them. They hand it back and ask no questions.
+ */
+ serialize(): unknown;
}
export interface AgentProvider {
@@ -120,7 +130,21 @@ export interface AgentProvider {
* can plan around being blind instead of discovering it.
*/
readonly acceptsImages: boolean;
- createSession(opts: { system: string; tools: readonly CatalogTool[] }): AgentSession;
+ /**
+ * Start a conversation, or resume one from what {@link AgentSession.serialize}
+ * returned.
+ *
+ * A resumed memory belongs to the model that produced it — reasoning blocks
+ * go back to their author and the cached prefix is a byte match — so the
+ * caller must only hand back memory it saved under this same provider and
+ * model. A provider that cannot make sense of what it is given starts fresh
+ * rather than failing: a conversation you cannot continue is worth less than
+ * a new one, and far less than a crash.
+ */
+ createSession(
+ opts: { system: string; tools: readonly CatalogTool[] },
+ memory?: unknown,
+ ): AgentSession;
}
/**
diff --git a/desktop/electron/main.ts b/desktop/electron/main.ts
index cc54ea259..d9b790e49 100644
--- a/desktop/electron/main.ts
+++ b/desktop/electron/main.ts
@@ -47,6 +47,9 @@ import { mcpMode, startMcpEndpoint, stopMcpEndpoint, mcpEndpointStatus } from '.
import { secretStatus, setSecret, clearSecret, readSecret } from './secrets';
import { createSurfaceDriver } from './surfaceDriver';
import { createAgentHost } from './agent/host';
+import {
+ saveConversation, loadConversation, listConversations, deleteConversation,
+} from './agent/store';
import type { ConfirmAnswer } from './agent/types';
import { createAnthropicProvider } from './agent/anthropic';
@@ -696,6 +699,15 @@ const agentHost = createAgentHost({
contextWindow: agentEndpoint.contextWindow,
});
},
+ // Conversations are kept with the project they are about. With none open
+ // there is nowhere for them to go, which is a state, not a failure — and a
+ // disk that will not take them must never cost the user their turn, so this
+ // reports and moves on.
+ persist: (conversation) => {
+ if (!projectRoot) return;
+ void saveConversation(projectRoot, conversation)
+ .catch((e) => console.error('[agent] could not save the conversation:', e));
+ },
});
ipcMain.handle('agent:status', () => agentHost.status());
ipcMain.handle('agent:transcript', () => agentHost.transcript());
@@ -707,6 +719,18 @@ ipcMain.handle(
);
ipcMain.handle('agent:reset', () => agentHost.reset());
ipcMain.handle('agent:retry', (_e, n: number, text: string) => agentHost.retry(n, text));
+// — Saved conversations (agent/store.ts). Project-local, so an unopened project
+// simply has none rather than erroring. —
+ipcMain.handle('agent:conversations', () => (projectRoot ? listConversations(projectRoot) : []));
+ipcMain.handle('agent:resumeConversation', async (_e, id: string) => {
+ if (!projectRoot) return agentHost.status();
+ const stored = await loadConversation(projectRoot, id);
+ if (!stored) return agentHost.status();
+ return agentHost.resume(stored);
+});
+ipcMain.handle('agent:deleteConversation', async (_e, id: string) => {
+ if (projectRoot) await deleteConversation(projectRoot, id);
+});
ipcMain.handle('agent:setEndpoint', (_e, patch: { baseUrl?: string; model?: string; keyId?: string; contextWindow?: number }) => {
agentEndpoint = { ...agentEndpoint, ...patch };
// `ready` is derived from which key this points at, so it just changed.
diff --git a/desktop/electron/preload.ts b/desktop/electron/preload.ts
index 3d9c27a3b..2e579edda 100644
--- a/desktop/electron/preload.ts
+++ b/desktop/electron/preload.ts
@@ -23,6 +23,7 @@ import type { McpEndpointStatus } from './mcpEndpoint';
import type { SecretStatus } from './secrets';
import type { AgentStatus, AgentMessage } from './agent/host';
import type { AgentEvent, ConfirmAnswer } from './agent/types';
+import type { ConversationSummary } from './agent/store';
// 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.
@@ -126,6 +127,13 @@ const api = {
reset: (): Promise<AgentStatus> => ipcRenderer.invoke('agent:reset'),
/** Ask the n-th turn again, discarding it and everything after it. */
retry: (n: number, text: string): Promise<AgentStatus> => ipcRenderer.invoke('agent:retry', n, text),
+ /** Every conversation saved with this project, newest first. */
+ conversations: (): Promise<ConversationSummary[]> => ipcRenderer.invoke('agent:conversations'),
+ /** Continue a saved one — its transcript and the model's memory of it. */
+ resumeConversation: (id: string): Promise<AgentStatus> =>
+ ipcRenderer.invoke('agent:resumeConversation', id),
+ deleteConversation: (id: string): Promise<void> =>
+ ipcRenderer.invoke('agent:deleteConversation', id),
/** Point the NEXT session at an endpoint/model. Merged, so each settings row
* can push its own field. */
setEndpoint: (patch: { baseUrl?: string; model?: string; keyId?: string; contextWindow?: number }): Promise<void> =>
diff --git a/desktop/tests/agent-host.test.ts b/desktop/tests/agent-host.test.ts
index 1d34972f6..765019e6a 100644
--- a/desktop/tests/agent-host.test.ts
+++ b/desktop/tests/agent-host.test.ts
@@ -9,7 +9,10 @@
* 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 {
+ createAgentHost,
+ type AgentHost, type AgentMessage, type AgentStatus, type PersistedConversation,
+} from '../electron/agent/host';
import type { AgentProvider, AgentSession, StepEvent, ToolCall } from '../electron/agent/types';
const call = (name: string): ToolCall => ({ id: `c-${name}`, name, input: {} });
@@ -21,7 +24,7 @@ const ends = (): StepEvent[] => [{ type: 'stop', reason: 'end_turn' }];
function fakeProvider(steps: StepEvent[][]): AgentProvider & { session: AgentSession & { asked: string[]; rewinds: number[] } } {
let at = 0;
const session: AgentSession & { asked: string[]; rewinds: number[] } = {
- asked: [],
+ asked: [] as string[],
rewinds: [],
// The real one counts person's turns; asking is what opens them.
get turnIndex() { return session.asked.length; },
@@ -31,12 +34,22 @@ function fakeProvider(steps: StepEvent[][]): AgentProvider & { session: AgentSes
// Faithful about the coordinate too: rewinding drops those turns, so the
// next one reopens at n — which is what the host stamps onto turn_start.
rewindTo: (n) => { session.rewinds.push(n); session.asked.length = n; },
+ serialize: () => ({ asked: [...session.asked] }),
step: async function* () {
for (const ev of steps[at] ?? [{ type: 'stop', reason: 'end_turn' }]) yield ev;
at++;
},
};
- return { id: 'fake', model: 'fake-model', acceptsImages: true, session, createSession: () => session };
+ return {
+ id: 'fake', model: 'fake-model', acceptsImages: true, session,
+ createSession: (_opts, memory) => {
+ // Faithful to the real one: a resumed memory replaces what the session
+ // remembers, so the turns it has already had are its own again.
+ const m = memory as { asked?: string[] } | undefined;
+ if (m?.asked) session.asked = [...m.asked];
+ return session;
+ },
+ };
}
describe('the agent host', () => {
@@ -278,3 +291,141 @@ describe('the agent host', () => {
});
});
});
+
+/**
+ * Keeping a conversation, and putting it back.
+ *
+ * The host owns both halves — the event stream the window draws from and the
+ * memory the model needs — so it is the only place that can be asked whether
+ * they stay together.
+ */
+describe('a conversation that outlives the session', () => {
+ let messages: AgentMessage[];
+ let kept: PersistedConversation[];
+ let driver: ReturnType<typeof vi.fn> & { js: unknown; op: unknown };
+
+ const settled = (h: AgentHost): Promise<void> =>
+ vi.waitFor(() => expect(h.status().phase).toBe('idle'));
+
+ const host = (steps: StepEvent[][] = [ends(), ends()]): AgentHost => createAgentHost({
+ driver: driver as never,
+ push: (m) => messages.push(m),
+ ready: () => true,
+ provider: () => fakeProvider(steps),
+ persist: (c) => { kept.push({ ...c, events: [...c.events] }); },
+ });
+
+ beforeEach(() => {
+ messages = [];
+ kept = [];
+ driver = vi.fn(async (method: string) => {
+ if (method === 'mark') 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('hands over the turn once it ends, with the memory beside it', async () => {
+ const h = host();
+ h.send('add a pause menu');
+ await settled(h);
+ expect(kept).toHaveLength(1);
+ expect(kept[0].events.some((e) => e.type === 'turn_start')).toBe(true);
+ expect(kept[0].memory).toEqual({ asked: ['add a pause menu'] });
+ });
+
+ it('keeps handing over the same conversation as it grows', async () => {
+ const h = host();
+ h.send('first');
+ await settled(h);
+ h.send('second');
+ await settled(h);
+ expect(kept).toHaveLength(2);
+ expect(kept[0].id).toBe(kept[1].id);
+ expect(kept[1].memory).toEqual({ asked: ['first', 'second'] });
+ });
+
+ // Otherwise New Conversation would overwrite the one the user may want back.
+ it('a new conversation is a new file, not the old one rewritten', async () => {
+ const h = host([ends(), ends()]);
+ h.send('first');
+ await settled(h);
+ h.reset();
+ h.send('second');
+ await settled(h);
+ expect(kept[0].id).not.toBe(kept[1].id);
+ });
+
+ // A turn that failed is still one you may want back.
+ it('keeps a run that ended badly', async () => {
+ const h = createAgentHost({
+ driver: (vi.fn(async (m: string) => { if (m === 'mark') throw new Error('no window'); return null; }) as never),
+ push: (m) => messages.push(m),
+ ready: () => true,
+ provider: () => fakeProvider([ends()]),
+ persist: (c) => { kept.push({ ...c, events: [...c.events] }); },
+ });
+ h.send('hi');
+ await settled(h);
+ expect(kept).toHaveLength(1);
+ });
+
+ it('resuming replays the transcript and carries the memory into the next turn', async () => {
+ const saved: PersistedConversation = {
+ id: 'kept-1',
+ startedAt: 10,
+ model: 'fake-model',
+ endpoint: 'fake',
+ events: [
+ { type: 'turn_start', prompt: 'yesterday', model: 'fake-model', index: 0 },
+ { type: 'turn_end', steps: 0, mark: null, reason: 'end_turn' },
+ ],
+ memory: { asked: ['yesterday'] },
+ };
+ const h = host();
+ messages = [];
+ h.resume(saved);
+
+ // The window is told to drop what it had, then given the run back.
+ const replayed = messages.flatMap((m) => (m.kind === 'event' ? [m.event] : []));
+ expect(replayed[0]).toEqual({ type: 'conversation_reset' });
+ expect(replayed.some((e) => e.type === 'turn_start' && e.prompt === 'yesterday')).toBe(true);
+ expect(h.transcript()).toHaveLength(2);
+
+ // And the model picks up where it left off: the next turn opens at 1.
+ h.send('and now the fonts');
+ await settled(h);
+ const opened = messages.flatMap((m) => (m.kind === 'event' ? [m.event] : []))
+ .filter((e) => e.type === 'turn_start');
+ expect(opened.at(-1)).toMatchObject({ prompt: 'and now the fonts', index: 1 });
+ });
+
+ it('writes a resumed conversation back under the id it came from', async () => {
+ const h = host();
+ h.resume({
+ id: 'kept-1', startedAt: 10, model: 'fake-model', endpoint: 'fake',
+ events: [], memory: { asked: ['yesterday'] },
+ });
+ h.send('more');
+ await settled(h);
+ expect(kept.at(-1)?.id).toBe('kept-1');
+ expect(kept.at(-1)?.startedAt).toBe(10);
+ });
+
+ // Nothing to write to is a state, not a failure.
+ it('runs fine with nowhere to keep anything', async () => {
+ const h = createAgentHost({
+ driver: driver as never,
+ push: (m) => messages.push(m),
+ ready: () => true,
+ provider: () => fakeProvider([ends()]),
+ });
+ h.send('hi');
+ await settled(h);
+ expect(h.status().phase).toBe('idle');
+ });
+});
diff --git a/desktop/tests/agent-kernel.test.ts b/desktop/tests/agent-kernel.test.ts
index 2e8b04cc4..451c92ba4 100644
--- a/desktop/tests/agent-kernel.test.ts
+++ b/desktop/tests/agent-kernel.test.ts
@@ -26,6 +26,7 @@ function fakeSession(steps: StepEvent[][]): AgentSession & {
pushContext: (t) => { context.push(t); },
pushToolResults: (o) => { results.push([...o]); },
rewindTo: (n) => { user.length = n; },
+ serialize: () => ({ user: [...user] }),
step: async function* () {
for (const ev of steps[at] ?? [{ type: 'stop', reason: 'end_turn' }]) yield ev;
at++;
diff --git a/desktop/tests/agent-store.test.ts b/desktop/tests/agent-store.test.ts
new file mode 100644
index 000000000..6114b3a71
--- /dev/null
+++ b/desktop/tests/agent-store.test.ts
@@ -0,0 +1,134 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file agent-store.test.ts
+ * @brief Conversations kept on disk: what survives, what is deliberately
+ * dropped, and what is refused rather than half-read.
+ */
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { mkdtemp, rm, writeFile, mkdir, readFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import {
+ saveConversation, loadConversation, listConversations, deleteConversation,
+} from '../electron/agent/store';
+import type { AgentEvent } from '../electron/agent/types';
+
+let root: string;
+beforeEach(async () => { root = await mkdtemp(path.join(tmpdir(), 'estella-agent-')); });
+afterEach(async () => { await rm(root, { recursive: true, force: true }); });
+
+const turn = (index: number, prompt: string): AgentEvent[] => [
+ { type: 'turn_start', prompt, model: 'fake-model', index },
+ { type: 'text', delta: 'sure' },
+ { type: 'turn_end', steps: 1, mark: { seq: index }, reason: 'end_turn' },
+];
+
+const conversation = (over: Partial<Parameters<typeof saveConversation>[1]> = {}) => ({
+ id: 'abc-123',
+ startedAt: 1000,
+ model: 'fake-model',
+ endpoint: 'anthropic',
+ events: turn(0, 'add a pause menu'),
+ memory: { v: 1, messages: [{ role: 'user', content: 'add a pause menu' }] },
+ ...over,
+});
+
+describe('keeping a conversation', () => {
+ it('round-trips the events and the model memory', async () => {
+ await saveConversation(root, conversation());
+ const back = await loadConversation(root, 'abc-123');
+ expect(back?.events).toEqual(turn(0, 'add a pause menu'));
+ expect(back?.memory).toEqual({ v: 1, messages: [{ role: 'user', content: 'add a pause menu' }] });
+ });
+
+ // The memory is the half that makes a resumed conversation continuable; the
+ // events alone would give you one you can read and not carry on.
+ it('keeps the memory opaque — whatever the provider handed over comes back', async () => {
+ const odd = { v: 1, weird: [1, { nested: true }], blocks: [{ type: 'thinking', signature: 'xyz' }] };
+ await saveConversation(root, conversation({ memory: odd }));
+ expect((await loadConversation(root, 'abc-123'))?.memory).toEqual(odd);
+ });
+
+ it('names itself after the first thing asked', async () => {
+ await saveConversation(root, conversation({
+ events: [...turn(0, ' give every button a\nnine-slice '), ...turn(1, 'now the fonts')],
+ }));
+ expect((await loadConversation(root, 'abc-123'))?.title).toBe('give every button a nine-slice');
+ });
+
+ // A frame is hundreds of kilobytes of base64 and would dominate the file;
+ // what the call ANSWERED is in the summary either way.
+ it('drops screenshots but keeps the row that took them', async () => {
+ const withShot: AgentEvent[] = [
+ { type: 'turn_start', prompt: 'look', model: 'm', index: 0 },
+ { type: 'tool_end', id: 'c1', ok: true, summary: 'screenshot attached', image: 'data:image/png;base64,AAAA' },
+ { type: 'turn_end', steps: 0, mark: null, reason: 'end_turn' },
+ ];
+ await saveConversation(root, conversation({ events: withShot }));
+ const back = await loadConversation(root, 'abc-123');
+ const end = back!.events.find((e) => e.type === 'tool_end');
+ expect(end).toBeDefined();
+ expect(end).not.toHaveProperty('image');
+ expect(end).toMatchObject({ id: 'c1', ok: true, summary: 'screenshot attached' });
+ });
+
+ it('lists newest first, with the turn count', async () => {
+ await saveConversation(root, conversation({ id: 'older', events: turn(0, 'first') }));
+ await new Promise((r) => { setTimeout(r, 5); });
+ await saveConversation(root, conversation({
+ id: 'newer', events: [...turn(0, 'second'), ...turn(1, 'and again')],
+ }));
+ const list = await listConversations(root);
+ expect(list.map((c) => c.id)).toEqual(['newer', 'older']);
+ expect(list[0]).toMatchObject({ title: 'second', turns: 2, model: 'fake-model' });
+ });
+
+ it('has none before anything is saved, and none after deleting', async () => {
+ expect(await listConversations(root)).toEqual([]);
+ await saveConversation(root, conversation());
+ await deleteConversation(root, 'abc-123');
+ expect(await listConversations(root)).toEqual([]);
+ expect(await loadConversation(root, 'abc-123')).toBeNull();
+ });
+
+ it('deleting one that is not there is not a failure', async () => {
+ await expect(deleteConversation(root, 'never-existed')).resolves.toBeUndefined();
+ });
+});
+
+describe('what it refuses', () => {
+ // Ids name a file. Anything that could climb out of the directory is refused
+ // rather than sanitised into some other path.
+ it('will not read or write an id that is not one of ours', async () => {
+ await saveConversation(root, conversation({ id: '../escape' }));
+ expect(await loadConversation(root, '../escape')).toBeNull();
+ expect(await listConversations(root)).toEqual([]);
+ });
+
+ it('refuses a file from a newer editor rather than reading half of it', async () => {
+ await mkdir(path.join(root, '.esengine', 'agent'), { recursive: true });
+ await writeFile(
+ path.join(root, '.esengine', 'agent', 'future.json'),
+ JSON.stringify({ v: 99, id: 'future', events: [], memory: {} }),
+ 'utf8',
+ );
+ expect(await loadConversation(root, 'future')).toBeNull();
+ expect(await listConversations(root)).toEqual([]);
+ });
+
+ it('survives a corrupt file — it is one conversation lost, not the list', async () => {
+ await saveConversation(root, conversation({ id: 'good' }));
+ await writeFile(path.join(root, '.esengine', 'agent', 'bad.json'), '{ not json', 'utf8');
+ const list = await listConversations(root);
+ expect(list.map((c) => c.id)).toEqual(['good']);
+ });
+
+ it('leaves the file it could not parse alone', async () => {
+ await mkdir(path.join(root, '.esengine', 'agent'), { recursive: true });
+ const p = path.join(root, '.esengine', 'agent', 'bad.json');
+ await writeFile(p, '{ not json', 'utf8');
+ await listConversations(root);
+ expect(await readFile(p, 'utf8')).toBe('{ not json');
+ });
+});