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): say which failure this is, since each has a different answer

esengine8c6d7635c1fd
diff --git a/desktop/electron/agent/anthropic.ts b/desktop/electron/agent/anthropic.ts
index 40962cfc9..f65dc9221 100644
--- a/desktop/electron/agent/anthropic.ts
+++ b/desktop/electron/agent/anthropic.ts
@@ -142,6 +142,52 @@ export function toolResultContent(
];
}
+/**
+ * What went wrong, said to the person who has to decide what to do about it.
+ *
+ * The SDK's own message is written for whoever is reading a stack trace — it
+ * names a status code and a URL. In the transcript the only useful content is
+ * which of four situations this is, because each has a different answer: wait,
+ * fix the key, check the address, or nothing (it already retried).
+ *
+ * Exported so the phrasing is pinned by a test rather than by whichever error
+ * happens to occur first in production.
+ */
+/** The SDK hands back a `Headers` on some paths and a plain object on others;
+ * reading only one shape is how the useful half of a 429 goes missing. */
+function headerOf(error: unknown, name: string): string | undefined {
+ const headers = (error as { headers?: unknown })?.headers;
+ if (!headers) return undefined;
+ const get = (headers as Headers).get;
+ if (typeof get === 'function') return (headers as Headers).get(name) ?? undefined;
+ return (headers as Record<string, string>)[name];
+}
+
+export function describeApiError(error: unknown): string {
+ const status = (error as { status?: number })?.status;
+ const raw = (error as Error)?.message ?? String(error);
+ const retryAfter = Number(headerOf(error, 'retry-after'));
+
+ if (status === 429) {
+ // The SDK has already retried this with backoff by the time it reaches us,
+ // so "try again" is not advice — how long to wait is.
+ return Number.isFinite(retryAfter) && retryAfter > 0
+ ? `Rate limited, and the automatic retries did not clear it. The endpoint asks for ${retryAfter}s.`
+ : 'Rate limited, and the automatic retries did not clear it. Wait a moment and send again.';
+ }
+ if (status === 401 || status === 403) {
+ return 'The endpoint rejected the API key. Check it in Settings › AI Agents.';
+ }
+ if (status === 404) {
+ return 'The endpoint has no such model, or the address is wrong. Check both in Settings › AI Agents.';
+ }
+ if (status === 400) return `The endpoint refused the request: ${raw}`;
+ if (status && status >= 500) return 'The endpoint is having trouble. Nothing is wrong on this side — try again shortly.';
+ // Not an HTTP failure at all: DNS, offline, a gateway that is not running.
+ if (!status) return `Could not reach the endpoint: ${raw}`;
+ return raw;
+}
+
class AnthropicSession implements AgentSession {
private readonly messages: Message[] = [];
/** Context waiting for a legal spot — see {@link flushContext}. */
@@ -248,6 +294,20 @@ class AnthropicSession implements AgentSession {
// only the block's start carries the id the rest of the system speaks in.
const toolAt = new Map<number, string>();
+ try {
+ yield* this.consume(stream, toolAt);
+ } catch (e) {
+ // 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));
+ }
+ }
+
+ private async *consume(
+ stream: ReturnType<Anthropic['messages']['stream']> | ReturnType<Anthropic['beta']['messages']['stream']>,
+ toolAt: Map<number, string>,
+ ): AsyncIterable<StepEvent> {
for await (const event of stream) {
if (event.type === 'content_block_start') {
const block = event.content_block;
diff --git a/desktop/tests/agent-dialect.test.ts b/desktop/tests/agent-dialect.test.ts
index d0067d9d3..fdbb7fc40 100644
--- a/desktop/tests/agent-dialect.test.ts
+++ b/desktop/tests/agent-dialect.test.ts
@@ -13,7 +13,9 @@
* rejected or silently dropped, taking the editor's context with it.
*/
import { describe, it, expect } from 'vitest';
-import { buildStepRequest, createAnthropicProvider, toolResultContent } from '../electron/agent/anthropic';
+import {
+ buildStepRequest, createAnthropicProvider, toolResultContent, describeApiError,
+} from '../electron/agent/anthropic';
import { DEFAULT_MODEL } from '../src/settings/agentIds';
import type { CatalogTool } from '../electron/agent/types';
@@ -161,3 +163,52 @@ describe('a tool result carrying a rendered frame', () => {
expect(toolResultContent(plain, 'compatible')).toBe('7 created');
});
});
+
+// The SDK's message is written for someone reading a stack trace. In the
+// transcript the only useful content is WHICH situation this is, because each
+// one has a different answer.
+describe('what a failed request says', () => {
+ const err = (status: number | undefined, message = 'boom', headers?: Record<string, string>) =>
+ Object.assign(new Error(message), { status, headers });
+
+ it('names the wait, not "try again", when rate limited', () => {
+ // By the time this surfaces the SDK has already retried with backoff, so
+ // "try again" is not advice — how long is.
+ expect(describeApiError(err(429, 'x', { 'retry-after': '30' }))).toContain('30s');
+ expect(describeApiError(err(429))).toContain('Rate limited');
+ });
+
+ // The SDK returns a Headers on some paths and a plain object on others.
+ // Reading one shape is how the useful half of a 429 goes missing.
+ it('reads retry-after from either header shape', () => {
+ const withHeaders = Object.assign(new Error('x'), {
+ status: 429,
+ headers: new Headers({ 'retry-after': '12' }),
+ });
+ expect(describeApiError(withHeaders)).toContain('12s');
+ });
+
+ it('sends a rejected key to the place it is fixed', () => {
+ expect(describeApiError(err(401))).toContain('Settings');
+ expect(describeApiError(err(403))).toContain('Settings');
+ });
+
+ // The two are indistinguishable from a 404 and have the same fix, so say both
+ // rather than guessing one.
+ it('treats an unknown model and a wrong address as the same question', () => {
+ const text = describeApiError(err(404));
+ expect(text).toContain('model');
+ expect(text).toContain('address');
+ });
+
+ it('says an outage is not your fault', () => {
+ expect(describeApiError(err(503))).toContain('Nothing is wrong on this side');
+ });
+
+ // No status at all is not an HTTP failure: DNS, offline, a gateway that is
+ // not running. "Rate limited" would be a lie and "500" would be a guess.
+ it('separates never-reached from refused', () => {
+ expect(describeApiError(err(undefined, 'ECONNREFUSED'))).toContain('Could not reach');
+ expect(describeApiError(err(400, 'max_tokens too large'))).toContain('max_tokens too large');
+ });
+});