๐คฏ LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
๐ fix(hetero-agent): classify CC terminal errors + add a heterogeneous error taxonomy (#17887)
Arvin Xub0eb70c155e9
diff --git a/packages/heterogeneous-agents/src/adapters/claudeCode.test.ts b/packages/heterogeneous-agents/src/adapters/claudeCode.test.tsindex 6019d737c9e..88442cea31b 100644--- a/packages/heterogeneous-agents/src/adapters/claudeCode.test.ts+++ b/packages/heterogeneous-agents/src/adapters/claudeCode.test.ts@@ -87,17 +87,38 @@ describe('ClaudeCodeAdapter', () => {const errorEvent = events.at(-1)!;expect(errorEvent.type).toBe('error');+ // The streamed line is the only reason available, so it must become the+ // message โ and a dropped connection is transient, so it earns the+ // retryable `overloaded` code rather than the opaque generic card.expect(errorEvent.data).toMatchObject({agentType: 'claude-code',+ code: 'overloaded',+ error: apiError,+ message: apiError,+ });+ });++ it('keeps the diagnostic details pane for failures with no recognizable reason', () => {+ const adapter = new ClaudeCodeAdapter();++ adapter.adapt({ session_id: 'sess_x', subtype: 'init', type: 'system' });+ const events = adapter.adapt({+ duration_ms: 157_000,+ is_error: true,+ num_turns: 2,+ session_id: 'sess_x',+ subtype: 'error_during_execution',+ type: 'result',+ });++ expect(events.at(-1)!.data).toMatchObject({code: 'error_during_execution',details: {durationMs: 157_000,numTurns: 2,- sessionId: 'sess_net',+ sessionId: 'sess_x',subtype: 'error_during_execution',},- error: apiError,- message: apiError,});});@@ -436,8 +457,9 @@ describe('ClaudeCodeAdapter', () => {const adapter = new ClaudeCodeAdapter();// CC stamps a rate_limit_info onto an *allowed* request โ it carries the// rolling-window metadata (resetsAt / rateLimitType) even though nothing- // was rejected. A later ECONNRESET must surface as a generic error, NOT- // inherit this window and render a bogus "usage limit reached" guide.+ // was rejected. A later ECONNRESET must be classified on its own merits+ // (a transient transport failure) and must NOT inherit this window and+ // render a bogus "usage limit reached, resets at X" guide.const rawError = 'API Error: Unable to connect to API (ECONNRESET)';adapter.adapt({ subtype: 'init', type: 'system' });@@ -459,11 +481,239 @@ describe('ClaudeCodeAdapter', () => {});expect(events.map((e) => e.type)).toEqual(['stream_end', 'visible_output_end', 'error']);- expect(events[2].data).toMatchObject({ error: rawError, message: rawError });+ expect(events[2].data).toMatchObject({+ code: 'overloaded',+ error: rawError,+ message: rawError,+ });expect(events[2].data).not.toHaveProperty('code', 'rate_limit');expect(events[2].data).not.toHaveProperty('rateLimitInfo');});+ // Every case below is taken from a real recorded trace under+ // `<appStorage>/heteroAgent/tracing/claude-code`, where 53% of all+ // `is_error` results were landing in the generic fallback card.+ it.each([+ ['API Error: Unable to connect to API (ECONNRESET)', null],+ ['API Error: Unable to connect to API (ConnectionRefused)', null],+ ['API Error: Connection closed mid-response. The response above may be incomplete.', null],+ ['API Error: The socket connection was closed unexpectedly.', null],+ ['API Error: Stream idle timeout - partial response received', null],+ ['API Error: Response stalled mid-stream. The response above may be incomplete.', null],+ ['Request timed out', null],+ ['API Error: 500 Internal server error. This is a server-side issue.', 500],+ ])('classifies transport/5xx failure %j as overloaded (retryable)', (rawError, status) => {+ const adapter = new ClaudeCodeAdapter();++ adapter.adapt({ subtype: 'init', type: 'system' });+ const events = adapter.adapt({+ api_error_status: status,+ is_error: true,+ result: rawError,+ type: 'result',+ });++ expect(events.at(-1)!.data).toMatchObject({ code: 'overloaded', message: rawError });+ });++ it.each([+ "You've hit your session limit ยท resets 6:30pm (Asia/Shanghai)",+ "You've hit your weekly limit ยท resets Jul 3 at 1pm (Asia/Shanghai)",+ "You've reached your Fable 5 limit. Run /usage-credits to continue or switch models.",+ 'API Error: Request rejected (429) ยท [1234][ๅทฒ่พพๅฐ 5 ๅฐๆถไฝฟ็จไธ้๏ผ2026-06-19 22:00:00 ๅๅฏ็ปง็ปญไฝฟ็จใ]',+ ])('classifies user-quota wording %j as rate_limit without a structured event', (rawError) => {+ const adapter = new ClaudeCodeAdapter();++ // No rate_limit_event at all: the 429 alone previously routed these real+ // quota exhaustions to the "server is busy, retry" guide.+ adapter.adapt({ subtype: 'init', type: 'system' });+ const events = adapter.adapt({+ api_error_status: 429,+ is_error: true,+ result: rawError,+ type: 'result',+ });++ expect(events.at(-1)!.data).toMatchObject({ code: 'rate_limit', message: rawError });+ });++ it('keeps an auth failure that mentions a transport symptom as auth_required', () => {+ const adapter = new ClaudeCodeAdapter();+ // Real trace: the transport wording would otherwise win and render a+ // useless retry card for a credential problem.+ const rawError =+ 'Failed to authenticate. API Error: 401 The socket connection was closed unexpectedly.';++ adapter.adapt({ subtype: 'init', type: 'system' });+ const events = adapter.adapt({+ api_error_status: 401,+ is_error: true,+ result: rawError,+ type: 'result',+ });++ expect(events.at(-1)!.data).toMatchObject({ code: 'auth_required' });+ });++ it.each(['aborted_streaming', 'aborted_tools'])(+ 'terminates a stopped run (%s) as interrupted, NOT as an error',+ (terminalReason) => {+ const adapter = new ClaudeCodeAdapter();++ adapter.adapt({ subtype: 'init', type: 'system' });+ // Real shape of a user-initiated stop: is_error, no result text, only+ // CC's internal diagnostic in `errors`, and the process exits 0.+ const events = adapter.adapt({+ errors: ['[ede_diagnostic] result_type=user last_content_type=n/a stop_reason=tool_use'],+ is_error: true,+ num_turns: 4,+ subtype: 'error_during_execution',+ terminal_reason: terminalReason,+ type: 'result',+ });++ const terminal = events.at(-1)!;+ // A stop is an outcome, not a fault: no error terminal means no red+ // card, no `failed` topic status.+ expect(events.some((e) => e.type === 'error')).toBe(false);+ expect(terminal.type).toBe('agent_runtime_end');+ expect(terminal.data).toMatchObject({+ kind: 'aborted',+ reason: 'interrupted',+ terminalReason,+ });+ expect(JSON.stringify(terminal.data)).not.toContain('ede_diagnostic');+ },+ );++ it('does not fabricate a terminal for a stop under the on-transport-close strategy', () => {+ // The SDK transport supplies its own terminal when the transport closes;+ // emitting one here too would double-terminate the run.+ const adapter = new ClaudeCodeSdkAdapter();++ adapter.adapt({ subtype: 'init', type: 'system' });+ const events = adapter.adapt({+ errors: ['[ede_diagnostic] result_type=user last_content_type=n/a stop_reason=tool_use'],+ is_error: true,+ subtype: 'error_during_execution',+ terminal_reason: 'aborted_streaming',+ type: 'result',+ });++ expect(events.some((e) => e.type === 'error' || e.type === 'agent_runtime_end')).toBe(false);+ });++ it('keeps a real reason reported during an aborted wind-down', () => {+ const adapter = new ClaudeCodeAdapter();+ const rawError = "You've hit your session limit ยท resets 6:30pm (Asia/Shanghai)";++ adapter.adapt({ subtype: 'init', type: 'system' });+ const events = adapter.adapt({+ api_error_status: 429,+ is_error: true,+ result: rawError,+ terminal_reason: 'aborted_tools',+ type: 'result',+ });++ expect(events.at(-1)!.data).toMatchObject({ code: 'rate_limit', message: rawError });+ });++ it('still surfaces a non-diagnostic errors[] entry (stale --resume id)', () => {+ const adapter = new ClaudeCodeAdapter();+ const resumeError = 'No conversation found with session ID: 0a8e28f6-5ba2-4828-900b-069d77';++ adapter.adapt({ subtype: 'init', type: 'system' });+ const events = adapter.adapt({+ errors: [resumeError],+ is_error: true,+ subtype: 'error_during_execution',+ type: 'result',+ });++ expect(events.at(-1)!.data).toMatchObject({+ code: 'resume_thread_not_found',+ message: resumeError,+ });+ });++ // The long tail has no dedicated guide card, so the value is the taxonomy+ // kind: it keeps these out of the `agent_failed` catch-all.+ it.each([+ ['Claude Fable 5 is currently unavailable. Learn more: โฆ', 'model_unavailable'],+ ["There's an issue with the selected model (claude-fable-5).", 'model_unavailable'],+ ['Failed to decode image: The image format Gif is not supported', 'unsupported_attachment'],+ [+ 'API Error: 400 messages.6.content.2.server_tool_use.id: String should match pattern',+ 'invalid_request',+ ],+ ])('classifies tail failure %j as %s', (rawError, kind) => {+ const adapter = new ClaudeCodeAdapter();++ adapter.adapt({ subtype: 'init', type: 'system' });+ const events = adapter.adapt({ is_error: true, result: rawError, type: 'result' });++ expect(events.at(-1)!.data).toMatchObject({+ code: kind,+ details: { kind },+ message: rawError,+ });+ });++ it.each([+ ['API Error: Unable to connect to API (ECONNRESET)', null, 'network_drop'],+ [+ 'API Error: Server is temporarily limiting requests (not your usage limit) ยท Rate limited',+ 429,+ 'server_throttle',+ ],+ ['API Error: 529 Overloaded.', 529, 'server_overloaded'],+ ])('tags %j with taxonomy kind %s under one overloaded guide code', (msg, status, kind) => {+ const adapter = new ClaudeCodeAdapter();++ adapter.adapt({ subtype: 'init', type: 'system' });+ const events = adapter.adapt({+ api_error_status: status,+ is_error: true,+ result: msg,+ type: 'result',+ });++ // One guide code (so auto-retry behavior is unchanged), three kinds.+ expect(events.at(-1)!.data).toMatchObject({ code: 'overloaded', details: { kind } });+ });++ it('separates a credit limit from a plan window under the rate_limit guide', () => {+ const adapter = new ClaudeCodeAdapter();+ const rawError = "You've reached your Fable 5 limit. Run /usage-credits to continue.";++ adapter.adapt({ subtype: 'init', type: 'system' });+ const events = adapter.adapt({+ api_error_status: 429,+ is_error: true,+ result: rawError,+ type: 'result',+ });++ expect(events.at(-1)!.data).toMatchObject({+ code: 'rate_limit',+ details: { kind: 'credit_limit' },+ });+ });++ it('names error_max_turns as a lifecycle outcome, not the catch-all', () => {+ const adapter = new ClaudeCodeAdapter();++ adapter.adapt({ subtype: 'init', type: 'system' });+ const events = adapter.adapt({+ is_error: true,+ subtype: 'error_max_turns',+ type: 'result',+ });++ expect(events.at(-1)!.data).toMatchObject({ details: { kind: 'max_turns' } });+ });+it('classifies rate-limit failures from paired rate_limit_event + result events', () => {const adapter = new ClaudeCodeAdapter();const rawError = "You've hit your limit ยท resets 9am (Asia/Shanghai)";diff --git a/packages/heterogeneous-agents/src/adapters/claudeCode.ts b/packages/heterogeneous-agents/src/adapters/claudeCode.tsindex ec517bfdb76..80ffe7cfb0b 100644--- a/packages/heterogeneous-agents/src/adapters/claudeCode.ts+++ b/packages/heterogeneous-agents/src/adapters/claudeCode.ts@@ -36,6 +36,7 @@* - `tool_result` blocks are in `type: 'user'` events, not assistant events*/+import type { HeteroErrorKind } from '../errors/specs';import { imagePlaceholder } from '../imageEcho';import type {AgentEventAdapter,@@ -214,10 +215,32 @@ const CLI_AUTH_REQUIRED_PATTERNS = [* appears in Anthropic's transient server throttle, so leaning on it would* reintroduce the very misclassification this set exists to avoid.*/+/**+ * Credit/balance exhaustion, e.g. `You've reached your Fable 5 limit. Run+ * /usage-credits to continue or switch models with /model.` It renders the+ * same guide as a plan window, but waiting for a reset never clears it.+ */+const CLI_CREDIT_LIMIT_PATTERNS = [+ /you'?ve reached your .{0,40}\blimit\b/i,+ /\/usage-credits\b/i,+] as const;+const CLI_USER_RATE_LIMIT_PATTERNS = [/you'?ve hit your limit/i,+ // CC names the window in the wording it actually ships โ `You've hit your+ // session limit ยท resets 6:30pm (Asia/Shanghai)` and `You've hit your weekly+ // limit ยท resets Jul 3 at 1pm`. Without these the bare `you've hit your+ // limit` pattern misses every real message, leaving the 429 to fall through+ // to the overloaded (retry) guide.+ /you'?ve hit your \S+ limit/i,+ ...CLI_CREDIT_LIMIT_PATTERNS,/usage limit reached/i,/\blimit reached\b/i,+ // Gateways/proxies in front of the API localize the same quota rejection,+ // e.g. `API Error: Request rejected (429) ยท [1234][ๅทฒ่พพๅฐ 5 ๅฐๆถไฝฟ็จไธ้๏ผ+ // 2026-06-19 22:00:00 ๅๅฏ็ปง็ปญไฝฟ็จใโฆ]`. English-only patterns classified+ // these as a transient overload and told the user to just retry.+ /ไฝฟ็จไธ้/,] as const;/**@@ -233,13 +256,94 @@ const CLI_SERVER_THROTTLE_PATTERNS = [/server is temporarily limiting requests/i,] as const;+/**+ * Transport-level failures: the connection dropped, stalled, or timed out+ * before the run could finish. CC reports these as an `API Error:` line with+ * no `api_error_status` at all, so neither the 429/529 check nor the+ * overloaded wording claimed them and they fell through to the opaque generic+ * card โ with no retry affordance, even though retrying is exactly the right+ * move. They share the transient/retry UX with a server overload, so they are+ * classified as `overloaded` rather than earning a code the UI can't render.+ */+const CLI_NETWORK_ERROR_PATTERNS = [+ /unable to connect to api/i,+ /\beconnreset\b/i,+ /\beconnrefused\b/i,+ /\bconnectionrefused\b/i,+ /\betimedout\b/i,+ /\benotfound\b/i,+ /connection closed mid-response/i,+ /socket connection was closed/i,+ /socket hang up/i,+ /stream idle timeout/i,+ /response stalled mid-stream/i,+ /request timed out/i,+] as const;+const CLI_OVERLOADED_PATTERNS = [/overloaded_error/i,/\boverloaded\b/i,- /api error:\s*529\b/i,+ // Any 5xx is a server-side condition with the same retry UX โ the old+ // 529-only pattern let `API Error: 500 Internal server error` (and the+ // localized `API Error: 503 ยท [่ฏฅๆจกๅๅฝๅ่ฎฟ้ฎ้่ฟๅคง๏ผ่ฏทๆจ็จๅๅ่ฏ]`) fall+ // through to the generic card.+ /api error:\s*5\d\d\b/i,...CLI_SERVER_THROTTLE_PATTERNS,+ ...CLI_NETWORK_ERROR_PATTERNS,] as const;+/**+ * CC's internal end-of-run diagnostic, e.g.+ * `[ede_diagnostic] result_type=user last_content_type=n/a stop_reason=tool_use`.+ * It rides in the result event's `errors` array on aborted runs. It is+ * engineer-facing jargon, never a user-facing reason, so it must not become+ * the error card's message โ it belongs in the details pane.+ */+const CC_INTERNAL_DIAGNOSTIC_PATTERN = /^\[ede_diagnostic\]/i;++/**+ * Terminal reasons CC reports when a run was stopped rather than failed โ+ * a user pressing stop closes the SDK session / SIGINTs the tree, and CC+ * winds down and exits **0**. The result event is still flagged `is_error`+ * with no `result` text, so these used to surface the raw `[ede_diagnostic]`+ * line as the failure message. They are by far the most common "error" in+ * real traces, and none of them is a fault worth a red card's usual wording.+ */+const CLI_ABORTED_TERMINAL_REASONS = new Set(['aborted_streaming', 'aborted_tools']);++/**+ * The remaining long tail, each taken from real recorded traces. None of these+ * has a dedicated status guide, so they ride the generic card โ but they still+ * earn a taxonomy `kind` so the failure is named in telemetry rather than+ * pooled into the `agent_failed` catch-all.+ */+const CLI_TAIL_CLASSIFIERS: { kind: HeteroErrorKind; patterns: readonly RegExp[] }[] = [+ {+ // `No conversation found with session ID: <uuid>` โ a stale `--resume` id.+ // Arrives via the result event's `errors` array with turns=0 and no result+ // text; the spawn layer recovers it, but the run still terminates here.+ kind: 'resume_thread_not_found',+ patterns: [/no conversation found with session id/i],+ },+ {+ // `Claude Fable 5 is currently unavailable. Learn more: โฆ` /+ // `There's an issue with the selected model (claude-fable-5).`+ kind: 'model_unavailable',+ patterns: [/is currently unavailable/i, /issue with the selected model/i],+ },+ {+ // `Failed to decode image: The image format Gif is not supported`+ kind: 'unsupported_attachment',+ patterns: [/failed to decode image/i, /image format \w+ is not supported/i],+ },+ {+ // `API Error: 400 messages.6.content.2.server_tool_use.id: String should+ // match pattern โฆ` โ a malformed request; retrying reproduces it exactly.+ kind: 'invalid_request',+ patterns: [/api error:\s*400\b/i, /string should match pattern/i],+ },+];+/*** CC streams a synthetic assistant text turn when the underlying API call* fails mid-run โ e.g. `API Error: Connection closed mid-response. The@@ -314,6 +418,10 @@ const getCliResultErrors = (raw: any): string | undefined => {const text = raw.errors.map((entry: unknown) => getCliResultMessage(entry)).filter((entry?: string): entry is string => !!entry?.trim())+ // Drop CC's internal end-of-run diagnostic: it is the ONLY `errors` entry+ // on an aborted run, so letting it through made the error card read+ // `[ede_diagnostic] result_type=user last_content_type=n/a โฆ`.+ .filter((entry: string) => !CC_INTERNAL_DIAGNOSTIC_PATTERN.test(entry.trim())).join('\n');return text || undefined;@@ -450,6 +558,7 @@ const getAuthRequiredTerminalError = (agentType: 'claude-code',clearEchoedContent: true,code: 'auth_required',+ details: { kind: 'auth_required' satisfies HeteroErrorKind },docsUrl: CLAUDE_CODE_CLI_INSTALL_DOCS_URL,error: rawMessage,message:@@ -458,6 +567,62 @@ const getAuthRequiredTerminalError = (};};+/**+ * A run that was **stopped**, not one that failed โ the single most common+ * `is_error` result in real traces.+ *+ * CC flags a user stop `is_error` with `terminal_reason: 'aborted_streaming' |+ * 'aborted_tools'`, an empty `result`, and only its internal `[ede_diagnostic]`+ * line in `errors` โ while exiting **0**. It is an outcome, not a fault, so it+ * must not terminate as an `error`: that persists a red card, writes topic+ * status `failed`, and frames the user's own stop as a crash.+ *+ * Instead it terminates as `agent_runtime_end` with `reason: 'interrupted'` โ+ * the reason the runtime already uses for a mid-stream cancel+ * (`NON_COMPLETION_RUNTIME_END_REASONS`), which routes to a neutral `active`+ * topic status with no unread badge and no completion notification, while+ * still flushing whatever content the run produced before it was stopped.+ *+ * A stop that DID report a reason (a rate limit landing while winding down)+ * is not this case โ it belongs to the classifier that owns that reason.+ */+const isAbortedResult = (raw: any): boolean =>+ CLI_ABORTED_TERMINAL_REASONS.has(raw?.terminal_reason) &&+ !getCliResultMessage(raw?.result) &&+ !getCliResultErrors(raw);++const buildAbortedRuntimeEndData = (raw: any): Record<string, unknown> => ({+ kind: 'aborted' satisfies HeteroErrorKind,+ reason: 'interrupted',+ ...(typeof raw.num_turns === 'number' ? { numTurns: raw.num_turns } : {}),+ ...(typeof raw.subtype === 'string' ? { subtype: raw.subtype } : {}),+ terminalReason: raw.terminal_reason,+});++/**+ * Classify the long tail that has no dedicated guide card. The message is+ * already self-explanatory, so it is surfaced verbatim; the value added here+ * is the taxonomy `kind`, which keeps these out of the `agent_failed`+ * catch-all whose volume drives what we carve out next.+ */+const getTailTerminalError = (result: unknown): HeterogeneousTerminalErrorData | undefined => {+ const rawMessage = getCliResultMessage(result);+ if (!rawMessage) return;++ const entry = CLI_TAIL_CLASSIFIERS.find(({ patterns }) =>+ patterns.some((pattern) => pattern.test(rawMessage)),+ );+ if (!entry) return;++ return {+ agentType: 'claude-code',+ code: entry.kind,+ details: { kind: entry.kind },+ error: rawMessage,+ message: rawMessage,+ };+};+/*** Last-resort terminal error for `is_error` results that no structured* classifier (rate-limit / overloaded / auth) claimed. CC's error results@@ -482,7 +647,13 @@ const buildFallbackTerminalError = ((subtype && CLI_ERROR_SUBTYPE_MESSAGES[subtype]) ||'Agent execution failed';+ // `error_max_turns` is a named lifecycle outcome, not an unclassified+ // failure; everything else that reaches here is the catch-all whose volume+ // tells us which kind to carve out next.+ const kind: HeteroErrorKind = subtype === 'error_max_turns' ? 'max_turns' : 'agent_failed';+const details: Record<string, unknown> = {+ kind,...(raw.api_error_status == null ? {} : { apiErrorStatus: raw.api_error_status }),...(typeof raw.duration_ms === 'number' ? { durationMs: raw.duration_ms } : {}),...(streamedApiError && streamedApiError !== message ? { lastApiError: streamedApiError } : {}),@@ -525,20 +696,38 @@ const getOverloadedTerminalError = (// A real user-quota limit is the rate-limit classifier's job โ never steal// it here, even if it happened to ride in on a 429/529.if (isUserQuotaRateLimit(rateLimitInfo)) return;+ // Nor an authentication failure that merely *mentions* a transport symptom,+ // e.g. `Failed to authenticate. API Error: 401 The socket connection was+ // closed unexpectedly.` โ retrying that forever never signs the user in.+ if (apiErrorStatus === 401 || apiErrorStatus === 403) return;+ if (rawMessage && CLI_AUTH_REQUIRED_PATTERNS.some((pattern) => pattern.test(rawMessage))) return;const looksOverloaded =- // Both 529 (upstream overloaded) and a 429 with no quota signal (transient- // server throttle) are momentary server-side conditions โ same retry UX.- apiErrorStatus === 529 ||+ // Any 5xx (upstream overloaded / internal error) and a 429 with no quota+ // signal (transient server throttle) are momentary server-side conditions+ // โ same retry UX.+ (typeof apiErrorStatus === 'number' && apiErrorStatus >= 500 && apiErrorStatus < 600) ||apiErrorStatus === 429 ||(!!rawMessage && CLI_OVERLOADED_PATTERNS.some((pattern) => pattern.test(rawMessage)));if (!looksOverloaded || !rawMessage) return;+ // Same `overloaded` guide code (and therefore the same auto-retry contract),+ // but recorded as three distinct taxonomy kinds so telemetry can tell a bad+ // local network apart from a genuinely busy provider.+ const kind: HeteroErrorKind = CLI_NETWORK_ERROR_PATTERNS.some((pattern) =>+ pattern.test(rawMessage),+ )+ ? 'network_drop'+ : CLI_SERVER_THROTTLE_PATTERNS.some((pattern) => pattern.test(rawMessage))+ ? 'server_throttle'+ : 'server_overloaded';+return {agentType: 'claude-code',clearEchoedContent: true,code: 'overloaded',+ details: { kind },error: rawMessage,message: rawMessage,stderr: rawMessage,@@ -567,10 +756,19 @@ const getRateLimitTerminalError = (if (!looksLikeUserLimit || !rawMessage) return;+ // A credit/balance limit shares the `rate_limit` guide but not its remedy:+ // waiting for a reset never clears it, so it is a distinct taxonomy kind.+ const kind: HeteroErrorKind = CLI_CREDIT_LIMIT_PATTERNS.some((pattern) =>+ pattern.test(rawMessage),+ )+ ? 'credit_limit'+ : 'usage_limit';+return {agentType: 'claude-code',clearEchoedContent: true,code: 'rate_limit',+ details: { kind },error: rawMessage,message: rawMessage,rateLimitInfo,@@ -1708,21 +1906,28 @@ export class ClaudeCodeAdapter implements AgentEventAdapter {const classifiableResult =getCliResultMessage(raw.result) || getCliResultErrors(raw) || this.lastApiErrorText;const rateLimitError = getRateLimitTerminalError(classifiableResult, this.pendingRateLimitInfo);- const finalEvent: HeterogeneousAgentEvent | undefined = raw.is_error- ? this.makeEvent(- 'error',- rateLimitError ||- getOverloadedTerminalError(- classifiableResult,- raw.api_error_status,- this.pendingRateLimitInfo,- ) ||- getAuthRequiredTerminalError(classifiableResult) ||- buildFallbackTerminalError(raw, this.lastApiErrorText),- )- : this.options.runtimeEndStrategy === 'on-result'- ? this.makeEvent('agent_runtime_end', {})- : undefined;+ // A stop is resolved before any classifier: it reports no reason of its+ // own, so every one of them would either miss it or mislabel it. It then+ // follows the SAME runtime-end strategy as a clean finish, because it is+ // now a non-error terminal like one.+ const aborted = isAbortedResult(raw);+ const finalEvent: HeterogeneousAgentEvent | undefined =+ raw.is_error && !aborted+ ? this.makeEvent(+ 'error',+ rateLimitError ||+ getOverloadedTerminalError(+ classifiableResult,+ raw.api_error_status,+ this.pendingRateLimitInfo,+ ) ||+ getAuthRequiredTerminalError(classifiableResult) ||+ getTailTerminalError(classifiableResult) ||+ buildFallbackTerminalError(raw, this.lastApiErrorText),+ )+ : this.options.runtimeEndStrategy === 'on-result'+ ? this.makeEvent('agent_runtime_end', aborted ? buildAbortedRuntimeEndData(raw) : {})+ : undefined;this.pendingRateLimitInfo = undefined;this.lastApiErrorText = undefined;diff --git a/packages/heterogeneous-agents/src/errors/index.ts b/packages/heterogeneous-agents/src/errors/index.tsnew file mode 100644index 00000000000..037d2f02b4f--- /dev/null+++ b/packages/heterogeneous-agents/src/errors/index.ts@@ -0,0 +1,14 @@+export type { HeteroErrorKind, HeteroErrorSpec } from './specs';+export {+ formatHeteroErrorId,+ getHeteroErrorSpec,+ HETERO_ERROR_SPECS,+ isUserSideHeteroError,+} from './specs';+export type {+ HeteroErrorAttribution,+ HeteroErrorCategory,+ HeteroErrorSeverity,+ HeteroGuideCode,+} from './taxonomy';+export { HETERO_CATEGORY_NUMERIC_PREFIX } from './taxonomy';diff --git a/packages/heterogeneous-agents/src/errors/specs.test.ts b/packages/heterogeneous-agents/src/errors/specs.test.tsnew file mode 100644index 00000000000..58134970bcd--- /dev/null+++ b/packages/heterogeneous-agents/src/errors/specs.test.ts@@ -0,0 +1,69 @@+import { describe, expect, it } from 'vitest';++import {+ formatHeteroErrorId,+ getHeteroErrorSpec,+ HETERO_ERROR_SPECS,+ isUserSideHeteroError,+} from './specs';+import { HETERO_CATEGORY_NUMERIC_PREFIX } from './taxonomy';++describe('hetero error taxonomy', () => {+ const specs = Object.values(HETERO_ERROR_SPECS);++ it('keys every spec by its own kind', () => {+ for (const [key, spec] of Object.entries(HETERO_ERROR_SPECS)) {+ expect(spec.kind).toBe(key);+ }+ });++ it('assigns numericIds whose leading digit matches the category', () => {+ for (const spec of specs) {+ const leading = Number(String(spec.numericId)[0]);+ expect(leading).toBe(HETERO_CATEGORY_NUMERIC_PREFIX[spec.category]);+ expect(String(spec.numericId)).toHaveLength(4);+ }+ });++ it('keeps numericIds unique โ they are an append-only external reference', () => {+ const ids = specs.map((spec) => spec.numericId);+ expect(new Set(ids).size).toBe(ids.length);+ });++ it('only emits guide codes the client can actually render', () => {+ const renderable = new Set(['auth_required', 'cli_not_found', 'overloaded', 'rate_limit']);+ for (const spec of specs) {+ if (spec.guideCode) expect(renderable).toContain(spec.guideCode);+ }+ });++ it('never marks a user-attributed outcome as an operational failure', () => {+ for (const spec of specs) {+ if (spec.attribution === 'user') expect(spec.countAsFailure).toBe(false);+ }+ });++ it('only treats transient kinds as retryable', () => {+ const retryable = specs.filter((spec) => spec.retryable).map((spec) => spec.kind);+ expect(retryable.toSorted()).toEqual(['network_drop', 'server_overloaded', 'server_throttle']);+ });++ it('exposes exactly one fallback bucket', () => {+ const fallbacks = specs.filter((spec) => spec.isFallback).map((spec) => spec.kind);+ expect(fallbacks).toEqual(['agent_failed']);+ });++ it('formats and resolves stable ids', () => {+ expect(formatHeteroErrorId('usage_limit')).toBe('H2001');+ expect(formatHeteroErrorId('agent_failed')).toBe('H9002');+ expect(getHeteroErrorSpec('aborted')?.category).toBe('lifecycle');+ expect(getHeteroErrorSpec('nope')).toBeUndefined();+ });++ it('excludes expected user-side outcomes from failure metrics', () => {+ expect(isUserSideHeteroError('aborted')).toBe(true);+ expect(isUserSideHeteroError('usage_limit')).toBe(true);+ expect(isUserSideHeteroError('network_drop')).toBe(false);+ expect(isUserSideHeteroError('unknown_kind')).toBe(false);+ });+});diff --git a/packages/heterogeneous-agents/src/errors/specs.ts b/packages/heterogeneous-agents/src/errors/specs.tsnew file mode 100644index 00000000000..a2c64dfa77b--- /dev/null+++ b/packages/heterogeneous-agents/src/errors/specs.ts@@ -0,0 +1,281 @@+import type {+ HeteroErrorAttribution,+ HeteroErrorCategory,+ HeteroErrorSeverity,+ HeteroGuideCode,+} from './taxonomy';++/**+ * Every failure kind a heterogeneous run can be classified into.+ *+ * Naming is behavioral, not textual: `usage_limit` is "the user's plan window+ * is exhausted", regardless of whether the CLI said `You've hit your session+ * limit`, `weekly limit`, or a gateway localized it to `ๅทฒ่พพๅฐ 5 ๅฐๆถไฝฟ็จไธ้`.+ */+export type HeteroErrorKind =+ // auth+ | 'auth_required'+ // quota+ | 'usage_limit'+ | 'credit_limit'+ // capacity+ | 'server_overloaded'+ | 'server_throttle'+ // request+ | 'invalid_request'+ | 'unsupported_attachment'+ // network+ | 'network_drop'+ // lifecycle+ | 'aborted'+ | 'max_turns'+ // session+ | 'resume_thread_not_found'+ | 'resume_cwd_mismatch'+ // environment+ | 'cli_not_found'+ // provider+ | 'model_unavailable'+ | 'agent_failed';++export interface HeteroErrorSpec {+ attribution: HeteroErrorAttribution;+ category: HeteroErrorCategory;+ /** Whether this kind counts toward operational failure metrics. */+ countAsFailure: boolean;+ /** Short English description for dashboards / docs. */+ description: string;+ /**+ * The coarse code emitted on the wire so the client renders a dedicated+ * status guide. Absent โ the generic error card shows the message verbatim,+ * which is only acceptable when that message explains itself.+ */+ guideCode?: HeteroGuideCode;+ /**+ * Marks a catch-all bucket. Monitoring tracks its volume to decide when a+ * finer kind is worth carving out โ this is exactly how `agent_failed` went+ * from 53% of all real errors to ~3%.+ */+ isFallback?: boolean;+ kind: HeteroErrorKind;+ /** Stable identifier surfaced as `H<numericId>`. Append-only. */+ numericId: number;+ /** Whether an automatic retry of the same run is worth attempting. */+ retryable: boolean;+ severity: HeteroErrorSeverity;+}++/**+ * Single source of truth for heterogeneous run failures.+ *+ * To add a kind:+ * 1. Add it to `HeteroErrorKind` above.+ * 2. Add a spec entry here with the next free `numericId` in its category.+ * 3. Teach a classifier to produce it (`../adapters/*.ts` for in-stream+ * failures, `../spawn/classifyProcessFailure.ts` for pre-stream ones).+ * 4. If it needs a dedicated card, give it a `guideCode` AND register that+ * code in the two status-guide sets named in `./taxonomy`.+ */+export const HETERO_ERROR_SPECS: Record<HeteroErrorKind, HeteroErrorSpec> = {+ // โโโ 1xxx Auth โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ+ auth_required: {+ attribution: 'user',+ category: 'auth',+ countAsFailure: false,+ description:+ 'The CLI has no usable credentials โ never signed in, or the token was rejected/expired.',+ guideCode: 'auth_required',+ kind: 'auth_required',+ numericId: 1001,+ retryable: false,+ severity: 'warning',+ },++ // โโโ 2xxx Quota โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ+ usage_limit: {+ attribution: 'user',+ category: 'quota',+ countAsFailure: false,+ description:+ "The user's plan window is exhausted and carries a concrete reset time (5-hour / session / weekly).",+ guideCode: 'rate_limit',+ kind: 'usage_limit',+ numericId: 2001,+ retryable: false,+ severity: 'warning',+ },+ credit_limit: {+ attribution: 'user',+ category: 'quota',+ countAsFailure: false,+ description:+ 'Credits or balance for the selected model are exhausted; resolved by topping up or switching model, not by waiting.',+ guideCode: 'rate_limit',+ kind: 'credit_limit',+ numericId: 2002,+ retryable: false,+ severity: 'warning',+ },++ // โโโ 3xxx Capacity โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ+ server_overloaded: {+ attribution: 'provider',+ category: 'capacity',+ countAsFailure: true,+ description: 'Upstream returned 5xx / overloaded_error. Momentary; the same request may pass.',+ guideCode: 'overloaded',+ kind: 'server_overloaded',+ numericId: 3001,+ retryable: true,+ severity: 'warning',+ },+ server_throttle: {+ attribution: 'provider',+ category: 'capacity',+ countAsFailure: true,+ description:+ 'Provider-side transient throttle: a 429 that explicitly disclaims the plan limit ("not your usage limit"). Clears on its own.',+ guideCode: 'overloaded',+ kind: 'server_throttle',+ numericId: 3002,+ retryable: true,+ severity: 'warning',+ },++ // โโโ 4xxx Request โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ+ invalid_request: {+ attribution: 'harness',+ category: 'request',+ countAsFailure: true,+ description:+ 'Upstream rejected the request as malformed (400) โ e.g. a tool-use id that fails schema validation. Retrying is futile.',+ kind: 'invalid_request',+ numericId: 4001,+ retryable: false,+ severity: 'error',+ },+ unsupported_attachment: {+ attribution: 'user',+ category: 'request',+ countAsFailure: false,+ description: 'An attached file could not be decoded or is an unsupported format.',+ kind: 'unsupported_attachment',+ numericId: 4002,+ retryable: false,+ severity: 'warning',+ },++ // โโโ 5xxx Network โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ+ network_drop: {+ attribution: 'system',+ category: 'network',+ countAsFailure: true,+ description:+ 'The connection reset, refused, stalled, or timed out mid-run. Shares the retry contract with a capacity failure, so it reports the `overloaded` guide code.',+ guideCode: 'overloaded',+ kind: 'network_drop',+ numericId: 5001,+ retryable: true,+ severity: 'warning',+ },++ // โโโ 6xxx Lifecycle โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ+ aborted: {+ attribution: 'user',+ category: 'lifecycle',+ countAsFailure: false,+ description:+ 'The run was stopped before finishing (the user pressed stop). The CLI flags the result `is_error` while exiting 0, but it is an outcome, not a fault โ so it does NOT terminate as an error: it ends as `agent_runtime_end { reason: "interrupted" }`, leaving the topic neutral with no error card, no unread badge, and no completion notification.',+ kind: 'aborted',+ numericId: 6001,+ retryable: false,+ severity: 'info',+ },+ max_turns: {+ attribution: 'harness',+ category: 'lifecycle',+ countAsFailure: true,+ description: 'The run hit its configured maximum number of turns and stopped short.',+ kind: 'max_turns',+ numericId: 6002,+ retryable: false,+ severity: 'warning',+ },++ // โโโ 7xxx Session โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ+ resume_thread_not_found: {+ attribution: 'harness',+ category: 'session',+ countAsFailure: true,+ description:+ 'The `--resume` id no longer exists in the CLI\'s local store ("No conversation found with session ID"). Recovered by rebuilding the transcript or starting a fresh session.',+ kind: 'resume_thread_not_found',+ numericId: 7001,+ retryable: false,+ severity: 'warning',+ },+ resume_cwd_mismatch: {+ attribution: 'harness',+ category: 'session',+ countAsFailure: true,+ description:+ 'Resume was attempted from a different working directory than the one that created the session.',+ kind: 'resume_cwd_mismatch',+ numericId: 7002,+ retryable: false,+ severity: 'warning',+ },++ // โโโ 8xxx Environment โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ+ cli_not_found: {+ attribution: 'user',+ category: 'environment',+ countAsFailure: false,+ description:+ 'The agent CLI is not installed or not executable on the machine running the run (`spawn <cmd> ENOENT`).',+ guideCode: 'cli_not_found',+ kind: 'cli_not_found',+ numericId: 8001,+ retryable: false,+ severity: 'warning',+ },++ // โโโ 9xxx Provider โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ+ model_unavailable: {+ attribution: 'provider',+ category: 'provider',+ countAsFailure: true,+ description:+ 'The selected model is withdrawn, gated, or temporarily unavailable. Resolved by switching model, not by retrying.',+ kind: 'model_unavailable',+ numericId: 9001,+ retryable: false,+ severity: 'warning',+ },+ agent_failed: {+ attribution: 'harness',+ category: 'provider',+ countAsFailure: true,+ description:+ 'Catch-all: the run failed with a reason no classifier claimed. Volume here is the signal for which kind to carve out next.',+ isFallback: true,+ kind: 'agent_failed',+ numericId: 9002,+ retryable: false,+ severity: 'error',+ },+};++/** Formatted stable id, e.g. `H2001`. */+export const formatHeteroErrorId = (kind: HeteroErrorKind): string =>+ `H${HETERO_ERROR_SPECS[kind].numericId}`;++export const getHeteroErrorSpec = (kind: string): HeteroErrorSpec | undefined =>+ HETERO_ERROR_SPECS[kind as HeteroErrorKind];++/**+ * True when the failure is an expected user-side or user-initiated outcome and+ * should be excluded from operational failure metrics.+ */+export const isUserSideHeteroError = (kind: string): boolean =>+ getHeteroErrorSpec(kind)?.countAsFailure === false;diff --git a/packages/heterogeneous-agents/src/errors/taxonomy.ts b/packages/heterogeneous-agents/src/errors/taxonomy.tsnew file mode 100644index 00000000000..71c40a169ca--- /dev/null+++ b/packages/heterogeneous-agents/src/errors/taxonomy.ts@@ -0,0 +1,88 @@+/**+ * Heterogeneous (external CLI agent) error taxonomy.+ *+ * Mirrors the model-runtime taxonomy (`@lobechat/model-runtime/errors`) in+ * shape and intent, but classifies a different failure surface: instead of one+ * HTTP call to a model provider, a heterogeneous run is a **local CLI process**+ * that streams events and can die at any of four layers โ spawn, transport,+ * the provider behind the CLI, or the run's own lifecycle.+ *+ * Two identifiers, deliberately separate:+ *+ * - `kind` โ the fine-grained classification (this module). It is what+ * dashboards slice on and what we reason about.+ * - `guideCode` โ the coarse code actually emitted on the wire as+ * `HeterogeneousTerminalErrorData.code`, because the client renders exactly+ * four status-guide cards and hardwires behavior to them (notably+ * `overloaded` โ capped auto-retry in `useHeterogeneousAutoRetry`).+ *+ * Keeping them separate is what lets `network_drop` and `server_overloaded`+ * stay distinct rows in the taxonomy while sharing one retry contract on+ * screen. Collapsing them into a single field is what previously made+ * "transient transport failure" indistinguishable from "provider is busy".+ *+ * Four dimensions, same meaning as model-runtime:+ *+ * - `category` โ semantic bucket for dashboard slicing.+ * - `severity` โ log level / alerting hint.+ * - `attribution` โ who owns the fix:+ * - `user` โ user signs in / waits for a reset / fixes their input.+ * - `provider` โ the model provider behind the CLI; neither user nor we+ * can fix it directly.+ * - `harness` โ our bug (LobeHub, the adapter, the spawn/resume plumbing)+ * or the CLI's own.+ * - `system` โ machine / network / OS layer.+ * - `countAsFailure` โ whether it should count toward operational failure+ * metrics. User-side and user-initiated outcomes are false: a usage limit or+ * a deliberate stop is an expected outcome, not an incident.+ */+export type HeteroErrorCategory =+ | 'auth' // credentials, login state+ | 'quota' // plan windows, credits, balance+ | 'capacity' // upstream overload / transient throttle+ | 'request' // malformed request, unsupported input+ | 'network' // transport drop, stall, timeout+ | 'lifecycle' // the run ended without completing (stopped, max turns)+ | 'session' // resume / conversation continuity+ | 'environment' // the CLI itself: missing, unusable+ | 'provider'; // provider-side biz error + catch-all++export type HeteroErrorSeverity = 'info' | 'warning' | 'error' | 'critical';++export type HeteroErrorAttribution = 'user' | 'provider' | 'harness' | 'system';++/**+ * The four codes the client can actually render a dedicated status guide for.+ * Anything else falls back to the generic error card, which shows the message+ * verbatim โ acceptable only when the message is self-explanatory.+ *+ * Must stay in sync with `HETEROGENEOUS_AGENT_STATUS_GUIDE_ERROR_CODES`+ * (`src/features/Conversation/Error/heterogeneous.ts`) and+ * `STATUS_GUIDE_ERROR_CODES` (`../spawn/classifyProcessFailure.ts`).+ */+export type HeteroGuideCode = 'auth_required' | 'cli_not_found' | 'overloaded' | 'rate_limit';++/**+ * Mapping of category โ leading digit of the `numericId`.+ *+ * The 4-digit `numericId` is surfaced as `H<numericId>` (e.g. `H2001`) โ the+ * `H` namespace keeps it from colliding with model-runtime's `E<numericId>`,+ * which numbers a different set of categories.+ *+ * digit 1 โ category bucket (this map)+ * digits 2-4 โ sequence within the category+ *+ * Append-only: once published, a (kind, numericId) pair never changes, so it+ * can be referenced from support tickets and dashboards long-term.+ */+export const HETERO_CATEGORY_NUMERIC_PREFIX: Record<HeteroErrorCategory, number> = {+ auth: 1,+ quota: 2,+ capacity: 3,+ request: 4,+ network: 5,+ lifecycle: 6,+ session: 7,+ environment: 8,+ provider: 9,+};diff --git a/packages/heterogeneous-agents/src/index.ts b/packages/heterogeneous-agents/src/index.tsindex 9810384b9ef..a2e8ec51227 100644--- a/packages/heterogeneous-agents/src/index.ts+++ b/packages/heterogeneous-agents/src/index.ts@@ -10,6 +10,21 @@ export {isRemoteHeterogeneousType,REMOTE_HETEROGENEOUS_AGENT_CONFIGS,} from './config';+export type {+ HeteroErrorAttribution,+ HeteroErrorCategory,+ HeteroErrorKind,+ HeteroErrorSeverity,+ HeteroErrorSpec,+ HeteroGuideCode,+} from './errors';+export {+ formatHeteroErrorId,+ getHeteroErrorSpec,+ HETERO_CATEGORY_NUMERIC_PREFIX,+ HETERO_ERROR_SPECS,+ isUserSideHeteroError,+} from './errors';export { HETEROGENEOUS_TYPE_LABELS } from './labels';export type {CreateAssistantIntent,diff --git a/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.tsindex 36bc47d59f9..fbfdb41054a 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts@@ -5645,6 +5645,42 @@ describe('heterogeneousAgentExecutor DB persistence', () => {);});+ // โโ 5b. CLI-reported stop โ non-error terminal, but still not a completion โโ+ it('a CLI-reported stop writes "active", fires NO notification and NO drain', async () => {+ desktopFlag.value = true;+ const updateTopicStatus = vi.fn();+ const store = createMockStore({+ activeTopicId: 'topic-1',+ drainQueuedMessages: vi.fn(() => [{ content: 'queued', id: 'q1' }]),+ updateTopicStatus,+ });++ // No abortController: the stop was reported by the CLI itself, so+ // `isAborted()` is false and only the terminal's `interrupted` reason+ // can distinguish this from a finished run.+ await runToComplete(store, [+ ccInit(),+ ccText('msg_01', 'partial'),+ {+ errors: ['[ede_diagnostic] result_type=user last_content_type=n/a stop_reason=tool_use'],+ is_error: true,+ subtype: 'error_during_execution',+ terminal_reason: 'aborted_streaming',+ type: 'result',+ },+ ]);++ // Not a failure: no error persisted, topic left neutral.+ expect(mockUpdateMessageError).not.toHaveBeenCalled();+ expect(updateTopicStatus).toHaveBeenCalledWith(+ expect.objectContaining({ status: 'active', topicId: 'topic-1' }),+ );+ // Not a completion either: announcing it or draining the queue would+ // treat the user's stop as a finished turn.+ expect(mockShowNotification).not.toHaveBeenCalled();+ expect(store.drainQueuedMessages).not.toHaveBeenCalled();+ });+// โโ 5. stuck-spinner regression: status reset must not wait on queued persistence โโit('resets topic status even when the persist queue never drains', async () => {// A DB write that never settles โ mirrors a dropped desktop-IPC reply. Itdiff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.tsindex 32493e4b848..650573d547d 100644--- a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts@@ -2204,6 +2204,16 @@ export const executeHeterogeneousAgent = async (}const isErrorTerminal = deferredTerminalEvent?.type === 'error';+ // A run can also end WITHOUT failing and without completing: a stop+ // terminates as `agent_runtime_end { reason: 'interrupted' }` (see+ // the CC adapter). Everything gated on "not an error" must gate on+ // this instead, or a stopped run would drain the queue and fire a+ // "run finished" notification.+ const isCleanCompletion =+ !isErrorTerminal &&+ isCompletedRuntimeEnd(+ (deferredTerminalEvent?.data as { reason?: string } | undefined)?.reason,+ );// Reset the sidebar "running" status BEFORE awaiting the persist queue.// Topic status is independent of message persistence, so a stalled queue@@ -2212,10 +2222,9 @@ export const executeHeterogeneousAgent = async (// this guards against. Content persistence + the terminal forward still// wait for queued reducer state so terminal never flushes stale content.{- const reason = (deferredTerminalEvent?.data as { reason?: string } | undefined)?.reason;if (isErrorTerminal) {writeTopicStatus('failed');- } else if (!isAborted() && isCompletedRuntimeEnd(reason)) {+ } else if (!isAborted() && isCleanCompletion) {// Clean completion: the viewer sees 'active'; a background topic gets// the unread badge (markTopicUnread self-guards on activeTopicId).if (get().activeTopicId === context.topicId) writeTopicStatus('active');@@ -2324,8 +2333,10 @@ export const executeHeterogeneousAgent = async (// showNotification + setBadgeCount fan-out for non-client runtimes. We pass// the in-memory accumulated content (the store snapshot isn't durable yet);// the shared helper strips markdown + caps length + resolves the title.- // Skip for aborted runs and for error terminations.- if (!isAborted() && !isErrorTerminal) {+ // Skip for aborted runs and for error terminations โ including a run+ // the CLI itself reported as stopped (`interrupted`), which is not a+ // finished run and must not announce itself as one.+ if (!isAborted() && isCleanCompletion) {await runLifecycle.afterRunComplete({context,notification: { content: finalContent },@@ -2459,7 +2470,14 @@ export const executeHeterogeneousAgent = async (// Cast: TS narrows the closure-mutated `deferredTerminalEvent` back to// `null` in linear flow (it can't see writes from the async IPC handler).const terminalEvent = deferredTerminalEvent as AgentStreamEvent | null;- if (!isAborted() && terminalEvent?.type !== 'error') {+ // A stop reported by the CLI itself terminates as `agent_runtime_end+ // { reason: 'interrupted' }` rather than an error, so testing for "not an+ // error" is no longer enough โ that would drain the queue on a stop the+ // user made, which is exactly what this guard exists to prevent.+ const drainableTerminal =+ terminalEvent?.type !== 'error' &&+ isCompletedRuntimeEnd((terminalEvent?.data as { reason?: string } | undefined)?.reason);+ if (!isAborted() && drainableTerminal) {const contextKey = messageMapKey(context);const remainingQueued = get().drainQueuedMessages?.(contextKey) ?? [];if (remainingQueued.length > 0) {