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(agent-runtime): keep classified 403 refusals and CLI session limits off the gateway error board (#21614)

Arvin Xu1af9866f05dc
diff --git a/apps/server/src/modules/AgentRuntime/GatewayStreamNotifier.ts b/apps/server/src/modules/AgentRuntime/GatewayStreamNotifier.ts
index ce58e6b768b..1b9d2f42a84 100644
--- a/apps/server/src/modules/AgentRuntime/GatewayStreamNotifier.ts
+++ b/apps/server/src/modules/AgentRuntime/GatewayStreamNotifier.ts
@@ -379,6 +379,7 @@ export class GatewayStreamNotifier implements IStreamEventManager {
// user-side / board-worthy decision lives here, next to the error spec.
...(reason === 'error' && {
recordError: shouldRecordGatewayError({
+ error: finalState?.error,
errorType: rawErrorType,
provider: finalState?.modelRuntimeConfig?.provider,
}),
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/GatewayStreamNotifier.recordError.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/GatewayStreamNotifier.recordError.test.ts
new file mode 100644
index 00000000000..087a03e8352
--- /dev/null
+++ b/apps/server/src/modules/AgentRuntime/__tests__/GatewayStreamNotifier.recordError.test.ts
@@ -0,0 +1,94 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { GatewayStreamNotifier } from '../GatewayStreamNotifier';
+import { createMockInner } from '../testUtils';
+import type { PublishAgentRuntimeEndParams } from '../types';
+
+const mockFetch = vi.fn().mockResolvedValue({ ok: true, text: () => Promise.resolve('') });
+vi.stubGlobal('fetch', mockFetch);
+
+/** Whether the terminal event tells the gateway to file the error on its board. */
+describe('GatewayStreamNotifier recordError', () => {
+ let notifier: GatewayStreamNotifier;
+
+ beforeEach(() => {
+ mockFetch.mockReset().mockResolvedValue({ ok: true, text: () => Promise.resolve('') });
+ notifier = new GatewayStreamNotifier(
+ createMockInner(),
+ 'https://gateway.test.com',
+ 'test-token',
+ );
+ });
+
+ const endEventData = async (
+ params: Omit<PublishAgentRuntimeEndParams, 'operationId' | 'stepIndex'>,
+ ) => {
+ await notifier.publishAgentRuntimeEnd({ operationId: 'op-1', stepIndex: 0, ...params });
+ await new Promise((r) => setTimeout(r, 50));
+ const pushCall = mockFetch.mock.calls.find((c: any[]) => c[0].includes('push-event'));
+ return JSON.parse(pushCall![1].body).event.data;
+ };
+
+ it('keeps a user-side error off the gateway board', async () => {
+ const data = await endEventData({
+ finalState: {
+ error: { message: 'insufficient quota', type: 'InsufficientQuota' },
+ modelRuntimeConfig: { model: 'gpt-5.6-sol', provider: 'openai' },
+ },
+ reason: 'error',
+ });
+
+ expect(data.recordError).toBe(false);
+ });
+
+ it('files a provider rate limit on our own provider', async () => {
+ const data = await endEventData({
+ finalState: {
+ error: { message: '429', type: 'RateLimitExceeded' },
+ modelRuntimeConfig: { model: 'claude-opus-5', provider: 'lobehub' },
+ },
+ reason: 'error',
+ });
+
+ expect(data.recordError).toBe(true);
+ });
+
+ it('classifies by the configured provider, not the upstream named in the error body', async () => {
+ // On our provider the normalized error names the upstream the router
+ // reached, never `lobehub` β€” trusting it would hide our own rate limit.
+ const data = await endEventData({
+ finalState: {
+ error: { body: { provider: 'azure' }, message: '429', type: 'RateLimitExceeded' },
+ modelRuntimeConfig: { model: 'gpt-5.6-sol', provider: 'lobehub' },
+ },
+ reason: 'error',
+ });
+
+ expect(data.recordError).toBe(true);
+ });
+
+ it('keeps an onboarding-gate refusal off the board', async () => {
+ // The numeric Forbidden type has no spec; the normalizer classified it.
+ const data = await endEventData({
+ finalState: {
+ error: {
+ attribution: 'user',
+ body: { reason: 'not_onboarded' },
+ countAsFailure: false,
+ message: 'Request blocked.',
+ type: 403,
+ },
+ modelRuntimeConfig: { model: 'deepseek-flash', provider: 'lobehub' },
+ },
+ reason: 'error',
+ });
+
+ expect(data.recordError).toBe(false);
+ });
+
+ it('omits the flag on a non-error end', async () => {
+ const data = await endEventData({ finalState: {}, reason: 'completed' });
+
+ expect(data).not.toHaveProperty('recordError');
+ });
+});
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/GatewayStreamNotifier.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/GatewayStreamNotifier.test.ts
index ff80fd91177..9f2c9b7f572 100644
--- a/apps/server/src/modules/AgentRuntime/__tests__/GatewayStreamNotifier.test.ts
+++ b/apps/server/src/modules/AgentRuntime/__tests__/GatewayStreamNotifier.test.ts
@@ -4,7 +4,6 @@ import { GatewayStreamNotifier } from '../GatewayStreamNotifier';
import { FULL_STRIP_REDACTION, sanitizeGatewayEventData } from '../gatewayVisitorRedaction';
import type { StreamChunkData } from '../StreamEventManager';
import { createMockInner } from '../testUtils';
-import type { PublishAgentRuntimeEndParams } from '../types';
// Mock global fetch
const mockFetch = vi.fn().mockResolvedValue({ ok: true, text: () => Promise.resolve('') });
@@ -641,61 +640,6 @@ describe('GatewayStreamNotifier', () => {
expect(body.event.data.reasonDetail).toBe('Custom detail');
});
- describe('recordError', () => {
- const endEventData = async (
- params: Omit<PublishAgentRuntimeEndParams, 'operationId' | 'stepIndex'>,
- ) => {
- await notifier.publishAgentRuntimeEnd({ operationId: 'op-1', stepIndex: 0, ...params });
- await new Promise((r) => setTimeout(r, 50));
- const pushCall = mockFetch.mock.calls.find((c: any[]) => c[0].includes('push-event'));
- return JSON.parse(pushCall![1].body).event.data;
- };
-
- it('keeps a user-side error off the gateway board', async () => {
- const data = await endEventData({
- finalState: {
- error: { message: 'insufficient quota', type: 'InsufficientQuota' },
- modelRuntimeConfig: { model: 'gpt-5.6-sol', provider: 'openai' },
- },
- reason: 'error',
- });
-
- expect(data.recordError).toBe(false);
- });
-
- it('files a provider rate limit on our own provider', async () => {
- const data = await endEventData({
- finalState: {
- error: { message: '429', type: 'RateLimitExceeded' },
- modelRuntimeConfig: { model: 'claude-opus-5', provider: 'lobehub' },
- },
- reason: 'error',
- });
-
- expect(data.recordError).toBe(true);
- });
-
- it('classifies by the configured provider, not the upstream named in the error body', async () => {
- // On our provider the normalized error names the upstream the router
- // reached, never `lobehub` β€” trusting it would hide our own rate limit.
- const data = await endEventData({
- finalState: {
- error: { body: { provider: 'azure' }, message: '429', type: 'RateLimitExceeded' },
- modelRuntimeConfig: { model: 'gpt-5.6-sol', provider: 'lobehub' },
- },
- reason: 'error',
- });
-
- expect(data.recordError).toBe(true);
- });
-
- it('omits the flag on a non-error end', async () => {
- const data = await endEventData({ finalState: {}, reason: 'completed' });
-
- expect(data).not.toHaveProperty('recordError');
- });
- });
-
it('includes errorType from finalState.error.type', async () => {
const finalState = {
error: { message: 'Budget exceeded', type: 'InsufficientBudgetForModel' },
diff --git a/apps/server/src/modules/AgentRuntime/gatewayErrorRecord.test.ts b/apps/server/src/modules/AgentRuntime/gatewayErrorRecord.test.ts
index fb0998ec12e..310c68d8cf1 100644
--- a/apps/server/src/modules/AgentRuntime/gatewayErrorRecord.test.ts
+++ b/apps/server/src/modules/AgentRuntime/gatewayErrorRecord.test.ts
@@ -32,4 +32,55 @@ describe('shouldRecordGatewayError', () => {
] as const)('%s β†’ %s', (_label, errorType, provider, expected) => {
expect(shouldRecordGatewayError({ errorType, provider })).toBe(expected);
});
+
+ describe('normalized error classification', () => {
+ // A platform admission refusal keeps the numeric `Forbidden` type, which
+ // has no spec; the normalizer classifies it on the error itself.
+ const forbidden = '403';
+
+ it('keeps a user-side refusal without a spec off the board', () => {
+ expect(
+ shouldRecordGatewayError({
+ error: { attribution: 'user', countAsFailure: false },
+ errorType: forbidden,
+ provider: BRANDING_PROVIDER,
+ }),
+ ).toBe(false);
+ });
+
+ it('files an unclassified refusal', () => {
+ expect(shouldRecordGatewayError({ error: {}, errorType: forbidden })).toBe(true);
+ });
+
+ it('files a refusal the normalizer counts as a failure', () => {
+ expect(
+ shouldRecordGatewayError({
+ error: { attribution: 'harness', countAsFailure: true },
+ errorType: forbidden,
+ }),
+ ).toBe(true);
+ });
+
+ it('overrides the generic type a heterogeneous CLI failure keeps', () => {
+ // A Claude Code session limit stays `AgentRuntimeError`, whose spec
+ // counts as a failure; the CLI classification says it is the user's.
+ expect(
+ shouldRecordGatewayError({
+ error: { attribution: 'user', countAsFailure: false },
+ errorType: AgentRuntimeErrorType.AgentRuntimeError,
+ provider: 'claude-code',
+ }),
+ ).toBe(false);
+ });
+
+ it('keeps a CLI capacity error off the board for the CLI provider', () => {
+ expect(
+ shouldRecordGatewayError({
+ error: { attribution: 'provider', countAsFailure: false },
+ errorType: AgentRuntimeErrorType.AgentRuntimeError,
+ provider: 'codex',
+ }),
+ ).toBe(false);
+ });
+ });
});
diff --git a/apps/server/src/modules/AgentRuntime/gatewayErrorRecord.ts b/apps/server/src/modules/AgentRuntime/gatewayErrorRecord.ts
index 8d59bc7ecce..10612716a14 100644
--- a/apps/server/src/modules/AgentRuntime/gatewayErrorRecord.ts
+++ b/apps/server/src/modules/AgentRuntime/gatewayErrorRecord.ts
@@ -1,6 +1,6 @@
import { BRANDING_PROVIDER } from '@lobechat/business-const';
import { getErrorCodeSpec } from '@lobechat/model-runtime';
-import { AgentRuntimeErrorType } from '@lobechat/types';
+import { AgentRuntimeErrorType, type ChatMessageError } from '@lobechat/types';
/**
* User-attributed codes that still point at something the harness could have
@@ -31,17 +31,31 @@ const HARNESS_SIGNAL_ERROR_TYPES = new Set<string>([
* `provider` is the operation's configured provider β€” the one the board shows.
* The normalized error's `body.provider` is not a substitute: for our provider it
* names the upstream the router reached (`azure`, `google`, …), never ours.
+ *
+ * `error` is the normalized error on the final state. When it carries a
+ * classification, that classification decides; the spec of `errorType` is the
+ * fallback for errors that were never normalized. The normalizer can know more
+ * than the type: a platform admission refusal keeps the numeric `Forbidden` type
+ * (the chat renderer picks its card from it), and a heterogeneous CLI failure
+ * keeps the generic `AgentRuntimeError` type, but both are classified on the
+ * error itself. Reading the type alone filed every plan-gate refusal and every
+ * Claude Code / Codex session limit as an unknown failure.
*/
export const shouldRecordGatewayError = ({
+ error,
errorType,
provider,
}: {
+ error?: Pick<ChatMessageError, 'attribution' | 'countAsFailure'>;
errorType?: string;
provider?: string;
}): boolean => {
if (!errorType || HARNESS_SIGNAL_ERROR_TYPES.has(errorType)) return true;
- const spec = getErrorCodeSpec(errorType);
+ const spec =
+ typeof error?.countAsFailure === 'boolean' && error.attribution
+ ? { attribution: error.attribution, countAsFailure: error.countAsFailure }
+ : getErrorCodeSpec(errorType);
if (!spec || spec.countAsFailure) return true;
switch (spec.attribution) {
diff --git a/apps/server/src/services/heterogeneousAgent/__tests__/finishErrorBoard.test.ts b/apps/server/src/services/heterogeneousAgent/__tests__/finishErrorBoard.test.ts
new file mode 100644
index 00000000000..97bd389c573
--- /dev/null
+++ b/apps/server/src/services/heterogeneousAgent/__tests__/finishErrorBoard.test.ts
@@ -0,0 +1,90 @@
+// @vitest-environment node
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { CompletionLifecycle } from '@/server/services/agentRuntime/CompletionLifecycle';
+
+import { HeterogeneousAgentService } from '..';
+
+/**
+ * The gateway files an errored run on its error board from the terminal
+ * `agent_runtime_end` alone, so heteroFinish has to say what failed and whether
+ * it belongs on the board.
+ */
+const finish = async (
+ params: Pick<Parameters<HeterogeneousAgentService['heteroFinish']>[0], 'error' | 'result'>,
+) => {
+ vi.spyOn(CompletionLifecycle.prototype, 'completeOperation').mockResolvedValue(undefined as any);
+ const publishStreamEvent = vi.fn(async () => 'ok');
+ const service = new HeterogeneousAgentService({} as any, 'user-1', {
+ agentOperationModel: { findById: vi.fn(async () => ({ metadata: {} })) } as any,
+ persistenceHandler: { finish: vi.fn(async () => undefined) } as any,
+ snapshotStore: null,
+ streamEventManager: { publishStreamEvent } as any,
+ topicModel: {
+ settleRunningOperation: vi.fn(async () => ({ status: 'settled' })),
+ updateMetadata: vi.fn(async () => undefined),
+ } as any,
+ workspaceId: 'ws-1',
+ });
+
+ await service.heteroFinish({
+ agentType: 'claude-code',
+ operationId: 'op-1',
+ topicId: 'tpc-1',
+ ...params,
+ });
+
+ const [, event] = publishStreamEvent.mock.calls.at(-1) as unknown as [string, any];
+ expect(event.type).toBe('agent_runtime_end');
+ return event.data;
+};
+
+describe('HeterogeneousAgentService.heteroFinish β€” gateway error board', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it("keeps the user's own CLI session limit off the board", async () => {
+ const data = await finish({
+ error: {
+ body: {
+ code: 'rate_limit',
+ error: "You've hit your session limit Β· resets 2:00am (Asia/Shanghai)",
+ },
+ message: "You've hit your session limit Β· resets 2:00am (Asia/Shanghai)",
+ type: 'AgentRuntimeError',
+ },
+ result: 'error',
+ });
+
+ expect(data).toMatchObject({
+ errorType: 'AgentRuntimeError',
+ reason: 'error',
+ reasonDetail: "You've hit your session limit Β· resets 2:00am (Asia/Shanghai)",
+ recordError: false,
+ });
+ });
+
+ it('files an unclassified CLI failure with its message', async () => {
+ const data = await finish({
+ error: { message: 'thread-store conflict', type: 'AgentRuntimeError' },
+ result: 'error',
+ });
+
+ expect(data).toMatchObject({
+ errorType: 'AgentRuntimeError',
+ reasonDetail: 'thread-store conflict',
+ recordError: true,
+ });
+ });
+
+ it('adds no board fields to a successful run', async () => {
+ const data = await finish({ result: 'success' });
+
+ expect(data).not.toHaveProperty('recordError');
+ expect(data).not.toHaveProperty('errorType');
+ });
+});
diff --git a/apps/server/src/services/heterogeneousAgent/index.ts b/apps/server/src/services/heterogeneousAgent/index.ts
index efa5f8ea514..a1b5a70debd 100644
--- a/apps/server/src/services/heterogeneousAgent/index.ts
+++ b/apps/server/src/services/heterogeneousAgent/index.ts
@@ -10,7 +10,7 @@ import {
classifyHeteroProcessFailure,
isHeteroStatusGuideErrorData,
} from '@lobechat/heterogeneous-agents/processFailure';
-import { ThreadStatus } from '@lobechat/types';
+import { type ChatMessageError, ThreadStatus } from '@lobechat/types';
import debug from 'debug';
import {
@@ -22,6 +22,7 @@ import { MessageModel } from '@/database/models/message';
import { ThreadModel } from '@/database/models/thread';
import { TopicModel } from '@/database/models/topic';
import { createStreamEventManager } from '@/server/modules/AgentRuntime/factory';
+import { shouldRecordGatewayError } from '@/server/modules/AgentRuntime/gatewayErrorRecord';
import { type IStreamEventManager } from '@/server/modules/AgentRuntime/types';
import { CompletionLifecycle } from '@/server/services/agentRuntime/CompletionLifecycle';
import type { SerializedHook } from '@/server/services/agentRuntime/hooks/types';
@@ -489,6 +490,27 @@ export class HeterogeneousAgentService {
}
}
+ // The gateway files an errored run on its error board from this event alone, so
+ // it carries the same `errorType` / `reasonDetail` / `recordError` contract as
+ // the LLM runtime's end event. Without them every CLI failure, including a
+ // user's own Claude Code / Codex session limit, was filed as an empty row.
+ const endData = {
+ agentType,
+ error,
+ operationId,
+ reason: result,
+ sessionId,
+ ...(result === 'error' && {
+ errorType: error?.type,
+ reasonDetail: error?.message,
+ recordError: shouldRecordGatewayError({
+ error: error as Pick<ChatMessageError, 'attribution' | 'countAsFailure'> | undefined,
+ errorType: error?.type,
+ provider: agentType,
+ }),
+ }),
+ };
+
if (staleActiveOperationId) {
log(
'heteroFinish: settle stale finish topic=%s op=%s; current operation is %s',
@@ -509,13 +531,7 @@ export class HeterogeneousAgentService {
log('heteroFinish: failed to settle stale operation row (non-fatal): %O', err);
}
await this.streamEventManager.publishStreamEvent(operationId, {
- data: {
- agentType,
- error,
- operationId,
- reason: result,
- sessionId,
- },
+ data: endData,
stepIndex: 0,
type: 'agent_runtime_end',
});
@@ -542,13 +558,7 @@ export class HeterogeneousAgentService {
// if the CLI stream missed it. A stale callback that belongs to neither the
// root operation nor one of its children returns above.
await this.streamEventManager.publishStreamEvent(operationId, {
- data: {
- agentType,
- error,
- operationId,
- reason: result,
- sessionId,
- },
+ data: endData,
stepIndex: 0,
type: 'agent_runtime_end',
});