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): ask a turn again without throwing away the conversation

esengine321aeace25a4
diff --git a/desktop/electron/agent/anthropic.ts b/desktop/electron/agent/anthropic.ts
index d6d25cfd1..dba9db0da 100644
--- a/desktop/electron/agent/anthropic.ts
+++ b/desktop/electron/agent/anthropic.ts
@@ -146,6 +146,9 @@ class AnthropicSession implements AgentSession {
private readonly 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[] = [];
constructor(
private readonly client: Anthropic,
@@ -155,9 +158,19 @@ class AnthropicSession implements AgentSession {
) {}
pushUser(text: string): void {
+ this.turnStarts.push(this.messages.length);
this.messages.push({ role: 'user', content: text });
}
+ rewindTo(n: number): void {
+ const at = this.turnStarts[n];
+ if (at === undefined) return;
+ this.messages.length = at;
+ this.turnStarts.length = n;
+ // Context buffered for a turn that is no longer going to happen.
+ this.pending.length = 0;
+ }
+
pushContext(text: string): void {
this.pending.push(text);
}
diff --git a/desktop/electron/agent/host.ts b/desktop/electron/agent/host.ts
index f85ffee98..d038423a0 100644
--- a/desktop/electron/agent/host.ts
+++ b/desktop/electron/agent/host.ts
@@ -69,6 +69,12 @@ export interface AgentHost {
confirm(callId: string, allow: boolean): void;
/** Drop the conversation and start over; the next turn re-reads the key. */
reset(): 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
+ * whole conversation leading up to it.
+ */
+ retry(n: number, text: string): AgentStatus;
/**
* Re-push the status because something OUTSIDE changed it — the window picked
* a different provider, so `ready` now answers differently. Without this the
@@ -110,7 +116,7 @@ export function createAgentHost(deps: AgentHostDeps): AgentHost {
pushStatus();
});
- const send = (text: string): AgentStatus => {
+ const send = (text: string, rewindTo?: number): AgentStatus => {
if (phase !== 'idle') {
error = 'the agent is still working on the previous message';
pushStatus();
@@ -128,6 +134,8 @@ export function createAgentHost(deps: AgentHostDeps): AgentHost {
}
}
+ if (rewindTo !== undefined) session.rewindTo(rewindTo);
+
error = null;
phase = 'running';
const controller = new AbortController();
@@ -171,7 +179,9 @@ export function createAgentHost(deps: AgentHostDeps): AgentHost {
return {
status,
- send,
+ send: (text: string) => send(text),
+ // A retry with no session yet is just a first message — nothing to rewind to.
+ retry: (n, text) => send(text, session ? n : undefined),
stop: () => {
running?.abort();
// The kernel may be parked on a confirmation, which an aborted signal does
diff --git a/desktop/electron/agent/types.ts b/desktop/electron/agent/types.ts
index 2fb1f85e8..5a41ff5d8 100644
--- a/desktop/electron/agent/types.ts
+++ b/desktop/electron/agent/types.ts
@@ -75,6 +75,16 @@ export interface AgentSession {
pushContext(text: string): void;
/** Results for the calls the last step asked for, all of them, in one go. */
pushToolResults(outcomes: readonly ToolOutcome[]): void;
+ /**
+ * Drop everything from the `n`-th person's turn onward, so it can be asked
+ * again from there.
+ *
+ * Counted in PERSON's turns, not messages: a tool result is also a `user`
+ * message, and a caller that knew that would be reasoning about the
+ * provider's wire format — which is the one thing this contract exists to
+ * keep out of the kernel.
+ */
+ rewindTo(n: number): void;
/** Run one model call. */
step(signal: AbortSignal): AsyncIterable<StepEvent>;
}
diff --git a/desktop/electron/main.ts b/desktop/electron/main.ts
index 159be0228..1252f40d9 100644
--- a/desktop/electron/main.ts
+++ b/desktop/electron/main.ts
@@ -685,6 +685,7 @@ 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());
+ipcMain.handle('agent:retry', (_e, n: number, text: string) => agentHost.retry(n, text));
ipcMain.handle('agent:setEndpoint', (_e, patch: { baseUrl?: string; model?: string; keyId?: string }) => {
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 3a94d0954..4bb45e5da 100644
--- a/desktop/electron/preload.ts
+++ b/desktop/electron/preload.ts
@@ -119,6 +119,8 @@ const api = {
ipcRenderer.invoke('agent:confirm', callId, allow),
/** Drop the conversation and start a new one. */
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),
/** 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 }): Promise<void> =>
diff --git a/desktop/src/components/AgentDrawer.tsx b/desktop/src/components/AgentDrawer.tsx
index b02f2d667..5071f1137 100644
--- a/desktop/src/components/AgentDrawer.tsx
+++ b/desktop/src/components/AgentDrawer.tsx
@@ -26,12 +26,12 @@
import { useEffect, useLayoutEffect, useRef, useState, useSyncExternalStore } from 'react';
import {
X, Plus, PanelRight, ArrowUp, Square, ChevronRight, ChevronDown, Check, TriangleAlert,
- Loader, Copy, Pencil, Eye, KeyRound, Boxes, Stethoscope, Image as ImageIcon,
+ Loader, Copy, Pencil, Eye, KeyRound, Boxes, Stethoscope, Image as ImageIcon, RotateCcw,
} from 'lucide-react';
import { useEditorStore } from '@/store/editorStore';
import {
useAgent, sendAgentMessage, stopAgentTurn, confirmAgentCall, resetAgentSession,
- peekEntities, entitiesInInput, effectiveSelection, selectAgentModel,
+ peekEntities, entitiesInInput, effectiveSelection, selectAgentModel, retryAgentTurn,
type AgentTurn, type AgentEntry, type AgentToolEntry,
} from '@/store/AgentStore';
import {
@@ -254,6 +254,20 @@ function Turn({ turn, isLast, running }: { turn: AgentTurn; isLast: boolean; run
<span className="ag-hrow">
<ChevronRight size={12} strokeWidth={2} className="ag-fold" />
<span className="ag-req">{turn.prompt}</span>
+ {/* A bad answer three turns in should cost you that answer, not the
+ whole conversation that led to it. */}
+ {!running && (
+ <span
+ role="button"
+ tabIndex={0}
+ className="ag-rerun"
+ title={t('agent.rerun')}
+ onClick={(e) => { e.stopPropagation(); void retryAgentTurn(turn.id); }}
+ onKeyDown={(e) => { if (e.key === 'Enter') { e.stopPropagation(); void retryAgentTurn(turn.id); } }}
+ >
+ <RotateCcw size={12} strokeWidth={1.9} />
+ </span>
+ )}
</span>
<span className="ag-stat">
<Elapsed turn={turn} />
diff --git a/desktop/src/i18n/messages/agent.ts b/desktop/src/i18n/messages/agent.ts
index 8c5b8f57f..698182580 100644
--- a/desktop/src/i18n/messages/agent.ts
+++ b/desktop/src/i18n/messages/agent.ts
@@ -62,6 +62,7 @@ export const agentMessages = defineMessages({
'agent.turn.refusal': { en: 'The model declined this one.', zh: '模型拒绝了这个请求。' },
'agent.turn.queuedMessage': { en: 'Queued: {text}', zh: '已排队:{text}' },
'agent.copy': { en: 'Copy', zh: '复制' },
+ 'agent.rerun': { en: 'Ask this again, discarding what followed', zh: '从这里重跑(丢弃之后的内容)' },
// — The decision it needs from you —
'agent.confirm.title': { en: 'Run {tool}?', zh: '要执行 {tool} 吗?' },
diff --git a/desktop/src/store/AgentStore.ts b/desktop/src/store/AgentStore.ts
index 34b472df4..11e2d089b 100644
--- a/desktop/src/store/AgentStore.ts
+++ b/desktop/src/store/AgentStore.ts
@@ -378,6 +378,19 @@ export async function sendAgentMessage(text: string): Promise<void> {
if (status) adoptStatus(status);
}
+/**
+ * Ask a turn again, discarding it and everything after it — on both sides. The
+ * store truncates first so the transcript never shows runs the session has
+ * already forgotten.
+ */
+export async function retryAgentTurn(turnId: number): Promise<void> {
+ const turn = useAgent.getState().turns[turnId];
+ if (!turn) return;
+ useAgent.setState((s) => ({ turns: s.turns.slice(0, turnId), checkpointDone: null }));
+ const status = await window.estella?.agent?.retry(turnId, turn.prompt);
+ if (status) adoptStatus(status);
+}
+
export function stopAgentTurn(): void {
void window.estella?.agent?.stop();
}
diff --git a/desktop/src/theme/agent.css b/desktop/src/theme/agent.css
index ce327b6b3..f3d4e7cf5 100644
--- a/desktop/src/theme/agent.css
+++ b/desktop/src/theme/agent.css
@@ -590,3 +590,15 @@
font-size: var(--fs-sm);
font-weight: 500;
}
+/* Re-ask this turn. Quiet until the header is hovered — it discards work. */
+.ag-rerun {
+ flex: none;
+ width: 22px; height: 22px;
+ display: grid; place-items: center;
+ border-radius: var(--r-sm);
+ color: var(--text-faint);
+ opacity: 0;
+ transition: opacity var(--t-fast), color var(--t-fast), background var(--t-fast);
+}
+.ag-th:hover .ag-rerun, .ag-rerun:focus-visible { opacity: 1; }
+.ag-rerun:hover { color: var(--text-hi); background: var(--hover); }
diff --git a/desktop/tests/agent-host.test.ts b/desktop/tests/agent-host.test.ts
index c4760be78..20f046f61 100644
--- a/desktop/tests/agent-host.test.ts
+++ b/desktop/tests/agent-host.test.ts
@@ -18,18 +18,21 @@ const asks = (...calls: ToolCall[]): StepEvent[] =>
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 {
+function fakeProvider(steps: StepEvent[][]): AgentProvider & { session: AgentSession & { asked: string[]; rewinds: number[] } } {
let at = 0;
- const session: AgentSession = {
- pushUser: () => {},
+ const session: AgentSession & { asked: string[]; rewinds: number[] } = {
+ asked: [],
+ rewinds: [],
+ pushUser: (t) => { session.asked.push(t); },
pushContext: () => {},
pushToolResults: () => {},
+ rewindTo: (n) => { session.rewinds.push(n); },
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 };
+ return { id: 'fake', model: 'fake-model', session, createSession: () => session };
}
describe('the agent host', () => {
@@ -44,6 +47,7 @@ describe('the agent host', () => {
const settled = (h: AgentHost): Promise<void> =>
vi.waitFor(() => expect(h.status().phase).toBe('idle'));
+ let provider: ReturnType<typeof fakeProvider> | null = null;
const host = (steps: StepEvent[][] = [ends()]): AgentHost => createAgentHost({
driver: driver as never,
push: (m) => messages.push(m),
@@ -51,7 +55,8 @@ describe('the agent host', () => {
provider: () => {
built++;
if (!keyed) throw new Error('No API key is configured. Add one in Settings › AI Agents.');
- return fakeProvider(steps);
+ provider = fakeProvider(steps);
+ return provider;
},
});
@@ -64,6 +69,7 @@ describe('the agent host', () => {
built = 0;
keyed = true;
markFails = null;
+ provider = null;
driver = vi.fn(async (method: string) => {
if (method === 'mark') {
if (markFails) throw new Error(markFails);
@@ -188,4 +194,27 @@ describe('the agent host', () => {
await settled(h);
expect(statuses().map((s) => s.phase)).toEqual(['running', 'idle']);
});
+
+ // A bad answer three turns in should cost you that answer, not the whole
+ // conversation that led to it.
+ it('rewinds the session to the turn being asked again', async () => {
+ const h = host([ends(), ends(), ends()]);
+ h.send('first');
+ await settled(h);
+ h.send('second');
+ await settled(h);
+
+ h.retry(1, 'second, but better');
+ await settled(h);
+ expect(provider!.session.rewinds).toEqual([1]);
+ expect(provider!.session.asked.at(-1)).toBe('second, but better');
+ });
+
+ it('has nothing to rewind before the first message', async () => {
+ const h = host();
+ h.retry(0, 'hello');
+ await settled(h);
+ expect(provider!.session.rewinds).toEqual([]);
+ expect(provider!.session.asked).toEqual(['hello']);
+ });
});