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.

πŸ› fix(hetero): keep status-guide error body through the remote CC finish leg (#17283)

Arvin Xu2b3da0097f2a
diff --git a/apps/cli/src/commands/hetero.test.ts b/apps/cli/src/commands/hetero.test.ts
index 62596faccb4..1ecc81a3e6f 100644
--- a/apps/cli/src/commands/hetero.test.ts
+++ b/apps/cli/src/commands/hetero.test.ts
@@ -1024,6 +1024,66 @@ describe('hetero exec command', () => {
});
});
+ it('forwards the adapter-classified status-guide error as the finish error body', async () => {
+ // The adapter classifies overloaded / rate-limit terminal errors into a
+ // structured payload carrying `agentType` + `code` β€” the pair the client's
+ // status-guide UI gates on. The finish leg must forward it verbatim instead
+ // of flattening to `{ message }`, otherwise flushFinalState overwrites the
+ // in-stream persisted error and the client falls back to the generic alert.
+ const overloadedMessage =
+ 'API Error: 529 Overloaded. This is a server-side issue, usually temporary.';
+ mockSpawnAgent.mockReturnValue(
+ createFakeHandle({
+ events: [
+ {
+ data: {
+ agentType: 'claude-code',
+ clearEchoedContent: true,
+ code: 'overloaded',
+ error: overloadedMessage,
+ message: overloadedMessage,
+ stderr: overloadedMessage,
+ },
+ operationId: 'op-err-guide',
+ stepIndex: 0,
+ timestamp: 1,
+ type: 'error',
+ },
+ ],
+ exitCode: 0,
+ }),
+ );
+
+ await runCmd([
+ 'hetero',
+ 'exec',
+ '--type',
+ 'claude-code',
+ '--prompt',
+ 'hi',
+ '--topic',
+ 'topic-1',
+ '--operation-id',
+ 'op-err-guide',
+ '--render',
+ 'none',
+ ]);
+
+ expect(mockHeteroFinishMutate).toHaveBeenCalledTimes(1);
+ expect(mockHeteroFinishMutate.mock.calls[0][0]).toMatchObject({
+ error: {
+ body: {
+ agentType: 'claude-code',
+ code: 'overloaded',
+ message: overloadedMessage,
+ },
+ message: overloadedMessage,
+ type: 'AgentRuntimeError',
+ },
+ result: 'error',
+ });
+ });
+
it('resets the per-message text accumulator at message boundaries (no cross-message duplication)', async () => {
// The `replace` snapshot accumulator must not span
// message boundaries. Two assistant messages separated by a
diff --git a/apps/cli/src/commands/hetero.ts b/apps/cli/src/commands/hetero.ts
index 25aedce4bae..1ac39d9ac22 100644
--- a/apps/cli/src/commands/hetero.ts
+++ b/apps/cli/src/commands/hetero.ts
@@ -18,6 +18,7 @@ import type {
import {
classifyHeteroProcessFailure,
createFileStoreImageUploader,
+ isHeteroStatusGuideErrorData,
spawnAgent,
} from '@lobechat/heterogeneous-agents/spawn';
import type { Command } from 'commander';
@@ -645,6 +646,12 @@ const exec = async (options: ExecOptions): Promise<void> => {
* and still exit 0, so the exit code alone is not enough)
* terminalErrorMessage β€” the message from that terminal `error` event, used
* as the task-level error detail in the finish payload
+ * terminalErrorData β€” the full structured payload of that terminal `error`
+ * event when the adapter already classified it into a
+ * status-guide error (overloaded / rate_limit / …); the
+ * finish leg forwards it verbatim as the error `body` so
+ * the client renders the dedicated guide instead of the
+ * generic error card
* stderrContent β€” accumulated stderr (only when interceptResumeErrors=true)
*/
const runOneAgent = async (
@@ -659,6 +666,7 @@ const exec = async (options: ExecOptions): Promise<void> => {
sessionId: string | undefined;
signal: NodeJS.Signals | null;
stderrContent: string;
+ terminalErrorData: Record<string, unknown> | undefined;
terminalErrorMessage: string | undefined;
}> => {
// One raw-dump file pair per spawn attempt (the resume retry is a second
@@ -750,6 +758,7 @@ const exec = async (options: ExecOptions): Promise<void> => {
let resumeNotFound = false;
let sawTerminalError = false;
let terminalErrorMessage: string | undefined;
+ let terminalErrorData: Record<string, unknown> | undefined;
const ingestError = false;
try {
for await (const event of handle.events) {
@@ -773,6 +782,11 @@ const exec = async (options: ExecOptions): Promise<void> => {
sawTerminalError = true;
const data = event.data as Record<string, unknown> | undefined;
terminalErrorMessage = String(data?.message ?? data?.error ?? '') || undefined;
+ // Keep the adapter's already-classified status-guide payload
+ // (overloaded / rate_limit carry `agentType` + `code`) so the finish
+ // leg doesn't flatten it back to a bare string β€” the process-failure
+ // classifier there only knows cli_not_found / auth_required.
+ terminalErrorData = isHeteroStatusGuideErrorData(data) ? data : undefined;
}
if (emitJsonl) process.stdout.write(`${JSON.stringify(event)}\n`);
serverIngester?.push(event);
@@ -831,6 +845,7 @@ const exec = async (options: ExecOptions): Promise<void> => {
sessionId: handle.sessionId,
signal,
stderrContent,
+ terminalErrorData,
terminalErrorMessage,
};
};
@@ -929,10 +944,22 @@ const exec = async (options: ExecOptions): Promise<void> => {
// payload small.
const stderrTail = result.stderrContent.trim();
const errorDetail = result.terminalErrorMessage || stderrTail;
- const finishError =
- !exitedClean && errorDetail
- ? buildFinishError(errorDetail.slice(-1024), 'AgentRuntimeError')
- : undefined;
+ // The adapter's in-stream classification (overloaded / rate_limit) already
+ // carries the structured status-guide body β€” forward it verbatim instead of
+ // re-deriving from the flattened message via the process-only classifier,
+ // which would drop `agentType`/`code` and demote the client UI to the
+ // generic error card.
+ const finishError = exitedClean
+ ? undefined
+ : result.terminalErrorData
+ ? {
+ body: { ...result.terminalErrorData },
+ message: String(result.terminalErrorData.message ?? errorDetail ?? ''),
+ type: 'AgentRuntimeError',
+ }
+ : errorDetail
+ ? buildFinishError(errorDetail.slice(-1024), 'AgentRuntimeError')
+ : undefined;
try {
await sink.finish({
diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts
index 5e5094b0c41..ac1c514d91e 100644
--- a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts
+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler.ts
@@ -11,6 +11,7 @@ import type {
} from '@lobechat/heterogeneous-agents';
import {
createMainAgentRunState,
+ isHeteroStatusGuideErrorData,
reduceMainAgent,
rehydrateSubagentRunsState,
} from '@lobechat/heterogeneous-agents';
@@ -1013,7 +1014,18 @@ export class HeterogeneousPersistenceHandler {
// terminal flush and the in-stream write produce one classified error shape.
// A structured `body` (status-guide error: agentType + code) passes
// through untouched β€” the client's guide UI gates on it.
- updateValue.error = formatErrorForState(error);
+ //
+ // Never DOWNGRADE, though: the in-stream `setError` path may already have
+ // persisted the adapter's classified status-guide error on this assistant,
+ // while older CLIs flatten the finish error to a bare `{ message }`.
+ // Overwriting would demote the client from the dedicated guide card to
+ // the generic error alert β€” keep the richer persisted error instead.
+ const overwritesGuideError =
+ !isHeteroStatusGuideErrorData(error.body) &&
+ isHeteroStatusGuideErrorData(
+ (await this.deps.messageModel.findById(state.main.currentAssistantId))?.error?.body,
+ );
+ if (!overwritesGuideError) updateValue.error = formatErrorForState(error);
}
if (Object.keys(updateValue).length > 0) {
diff --git a/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.test.ts b/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.test.ts
index c6d07acfb27..ffd050cc385 100644
--- a/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.test.ts
+++ b/apps/server/src/services/heterogeneousAgent/__tests__/HeterogeneousPersistenceHandler.test.ts
@@ -1289,6 +1289,47 @@ describe('HeterogeneousPersistenceHandler', () => {
expect(asst.error.message).toContain('was not found');
});
+ it('finish() must not downgrade an in-stream status-guide error with a flat message', async () => {
+ // Remote CC relays an API failure (529 overloaded / rate limit) as an
+ // in-stream `error` event whose data the adapter already classified into
+ // the structured status-guide shape (`agentType` + `code`). Older CLIs
+ // then send a finish error flattened to a bare `{ message }` β€” writing
+ // that over the persisted structured error would demote the client from
+ // the dedicated guide card to the generic error alert.
+ const h = createHarness({
+ assistantMessageId: 'asst-1',
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ const overloadedMessage = 'API Error: 529 Overloaded. This is a server-side issue.';
+ await h.handler.ingest({
+ events: [
+ buildEvent('error', 0, {
+ agentType: 'claude-code',
+ code: 'overloaded',
+ error: overloadedMessage,
+ message: overloadedMessage,
+ stderr: overloadedMessage,
+ }),
+ ],
+ operationId: 'op-1',
+ topicId: 'topic-1',
+ });
+
+ await h.handler.finish({
+ error: { message: overloadedMessage, type: 'AgentRuntimeError' },
+ operationId: 'op-1',
+ result: 'error',
+ });
+
+ const asst = h.messages.get('asst-1')!;
+ expect(asst.error.body).toMatchObject({
+ agentType: 'claude-code',
+ code: 'overloaded',
+ });
+ });
+
it('finish() with NO prior ingest bootstraps state and writes the error (spawn-fail path)', async () => {
// The real process-level failure shape: spawn ENOENT produces ZERO
// stream events, so no ingest ever created an OperationState. finish()
diff --git a/packages/heterogeneous-agents/src/index.ts b/packages/heterogeneous-agents/src/index.ts
index 2d585788c73..e679975a47a 100644
--- a/packages/heterogeneous-agents/src/index.ts
+++ b/packages/heterogeneous-agents/src/index.ts
@@ -26,6 +26,7 @@ export type {
} from './mainAgentCoordinator';
export { createMainAgentRunState, reduceMainAgent } from './mainAgentCoordinator';
export { createAdapter, listAgentTypes } from './registry';
+export { isHeteroStatusGuideErrorData } from './spawn/classifyProcessFailure';
export type {
CreateMessageIntent,
CreateThreadIntent,
diff --git a/packages/heterogeneous-agents/src/spawn/classifyProcessFailure.test.ts b/packages/heterogeneous-agents/src/spawn/classifyProcessFailure.test.ts
index fccd9f6ebb8..97a552b1ca9 100644
--- a/packages/heterogeneous-agents/src/spawn/classifyProcessFailure.test.ts
+++ b/packages/heterogeneous-agents/src/spawn/classifyProcessFailure.test.ts
@@ -1,6 +1,45 @@
import { describe, expect, it } from 'vitest';
-import { classifyHeteroProcessFailure } from './classifyProcessFailure';
+import {
+ classifyHeteroProcessFailure,
+ isHeteroStatusGuideErrorData,
+} from './classifyProcessFailure';
+
+describe('isHeteroStatusGuideErrorData', () => {
+ it('accepts an adapter-classified terminal error carrying agentType + code', () => {
+ expect(
+ isHeteroStatusGuideErrorData({
+ agentType: 'claude-code',
+ code: 'overloaded',
+ message: 'API Error: 529 Overloaded',
+ }),
+ ).toBe(true);
+ expect(
+ isHeteroStatusGuideErrorData({
+ agentType: 'codex',
+ code: 'rate_limit',
+ message: 'usage limit reached',
+ }),
+ ).toBe(true);
+ });
+
+ it('rejects payloads missing the agentType/code pair or outside the guide sets', () => {
+ expect(isHeteroStatusGuideErrorData(undefined)).toBe(false);
+ expect(isHeteroStatusGuideErrorData('API Error: 529 Overloaded')).toBe(false);
+ expect(isHeteroStatusGuideErrorData({ message: 'API Error: 529 Overloaded' })).toBe(false);
+ expect(isHeteroStatusGuideErrorData({ agentType: 'claude-code', message: 'boom' })).toBe(false);
+ expect(
+ isHeteroStatusGuideErrorData({ agentType: 'kimi-cli', code: 'overloaded', message: 'x' }),
+ ).toBe(false);
+ expect(
+ isHeteroStatusGuideErrorData({
+ agentType: 'claude-code',
+ code: 'resume_cwd_mismatch',
+ message: 'x',
+ }),
+ ).toBe(false);
+ });
+});
describe('classifyHeteroProcessFailure', () => {
it('classifies a raw spawn ErrnoException code as cli_not_found', () => {
diff --git a/packages/heterogeneous-agents/src/spawn/classifyProcessFailure.ts b/packages/heterogeneous-agents/src/spawn/classifyProcessFailure.ts
index 53f2371b435..4cc45809a81 100644
--- a/packages/heterogeneous-agents/src/spawn/classifyProcessFailure.ts
+++ b/packages/heterogeneous-agents/src/spawn/classifyProcessFailure.ts
@@ -53,6 +53,40 @@ const AUTH_REQUIRED_MESSAGES: Record<string, string> = {
'Codex could not authenticate on the machine running this agent. Sign in again or refresh its credentials, then retry.',
};
+/**
+ * Codes/agent types the client renders the dedicated status-guide card for.
+ * Must stay in sync with `HETEROGENEOUS_AGENT_STATUS_GUIDE_ERROR_CODES` in
+ * `src/features/Conversation/Error/heterogeneous.ts` β€” that predicate gates the
+ * guide UI on the same `agentType` + `code` pair.
+ */
+const STATUS_GUIDE_ERROR_CODES = new Set([
+ 'auth_required',
+ 'cli_not_found',
+ 'overloaded',
+ 'rate_limit',
+]);
+const STATUS_GUIDE_AGENT_TYPES = new Set(['amp', 'claude-code', 'codex']);
+
+/**
+ * Whether a terminal error payload (an adapter's in-stream `error` event data,
+ * or a persisted `ChatMessageError.body`) is a structured status-guide error β€”
+ * i.e. carries the `agentType` + `code` pair the client's guide UI gates on.
+ */
+export const isHeteroStatusGuideErrorData = (
+ value: unknown,
+): value is HeterogeneousTerminalErrorData & { agentType: string; code: string } => {
+ if (!value || typeof value !== 'object') return false;
+
+ const { agentType, code } = value as HeterogeneousTerminalErrorData;
+
+ return (
+ typeof agentType === 'string' &&
+ STATUS_GUIDE_AGENT_TYPES.has(agentType) &&
+ typeof code === 'string' &&
+ STATUS_GUIDE_ERROR_CODES.has(code)
+ );
+};
+
export interface ClassifyHeteroProcessFailureParams {
/** Adapter type key β€” only `claude-code` / `codex` have a status guide. */
agentType: string;
diff --git a/packages/heterogeneous-agents/src/spawn/index.ts b/packages/heterogeneous-agents/src/spawn/index.ts
index 70a42227b28..182010eaf82 100644
--- a/packages/heterogeneous-agents/src/spawn/index.ts
+++ b/packages/heterogeneous-agents/src/spawn/index.ts
@@ -21,6 +21,7 @@ export {
export {
classifyHeteroProcessFailure,
type ClassifyHeteroProcessFailureParams,
+ isHeteroStatusGuideErrorData,
} from './classifyProcessFailure';
export {
buildClaudeSdkUserMessageFromStreamJson,