Skip to content

🀯 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.

✨ feat(heterogeneous-agents): enrich Claude Code terminal error reporting (#17034)

Arvin Xua0ba6f5b0ff4
diff --git a/packages/electron-client-ipc/src/types/heterogeneousAgent.ts b/packages/electron-client-ipc/src/types/heterogeneousAgent.ts
index b75e4a9c915..73941ad0864 100644
--- a/packages/electron-client-ipc/src/types/heterogeneousAgent.ts
+++ b/packages/electron-client-ipc/src/types/heterogeneousAgent.ts
@@ -94,6 +94,8 @@ export interface HeterogeneousAgentSessionError {
agentType?: string;
code?: HeterogeneousAgentSessionErrorCode | string;
command?: string;
+ /** Diagnostic context from the CLI's terminal event (subtype, HTTP status, turn count, …). */
+ details?: Record<string, unknown>;
docsUrl?: string;
installCommands?: readonly string[];
message: string;
diff --git a/packages/heterogeneous-agents/src/adapters/claudeCode.test.ts b/packages/heterogeneous-agents/src/adapters/claudeCode.test.ts
index 47a2329aa70..10af42ba796 100644
--- a/packages/heterogeneous-agents/src/adapters/claudeCode.test.ts
+++ b/packages/heterogeneous-agents/src/adapters/claudeCode.test.ts
@@ -61,6 +61,109 @@ describe('ClaudeCodeAdapter', () => {
const events = adapter.adapt({ is_error: true, result: 'boom', type: 'result' });
expect(events.map((e) => e.type)).toEqual(['stream_end', 'visible_output_end', 'error']);
expect(events[2].data.message).toBe('boom');
+ // agentType marks the payload so the executor persists the WHOLE object
+ // as the error body instead of flattening it to a generic message.
+ expect(events[2].data.agentType).toBe('claude-code');
+ });
+
+ it('surfaces the streamed API error text when an error result carries no message', () => {
+ const adapter = new ClaudeCodeAdapter();
+ const apiError =
+ 'API Error: Connection closed mid-response. The response above may be incomplete.';
+
+ adapter.adapt({ session_id: 'sess_net', subtype: 'init', type: 'system' });
+ adapter.adapt({
+ message: { content: [{ text: apiError, type: 'text' }], id: 'msg_1' },
+ type: 'assistant',
+ });
+ const events = adapter.adapt({
+ duration_ms: 157_000,
+ is_error: true,
+ num_turns: 2,
+ session_id: 'sess_net',
+ subtype: 'error_during_execution',
+ type: 'result',
+ });
+
+ const errorEvent = events.at(-1)!;
+ expect(errorEvent.type).toBe('error');
+ expect(errorEvent.data).toMatchObject({
+ agentType: 'claude-code',
+ code: 'error_during_execution',
+ details: {
+ durationMs: 157_000,
+ numTurns: 2,
+ sessionId: 'sess_net',
+ subtype: 'error_during_execution',
+ },
+ error: apiError,
+ message: apiError,
+ });
+ });
+
+ it('describes error_max_turns results that carry no message', () => {
+ const adapter = new ClaudeCodeAdapter();
+ adapter.adapt({ subtype: 'init', type: 'system' });
+ const events = adapter.adapt({
+ is_error: true,
+ num_turns: 50,
+ subtype: 'error_max_turns',
+ type: 'result',
+ });
+
+ const errorEvent = events.at(-1)!;
+ expect(errorEvent.type).toBe('error');
+ expect(errorEvent.data).toMatchObject({
+ code: 'error_max_turns',
+ details: { numTurns: 50, subtype: 'error_max_turns' },
+ message: 'Claude Code stopped after reaching its maximum number of turns for this run.',
+ });
+ });
+
+ it('classifies auth failures from streamed API error text when the result is empty', () => {
+ const adapter = new ClaudeCodeAdapter();
+ const apiError =
+ 'API Error: 401 {"type":"error","error":{"type":"authentication_error","message":"Invalid authentication credentials"}}';
+
+ adapter.adapt({ subtype: 'init', type: 'system' });
+ adapter.adapt({
+ message: { content: [{ text: apiError, type: 'text' }], id: 'msg_1' },
+ type: 'assistant',
+ });
+ const events = adapter.adapt({
+ is_error: true,
+ subtype: 'error_during_execution',
+ type: 'result',
+ });
+
+ const errorEvent = events.at(-1)!;
+ expect(errorEvent.type).toBe('error');
+ expect(errorEvent.data).toMatchObject({ code: 'auth_required', stderr: apiError });
+ });
+
+ it('does NOT let a stale streamed API error leak into the next run', () => {
+ const adapter = new ClaudeCodeAdapter();
+ adapter.adapt({ subtype: 'init', type: 'system' });
+ adapter.adapt({
+ message: {
+ content: [{ text: 'API Error: Connection closed mid-response.', type: 'text' }],
+ id: 'msg_1',
+ },
+ type: 'assistant',
+ });
+ adapter.adapt({ is_error: true, subtype: 'error_during_execution', type: 'result' });
+
+ // Next turn on the same adapter fails without any streamed API error.
+ const events = adapter.adapt({
+ is_error: true,
+ subtype: 'error_during_execution',
+ type: 'result',
+ });
+ const errorEvent = events.at(-1)!;
+ expect(errorEvent.data.message).toBe(
+ 'Claude Code hit an error mid-run and exited without reporting a reason.',
+ );
+ expect(errorEvent.data.details?.lastApiError).toBeUndefined();
});
it('keeps runtime open until transport close in SDK mode', () => {
diff --git a/packages/heterogeneous-agents/src/adapters/claudeCode.ts b/packages/heterogeneous-agents/src/adapters/claudeCode.ts
index 2f646232576..b06139f2604 100644
--- a/packages/heterogeneous-agents/src/adapters/claudeCode.ts
+++ b/packages/heterogeneous-agents/src/adapters/claudeCode.ts
@@ -236,6 +236,25 @@ const CLI_OVERLOADED_PATTERNS = [
...CLI_SERVER_THROTTLE_PATTERNS,
] as const;
+/**
+ * CC streams a synthetic assistant text turn when the underlying API call
+ * fails mid-run β€” e.g. `API Error: Connection closed mid-response. The
+ * response above may be incomplete.`. The paired terminal `result` event
+ * usually carries NO `result` text for these failures (`subtype:
+ * 'error_during_execution'` and nothing else), so that streamed line is the
+ * only human-readable reason available to the terminal error card.
+ */
+const CC_SYNTHETIC_API_ERROR_PATTERN = /^API Error\b/;
+
+/**
+ * Human-readable fallbacks for CC's terminal error subtypes, used when
+ * neither the result event nor the stream carried any message text.
+ */
+const CLI_ERROR_SUBTYPE_MESSAGES: Record<string, string> = {
+ error_during_execution: 'Claude Code hit an error mid-run and exited without reporting a reason.',
+ error_max_turns: 'Claude Code stopped after reaching its maximum number of turns for this run.',
+};
+
/**
* Discriminates a user-side plan/quota limit from everything else.
*
@@ -416,6 +435,47 @@ const getAuthRequiredTerminalError = (
};
};
+/**
+ * Last-resort terminal error for `is_error` results that no structured
+ * classifier (rate-limit / overloaded / auth) claimed. CC's error results
+ * frequently carry NO `result` text at all β€” a mid-response network drop
+ * yields `{subtype: 'error_during_execution', is_error: true}` and nothing
+ * else β€” which used to surface as an opaque `Agent execution failed`.
+ * Prefer, in order: the CLI's own result text, the synthetic `API Error:`
+ * line captured off the stream, then a subtype-specific description β€” and
+ * attach the result event's diagnostic fields so the error card's details
+ * pane says what actually happened.
+ */
+const buildFallbackTerminalError = (
+ raw: any,
+ streamedApiError?: string,
+): HeterogeneousTerminalErrorData => {
+ const subtype =
+ typeof raw.subtype === 'string' && raw.subtype !== 'success' ? raw.subtype : undefined;
+ const message =
+ getCliResultMessage(raw.result) ||
+ streamedApiError ||
+ (subtype && CLI_ERROR_SUBTYPE_MESSAGES[subtype]) ||
+ 'Agent execution failed';
+
+ const details: Record<string, unknown> = {
+ ...(raw.api_error_status == null ? {} : { apiErrorStatus: raw.api_error_status }),
+ ...(typeof raw.duration_ms === 'number' ? { durationMs: raw.duration_ms } : {}),
+ ...(streamedApiError && streamedApiError !== message ? { lastApiError: streamedApiError } : {}),
+ ...(typeof raw.num_turns === 'number' ? { numTurns: raw.num_turns } : {}),
+ ...(typeof raw.session_id === 'string' ? { sessionId: raw.session_id } : {}),
+ ...(subtype ? { subtype } : {}),
+ };
+
+ return {
+ agentType: 'claude-code',
+ ...(subtype ? { code: subtype } : {}),
+ ...(Object.keys(details).length > 0 ? { details } : {}),
+ error: message,
+ message,
+ };
+};
+
const toRateLimitInfo = (value: unknown): HeterogeneousRateLimitInfo | undefined => {
if (!value || typeof value !== 'object') return;
@@ -652,6 +712,13 @@ export class ClaudeCodeAdapter implements AgentEventAdapter {
* authoritative usage on `message_delta`.
*/
private currentStreamEventModel: string | undefined;
+ /**
+ * Latest synthetic `API Error: …` assistant text seen on the main stream
+ * (see {@link CC_SYNTHETIC_API_ERROR_PATTERN}). Feeds the terminal error
+ * classifiers / fallback in `handleResult` when the error result event
+ * itself carries no text; cleared at end of run.
+ */
+ private lastApiErrorText?: string;
/** Cumulative text streamed via partial-message deltas, keyed by message.id. */
private streamedTextByMessageId = new Map<string, string>();
/** Cumulative thinking streamed via partial-message deltas, keyed by message.id. */
@@ -986,7 +1053,11 @@ export class ClaudeCodeAdapter implements AgentEventAdapter {
for (const block of content) {
switch (block.type) {
case 'text': {
- if (block.text) textParts.push(block.text);
+ if (block.text) {
+ textParts.push(block.text);
+ const trimmed = block.text.trim();
+ if (CC_SYNTHETIC_API_ERROR_PATTERN.test(trimmed)) this.lastApiErrorText = trimmed;
+ }
break;
}
case 'thinking': {
@@ -1192,7 +1263,11 @@ export class ClaudeCodeAdapter implements AgentEventAdapter {
for (const block of content) {
switch (block.type) {
case 'text': {
- if (block.text) textParts.push(block.text);
+ if (block.text) {
+ textParts.push(block.text);
+ const trimmed = block.text.trim();
+ if (CC_SYNTHETIC_API_ERROR_PATTERN.test(trimmed)) this.lastApiErrorText = trimmed;
+ }
break;
}
case 'thinking': {
@@ -1600,27 +1675,31 @@ export class ClaudeCodeAdapter implements AgentEventAdapter {
);
}
- const resultMessage = getCliResultMessage(raw.result) || 'Agent execution failed';
- const rateLimitError = getRateLimitTerminalError(raw.result, this.pendingRateLimitInfo);
+ // Classifiers read the result text; a mid-run API failure often ships an
+ // EMPTY result (`subtype: 'error_during_execution'` and nothing else), so
+ // fall back to the synthetic `API Error:` line captured off the stream β€”
+ // an auth / overload failure that died mid-response still classifies to
+ // its dedicated guide instead of the generic fallback.
+ const classifiableResult = getCliResultMessage(raw.result) || this.lastApiErrorText;
+ const rateLimitError = getRateLimitTerminalError(classifiableResult, this.pendingRateLimitInfo);
const finalEvent: HeterogeneousAgentEvent | undefined = raw.is_error
? this.makeEvent(
'error',
rateLimitError ||
getOverloadedTerminalError(
- raw.result,
+ classifiableResult,
raw.api_error_status,
this.pendingRateLimitInfo,
) ||
- getAuthRequiredTerminalError(raw.result) || {
- error: resultMessage,
- message: resultMessage,
- },
+ getAuthRequiredTerminalError(classifiableResult) ||
+ buildFallbackTerminalError(raw, this.lastApiErrorText),
)
: this.options.runtimeEndStrategy === 'on-result'
? this.makeEvent('agent_runtime_end', {})
: undefined;
this.pendingRateLimitInfo = undefined;
+ this.lastApiErrorText = undefined;
this.streamedTextByMessageId.clear();
this.streamedThinkingByMessageId.clear();
// Drop any unconsumed task-completion lineage so the next LLM run
diff --git a/packages/heterogeneous-agents/src/types.ts b/packages/heterogeneous-agents/src/types.ts
index 3db0bb6031a..345c766c426 100644
--- a/packages/heterogeneous-agents/src/types.ts
+++ b/packages/heterogeneous-agents/src/types.ts
@@ -330,6 +330,13 @@ export interface HeterogeneousTerminalErrorData {
agentType?: string;
clearEchoedContent?: boolean;
code?: string;
+ /**
+ * Diagnostic context from the CLI's terminal event (subtype, HTTP status,
+ * turn count, session id, …). Persisted verbatim into the error body so the
+ * error card's details pane explains the failure even when the CLI reported
+ * no message text.
+ */
+ details?: Record<string, unknown>;
docsUrl?: string;
error?: string;
installCommands?: readonly string[];
diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts
index 7225d1348f5..17cb8c4db99 100644
--- a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts
@@ -167,12 +167,19 @@ const toHeterogeneousAgentMessageError = (error: unknown, agentType?: string): C
};
}
+ // A plain `{message}` object (adapter wire data / IPC error envelope)
+ // without the session-error marker keys above still carries the only
+ // human-readable reason β€” don't flatten it to the generic fallback.
+ const objectMessage =
+ typeof error === 'object' && error && 'message' in error && typeof error.message === 'string'
+ ? error.message
+ : undefined;
const message =
error instanceof Error
? error.message
: typeof error === 'string'
? error
- : 'Agent execution failed';
+ : (objectMessage ?? 'Agent execution failed');
// Surface the underlying `cause` (e.g. undici's `ENOTFOUND` / `ECONNREFUSED`
// hidden under a generic `TypeError: fetch failed`). The desktop IPC layer