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.

fix(agent): a dropped connection costs the round, not the turn

yhh0e82862a3654
diff --git a/desktop/electron/agent/anthropic.ts b/desktop/electron/agent/anthropic.ts
index 97c646906..9748f56f2 100644
--- a/desktop/electron/agent/anthropic.ts
+++ b/desktop/electron/agent/anthropic.ts
@@ -169,6 +169,21 @@ function headerOf(error: unknown, name: string): string | undefined {
return (headers as Record<string, string>)[name];
}
+/**
+ * Whether asking again could plausibly work: the failure was the CONNECTION or
+ * the far side, not the request.
+ *
+ * A stream that dies halfway is the common one, and it is not rare over a long
+ * turn — a dogfood run lost eighty-seven rounds of work to a socket the gateway
+ * closed. It arrives with no HTTP status at all, because the request had already
+ * succeeded and the body stopped arriving.
+ */
+export function isTransientApiError(error: unknown): boolean {
+ const status = (error as { status?: number })?.status;
+ if (status === undefined || status === null) return true;
+ return status === 408 || status === 429 || status >= 500;
+}
+
export function describeApiError(error: unknown): string {
const status = (error as { status?: number })?.status;
const raw = (error as Error)?.message ?? String(error);
@@ -546,7 +561,13 @@ class AnthropicSession implements AgentSession {
// Rethrown, not swallowed — the kernel still has to end the turn. Only the
// wording changes, and it changes HERE because this is the layer that
// knows what an SDK error means.
- throw new Error(describeApiError(e));
+ //
+ // `retryable` is safe to act on for one reason: the history is appended
+ // AFTER `finalMessage()` below, so a stream that died has left this
+ // session exactly as it found it. Re-asking sends the same messages.
+ const err = new Error(describeApiError(e)) as Error & { retryable?: boolean };
+ err.retryable = isTransientApiError(e);
+ throw err;
}
}
diff --git a/desktop/electron/agent/kernel.ts b/desktop/electron/agent/kernel.ts
index 763dc9f78..75121a3e4 100644
--- a/desktop/electron/agent/kernel.ts
+++ b/desktop/electron/agent/kernel.ts
@@ -233,10 +233,30 @@ export async function runTurn(
const calls: ToolCall[] = [];
let refused = false;
- for await (const ev of session.step(signal)) {
- if (ev.type === 'tool_call') calls.push(ev.call);
- if (ev.type === 'stop' && ev.reason === 'refusal') refused = true;
- emit(ev);
+ // A dropped connection costs the ROUND, not the turn. The provider layer
+ // appends to the conversation only once a stream completes, so a stream
+ // that died left the session as it found it and asking again sends the
+ // same messages. Without this, an hour of work ends on a socket the
+ // gateway closed — twice in three dogfood runs, both times mid-build,
+ // with the reason buried in a transcript nobody reads until after.
+ for (let attempt = 0; ; attempt++) {
+ calls.length = 0;
+ try {
+ for await (const ev of session.step(signal)) {
+ if (ev.type === 'tool_call') calls.push(ev.call);
+ if (ev.type === 'stop' && ev.reason === 'refusal') refused = true;
+ emit(ev);
+ }
+ break;
+ } catch (e) {
+ const retryable = (e as { retryable?: boolean })?.retryable === true;
+ if (signal.aborted || !retryable || attempt >= STEP_RETRIES) throw e;
+ emit({
+ type: 'error',
+ message: `${(e as Error).message} — retrying (${attempt + 1}/${STEP_RETRIES}).`,
+ });
+ await new Promise((r) => { setTimeout(r, 1000 * (attempt + 1)); });
+ }
}
if (refused) { reason = 'refusal'; break; }
// No calls means it is about to answer. If it built something and never
@@ -339,6 +359,9 @@ export async function runTurn(
* money to deliver half a thing.
*/
const MAX_ROUNDS = 128;
+/** Extra attempts for a round whose CONNECTION failed. Small: a provider that is
+ * down stays down, and the point is only to survive a dropped socket. */
+const STEP_RETRIES = 2;
/**
* How many rounds from the cap the model is told it is running out.
diff --git a/desktop/tests/agent-kernel.test.ts b/desktop/tests/agent-kernel.test.ts
index c5daf2070..69452e5bc 100644
--- a/desktop/tests/agent-kernel.test.ts
+++ b/desktop/tests/agent-kernel.test.ts
@@ -658,3 +658,74 @@ describe('what verification means for a model that cannot see', () => {
}
});
});
+
+/**
+ * A round whose CONNECTION failed is not a turn that failed. The provider layer
+ * appends to the conversation only once a stream completes, so a stream that
+ * died left the session as it found it — two dogfood runs in three ended
+ * mid-build on a socket the gateway closed, with eighty-odd rounds of work on
+ * the floor.
+ */
+describe('a dropped connection', () => {
+ const mkDriver = () => {
+ const d = vi.fn(async (method: string) => {
+ if (method === 'mark') return { seq: 1 };
+ if (method === 'stepsSince') return 0;
+ if (method === 'getDiagnostics') return [];
+ return null;
+ }) as ReturnType<typeof vi.fn> & { js: unknown; op: unknown };
+ (d as { js: unknown }).js = vi.fn(async () => null);
+ (d as { op: unknown }).op = vi.fn(async () => null);
+ return d;
+ };
+
+ /** A session that throws on its first `n` steps, then behaves. */
+ const flaky = (n: number, retryable: boolean, steps: StepEvent[][]) => {
+ const s = fakeSession(steps);
+ const real = s.step;
+ let thrown = 0;
+ s.step = async function* (...args: Parameters<typeof real>) {
+ if (thrown < n) {
+ thrown++;
+ const e = new Error('Could not reach the endpoint: terminated') as Error & { retryable?: boolean };
+ e.retryable = retryable;
+ throw e;
+ }
+ yield* real(...args);
+ } as typeof real;
+ return s;
+ };
+
+ it('is retried, and the turn goes on to finish', async () => {
+ const events: AgentEvent[] = [];
+ const s = flaky(1, true, [asks(call('add_entity')), ends(), ends()]);
+ const out = await runTurn({
+ driver: mkDriver() as never, session: s, model: 'm', acceptsImages: false,
+ confirm: (async () => ({ answer: 'once' })) as never, emit: (e) => { events.push(e); },
+ }, 'build', null, new AbortController().signal);
+ expect(events.at(-1)).toMatchObject({ type: 'turn_end', reason: 'end_turn' });
+ expect(events.some((e) => e.type === 'error' && e.message.includes('retrying (1/2)'))).toBe(true);
+ expect(out.mark).toBeTruthy();
+ });
+
+ it('gives up once the retries are spent, and says the turn ended in error', async () => {
+ const events: AgentEvent[] = [];
+ const s = flaky(9, true, [ends()]);
+ await runTurn({
+ driver: mkDriver() as never, session: s, model: 'm', acceptsImages: false,
+ confirm: (async () => ({ answer: 'once' })) as never, emit: (e) => { events.push(e); },
+ }, 'build', null, new AbortController().signal);
+ expect(events.at(-1)).toMatchObject({ type: 'turn_end', reason: 'error' });
+ });
+
+ it('does not retry a refusal or a bad request', async () => {
+ const events: AgentEvent[] = [];
+ const s = flaky(1, false, [ends()]);
+ await runTurn({
+ driver: mkDriver() as never, session: s, model: 'm', acceptsImages: false,
+ confirm: (async () => ({ answer: 'once' })) as never, emit: (e) => { events.push(e); },
+ }, 'build', null, new AbortController().signal);
+ expect(events.some((e) => e.type === 'error' && e.message.includes('retrying'))).toBe(false);
+ expect(events.at(-1)).toMatchObject({ type: 'turn_end', reason: 'error' });
+ });
+});