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: map numeric chat errors to tRPC status (#17221)

YuTengjing97f6a0fb101f
diff --git a/AGENTS.md b/AGENTS.md
index f4ed846979a..7ea1c7322f8 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -115,6 +115,7 @@ Open this URL to develop locally against the production backend (app.lobehub.com
bun run check [changed-files...]
```
+- Every bug fix must include a corresponding regression test that fails before the fix and passes after it.
- No selector = **lint + test in a single pass** — run it once; don't fire a separate pass per selector. `--lint` / `--test` / `--type` narrow scope and are composable within one run. Default files = all working-tree changes (staged + unstaged + untracked); explicit paths override.
- `--lint` auto-fixes the given files and prints the applied fixes as a diff, so you can review what changed.
- `--test` auto-discovers the related tests for the given source files and runs them under the nearest owning vitest config (e.g. `packages/database`) — no need to `cd` into packages.
@@ -136,13 +137,3 @@ bun run check [changed-files...]
Before reviewing a PR / diff / branch change, read the **deep-review** skill. Ordinary review requests use its light mode (inline review against the dimension quick checklists); the full multi-subagent deep mode runs only on explicit invocation.
When designing or reviewing user-facing flows (empty/loading/error states, confirmations, async feedback, button hierarchy, lists at scale, pickers), follow LobeHub's design values in [`DESIGN.md`](./DESIGN.md) — Natural / Meaningful / Certainty / Growth (自然 / 意义感 / 确定性 / 成长).
-
-<!-- BEGIN:nextjs-agent-rules -->
-
-# This is NOT the Next.js you know
-
-This version has breaking changes — APIs, conventions, and file structure may all differ from your training data. Read the relevant guide in `node_modules/next/dist/docs/` before writing any code. Heed deprecation notices.
-
-**Keep this block, including in commits.** It is part of the project's agent setup, maintained by `next dev` for every agent that works here. If it appears as an uncommitted change, that is intentional — commit it as-is. Do not remove it to clean up a diff; it will be regenerated.
-
-<!-- END:nextjs-agent-rules -->
diff --git a/apps/server/src/routers/lambda/__tests__/aiChat.test.ts b/apps/server/src/routers/lambda/__tests__/aiChat.test.ts
index 3264e268dbc..40b43845c12 100644
--- a/apps/server/src/routers/lambda/__tests__/aiChat.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/aiChat.test.ts
@@ -1,6 +1,6 @@
// @vitest-environment node
import type { CreateMessageParams } from '@lobechat/types';
-import { AgentRuntimeErrorType, ThreadType } from '@lobechat/types';
+import { AgentRuntimeErrorType, ChatErrorType, ThreadType } from '@lobechat/types';
import { TRPCError } from '@trpc/server';
import { describe, expect, it, vi } from 'vitest';
@@ -1154,6 +1154,169 @@ describe('aiChatRouter', () => {
}
});
+ it('maps numeric chat error types to their tRPC status', async () => {
+ const { initModelRuntimeFromDB } = await import('@/server/modules/ModelRuntime');
+ const accessError = {
+ error: { message: ChatErrorType.Forbidden },
+ errorType: ChatErrorType.Forbidden,
+ message: 'Forbidden',
+ };
+ const mockGenerateObject = vi.fn().mockRejectedValue(accessError);
+
+ vi.mocked(initModelRuntimeFromDB).mockResolvedValue({
+ generateObject: mockGenerateObject,
+ } as any);
+
+ const caller = aiChatRouter.createCaller({ ...mockCtx, serverDB: {} } as any);
+
+ try {
+ await caller.outputJSON({
+ messages: [{ content: 'test', role: 'user' }],
+ model: 'claude-fable-5',
+ provider: 'lobehub',
+ });
+ throw new Error('Expected outputJSON to throw');
+ } catch (error) {
+ expect(error).toBeInstanceOf(TRPCError);
+ expect(error).toMatchObject({
+ cause: accessError,
+ code: 'FORBIDDEN',
+ message: accessError.message,
+ });
+ }
+ });
+
+ it.each([
+ {
+ accessError: {
+ error: { message: 'Nested forbidden message' },
+ errorType: ChatErrorType.Forbidden,
+ },
+ expectedMessage: 'Nested forbidden message',
+ source: 'nested error.message',
+ },
+ {
+ accessError: {
+ error: {},
+ errorMessage: 'Legacy forbidden message',
+ errorType: ChatErrorType.Forbidden,
+ },
+ expectedMessage: 'Legacy forbidden message',
+ source: 'legacy errorMessage',
+ },
+ ])('preserves $source for numeric chat errors', async ({ accessError, expectedMessage }) => {
+ const { initModelRuntimeFromDB } = await import('@/server/modules/ModelRuntime');
+ const mockGenerateObject = vi.fn().mockRejectedValue(accessError);
+
+ vi.mocked(initModelRuntimeFromDB).mockResolvedValue({
+ generateObject: mockGenerateObject,
+ } as any);
+
+ const caller = aiChatRouter.createCaller({ ...mockCtx, serverDB: {} } as any);
+
+ await expect(
+ caller.outputJSON({
+ messages: [{ content: 'test', role: 'user' }],
+ model: 'claude-fable-5',
+ provider: 'lobehub',
+ }),
+ ).rejects.toMatchObject({
+ cause: accessError,
+ code: 'FORBIDDEN',
+ message: expectedMessage,
+ });
+ });
+
+ it.each([
+ { errorType: 400, expectedCode: 'BAD_REQUEST' },
+ { errorType: 418, expectedCode: 'BAD_REQUEST' },
+ { errorType: 599, expectedCode: 'INTERNAL_SERVER_ERROR' },
+ ])(
+ 'maps numeric status $errorType to $expectedCode with a generic message',
+ async ({ errorType, expectedCode }) => {
+ const { initModelRuntimeFromDB } = await import('@/server/modules/ModelRuntime');
+ const accessError = { error: {}, errorType };
+ const mockGenerateObject = vi.fn().mockRejectedValue(accessError);
+
+ vi.mocked(initModelRuntimeFromDB).mockResolvedValue({
+ generateObject: mockGenerateObject,
+ } as any);
+
+ const caller = aiChatRouter.createCaller({ ...mockCtx, serverDB: {} } as any);
+
+ await expect(
+ caller.outputJSON({
+ messages: [{ content: 'test', role: 'user' }],
+ model: 'claude-fable-5',
+ provider: 'lobehub',
+ }),
+ ).rejects.toMatchObject({
+ cause: accessError,
+ code: expectedCode,
+ message: `Request failed (${errorType})`,
+ });
+ },
+ );
+
+ it('does not silence numeric runtime 5xx errors', async () => {
+ const { initModelRuntimeFromDB } = await import('@/server/modules/ModelRuntime');
+ const runtimeError = {
+ error: { message: 'Provider unavailable' },
+ errorType: 503,
+ };
+ const mockGenerateObject = vi.fn().mockRejectedValue(runtimeError);
+
+ vi.mocked(initModelRuntimeFromDB).mockResolvedValue({
+ generateObject: mockGenerateObject,
+ } as any);
+
+ const caller = aiChatRouter.createCaller({ ...mockCtx, serverDB: {} } as any);
+
+ try {
+ await caller.outputJSON({
+ messages: [{ content: 'test', role: 'user' }],
+ model: 'claude-fable-5',
+ provider: 'lobehub',
+ tracing: { scenario: 'input_completion' },
+ });
+ throw new Error('Expected outputJSON to throw');
+ } catch (error) {
+ expect(error).toMatchObject({
+ cause: runtimeError,
+ code: 'SERVICE_UNAVAILABLE',
+ message: runtimeError.error.message,
+ });
+ expect((runtimeError as any).__lobeSilentTRPCErrorLog).toBeUndefined();
+ }
+ });
+
+ it.each([399, 600])('does not map out-of-range numeric error type %i', async (errorType) => {
+ const { initModelRuntimeFromDB } = await import('@/server/modules/ModelRuntime');
+ const runtimeError = { errorType };
+ const mockGenerateObject = vi.fn().mockRejectedValue(runtimeError);
+
+ vi.mocked(initModelRuntimeFromDB).mockResolvedValue({
+ generateObject: mockGenerateObject,
+ } as any);
+
+ const caller = aiChatRouter.createCaller({ ...mockCtx, serverDB: {} } as any);
+
+ try {
+ await caller.outputJSON({
+ messages: [{ content: 'test', role: 'user' }],
+ model: 'claude-fable-5',
+ provider: 'lobehub',
+ tracing: { scenario: 'input_completion' },
+ });
+ throw new Error('Expected outputJSON to throw');
+ } catch (error) {
+ expect(error).toBeInstanceOf(TRPCError);
+ expect(error).toMatchObject({ code: 'INTERNAL_SERVER_ERROR' });
+ expect((error as Error).message).not.toBe(`Request failed (${errorType})`);
+ expect((runtimeError as any).__lobeSilentTRPCErrorLog).toBeUndefined();
+ }
+ });
+
it('maps raw provider 4xx errors to BAD_REQUEST instead of internal errors', async () => {
const { initModelRuntimeFromDB } = await import('@/server/modules/ModelRuntime');
diff --git a/apps/server/src/routers/lambda/aiChat.ts b/apps/server/src/routers/lambda/aiChat.ts
index cd4248e869a..bedafd392b3 100644
--- a/apps/server/src/routers/lambda/aiChat.ts
+++ b/apps/server/src/routers/lambda/aiChat.ts
@@ -5,6 +5,7 @@ import { getErrorCodeSpec } from '@lobechat/model-runtime';
import type { CreateMessageParams, SendMessageServerResponse } from '@lobechat/types';
import { AiSendMessageServerSchema, RequestTrigger, StructureOutputSchema } from '@lobechat/types';
import { createTimingHelpers, createTimingRequestId } from '@lobechat/utils';
+import { pickNonEmptyString, toRecord } from '@lobechat/utils/object';
import { TRPCError } from '@trpc/server';
import { getStatusKeyFromCode } from '@trpc/server/unstable-core-do-not-import';
import debug from 'debug';
@@ -33,21 +34,29 @@ const { createPrefixedTimingContext, logTiming, runTimedStage } = createTimingHe
type TRPCErrorCode = ConstructorParameters<typeof TRPCError>[0]['code'];
type TRPCStatusCode = Parameters<typeof getStatusKeyFromCode>[0];
-const getRuntimeErrorType = (error: unknown): string | undefined => {
+const getRuntimeErrorType = (error: unknown): number | string | undefined => {
if (!error || typeof error !== 'object') return;
const errorType = (error as { errorType?: unknown }).errorType;
- return typeof errorType === 'string' ? errorType : undefined;
+ return typeof errorType === 'number' || typeof errorType === 'string' ? errorType : undefined;
};
const getTRPCErrorCodeFromStatus = (status: number): TRPCErrorCode => {
const code = getStatusKeyFromCode(status as TRPCStatusCode) as TRPCErrorCode;
- if (code !== 'INTERNAL_SERVER_ERROR' || status === 500) return code;
+ if (code !== 'INTERNAL_SERVER_ERROR') return code;
- if (status >= 500) return 'INTERNAL_SERVER_ERROR';
- if (status >= 400) return 'BAD_REQUEST';
+ return status >= 400 && status < 500 ? 'BAD_REQUEST' : 'INTERNAL_SERVER_ERROR';
+};
+
+const getRuntimeErrorMessage = (error: unknown): string | undefined => {
+ const errorRecord = toRecord(error);
+ if (!errorRecord) return;
- return 'INTERNAL_SERVER_ERROR';
+ return (
+ pickNonEmptyString(errorRecord.message) ??
+ pickNonEmptyString(toRecord(errorRecord.error)?.message) ??
+ pickNonEmptyString(errorRecord.errorMessage)
+ );
};
const createRuntimeTRPCError = (
@@ -55,14 +64,22 @@ const createRuntimeTRPCError = (
options?: { silentHandlerLog?: boolean },
): TRPCError | undefined => {
const errorType = getRuntimeErrorType(error);
- const spec = getErrorCodeSpec(errorType);
- if (errorType && spec) {
- if (options?.silentHandlerLog && spec.httpStatus < 500) markSilentTRPCErrorLog(error);
+ const runtimeStatus =
+ typeof errorType === 'number'
+ ? errorType >= 400 && errorType <= 599
+ ? errorType
+ : undefined
+ : getErrorCodeSpec(errorType)?.httpStatus;
+ if (runtimeStatus) {
+ if (options?.silentHandlerLog && runtimeStatus < 500) markSilentTRPCErrorLog(error);
return new TRPCError({
cause: error,
- code: getTRPCErrorCodeFromStatus(spec.httpStatus),
- message: errorType,
+ code: getTRPCErrorCodeFromStatus(runtimeStatus),
+ message:
+ typeof errorType === 'string'
+ ? errorType
+ : (getRuntimeErrorMessage(error) ?? `Request failed (${runtimeStatus})`),
});
}
diff --git a/package.json b/package.json
index fa62e8d31e2..4d4d144633e 100644
--- a/package.json
+++ b/package.json
@@ -302,7 +302,7 @@
"@modelcontextprotocol/sdk": "^1.29.0",
"@napi-rs/canvas": "^0.1.100",
"@neondatabase/serverless": "^1.1.0",
- "@next/third-parties": "^16.3.0-preview.5",
+ "@next/third-parties": "^16.3.0-preview.6",
"@opentelemetry/auto-instrumentations-node": "^0.76.0",
"@opentelemetry/exporter-jaeger": "^2.8.0",
"@opentelemetry/resources": "^2.8.0",
@@ -382,7 +382,7 @@
"model-bank": "workspace:*",
"motion": "^12.42.0",
"nanoid": "^5.1.16",
- "next": "^16.3.0-preview.5",
+ "next": "^16.3.0-preview.6",
"next-mdx-remote": "^6.0.0",
"next-themes": "^0.4.6",
"nextjs-toploader": "^3.9.17",
diff --git a/src/libs/next/config/define-config.test.ts b/src/libs/next/config/define-config.test.ts
index 3630771455c..0bea171f07a 100644
--- a/src/libs/next/config/define-config.test.ts
+++ b/src/libs/next/config/define-config.test.ts
@@ -1,7 +1,14 @@
import { describe, expect, it } from 'vitest';
+import { defineConfig } from './define-config';
import { dockerCanvasTracingIncludes } from './dockerCanvasTracingIncludes';
+describe('defineConfig', () => {
+ it('disables Next.js agent rule injection', () => {
+ expect(defineConfig({}).agentRules).toBe(false);
+ });
+});
+
describe('dockerCanvasTracingIncludes', () => {
it('keeps Docker canvas tracing away from pnpm symlink directories', () => {
expect(dockerCanvasTracingIncludes).toContain('node_modules/@napi-rs/canvas/**/*');
diff --git a/src/libs/next/config/define-config.ts b/src/libs/next/config/define-config.ts
index fd6c401a327..f420130d17f 100644
--- a/src/libs/next/config/define-config.ts
+++ b/src/libs/next/config/define-config.ts
@@ -60,6 +60,8 @@ export function defineConfig(config: CustomNextConfig) {
const nextConfig: NextConfig = {
...(isStandaloneMode ? standaloneConfig : {}),
+ // Stop `next dev` from auto-injecting the nextjs-agent-rules block into AGENTS.md.
+ agentRules: false,
assetPrefix,
compiler: {