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(tool-execution): surface gateway rejection reason in analyzeMedia errors (#20590)

Arvin Xuba3f823628ce
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/lobeAgent.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/lobeAgent.test.ts
index c326c2abbec..5064206e1dd 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/lobeAgent.test.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/lobeAgent.test.ts
@@ -239,6 +239,88 @@ describe('lobeAgentRuntime', () => {
expect(result.content).toMatch(/own API key/i);
});
+ it('should surface the gateway rejection reason instead of a bare blocked message', async () => {
+ mockChat.mockRejectedValueOnce({
+ _responseBody: { provider: 'lobehub', reason: 'not_onboarded' },
+ error: { message: 403 },
+ errorType: 403,
+ message: 'Request blocked.',
+ });
+ const runtime = lobeAgentRuntime.factory(baseContext);
+
+ const result = await runtime.analyzeMedia({
+ question: 'what is this?',
+ urls: ['https://example.com/image.png'],
+ });
+
+ expect(result.success).toBe(false);
+ expect(result.error).toMatchObject({ code: 'GATEWAY_NOT_ONBOARDED' });
+ expect(result.content).toContain('platform model gateway');
+ expect(result.content).toContain('HTTP 403');
+ expect(result.content).toContain('provider: lobehub');
+ expect(result.content).toContain('not_onboarded');
+ expect(result.content).toMatch(/not a content-policy verdict/i);
+ });
+
+ it('should still rethrow unexpected non-gateway chat failures', async () => {
+ mockChat.mockRejectedValueOnce(new Error('socket hang up'));
+ const runtime = lobeAgentRuntime.factory(baseContext);
+
+ await expect(
+ runtime.analyzeMedia({
+ question: 'what is this?',
+ urls: ['https://example.com/image.png'],
+ }),
+ ).rejects.toThrow('socket hang up');
+ });
+
+ it('should rethrow ordinary structured HTTP errors without gateway response body', async () => {
+ mockChat.mockRejectedValueOnce({ errorType: 429, message: 'Rate limited' });
+ const runtime = lobeAgentRuntime.factory(baseContext);
+
+ await expect(
+ runtime.analyzeMedia({
+ question: 'what is this?',
+ urls: ['https://example.com/image.png'],
+ }),
+ ).rejects.toMatchObject({ errorType: 429, message: 'Rate limited' });
+ });
+
+ it('should rethrow a provider-only response body β€” provider alone is not a gateway marker', async () => {
+ // `normalizeChatMessageError` propagates `provider` into every error body as
+ // display metadata, so a provider-only `_responseBody` (e.g. a 429 rate
+ // limit tagged with the relay provider) must keep the rethrow behavior.
+ mockChat.mockRejectedValueOnce({
+ _responseBody: { provider: 'lobehub' },
+ errorType: 429,
+ message: 'Rate limited',
+ });
+ const runtime = lobeAgentRuntime.factory(baseContext);
+
+ await expect(
+ runtime.analyzeMedia({
+ question: 'what is this?',
+ urls: ['https://example.com/image.png'],
+ }),
+ ).rejects.toMatchObject({ errorType: 429, message: 'Rate limited' });
+ });
+
+ it('should classify a gateway rejection from the response body alone (no message needed)', async () => {
+ mockChat.mockRejectedValueOnce({
+ _responseBody: { provider: 'lobehub', reason: 'quota_exceeded' },
+ errorType: 402,
+ });
+ const runtime = lobeAgentRuntime.factory(baseContext);
+
+ const result = await runtime.analyzeMedia({
+ question: 'what is this?',
+ urls: ['https://example.com/image.png'],
+ });
+
+ expect(result.success).toBe(false);
+ expect(result.error).toMatchObject({ code: 'GATEWAY_QUOTA_EXCEEDED' });
+ });
+
it('should reject loopback media urls before calling the multimodal model', async () => {
const runtime = lobeAgentRuntime.factory(baseContext);
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/lobeAgent.ts b/apps/server/src/services/toolExecution/serverRuntimes/lobeAgent.ts
index 2bef60b1300..7eeb3184458 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/lobeAgent.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/lobeAgent.ts
@@ -103,6 +103,54 @@ const getCreditErrorType = (error: unknown): string | undefined => {
return typeof errorType === 'string' && CREDIT_ERROR_TYPES.has(errorType) ? errorType : undefined;
};
+/**
+ * Structured rejection from the model gateway (e.g. `{ errorType: 403,
+ * message: "Request blocked.", _responseBody: { provider, reason:
+ * "not_onboarded" } }`). The raw message alone gives the agent nothing to act
+ * on β€” the gateway's `reason` is the only actionable signal, and rethrowing
+ * collapses the whole payload into that bare string before the tool result is
+ * built. Surface it instead of letting the failure degrade to "Request
+ * blocked." with no code, no cause, and no recovery path.
+ */
+const getGatewayRejection = (error: unknown): { content: string; code: string } | undefined => {
+ if (!error || typeof error !== 'object') return;
+
+ const raw = error as {
+ _responseBody?: { provider?: unknown; reason?: unknown };
+ errorType?: unknown;
+ message?: unknown;
+ };
+
+ const errorType = typeof raw.errorType === 'number' ? raw.errorType : undefined;
+ const provider =
+ typeof raw._responseBody?.provider === 'string' ? raw._responseBody.provider : undefined;
+ const reason =
+ typeof raw._responseBody?.reason === 'string' ? raw._responseBody.reason : undefined;
+ const message = typeof raw.message === 'string' ? raw.message : undefined;
+
+ // Numeric error types are part of the generic model-runtime error contract
+ // (429 rate limits, 4xx validation, provider-policy refusals), and
+ // `normalizeChatMessageError` propagates `provider` (and other display
+ // metadata) into every error body β€” so neither establishes a gateway-level
+ // refusal on its own. `_responseBody.reason` is the gateway-specific marker:
+ // require it before suppressing the throw, and keep ordinary structured
+ // errors (including provider-only response bodies, e.g. a 429 rate limit)
+ // transparent and retryable via the existing rethrow behavior.
+ if (errorType === undefined || !reason) return;
+
+ const parts = [
+ `Media analysis was rejected by the platform model gateway (HTTP ${errorType}${provider ? `, provider: ${provider}` : ''}).`,
+ `Gateway reason: ${reason}.`,
+ message && message !== 'error' ? `Upstream message: ${message}.` : undefined,
+ 'This is an account/gateway-level refusal, not a content-policy verdict on the media. Do not retry blindly or treat the media as blocked content.',
+ ].filter(Boolean);
+
+ return {
+ code: `GATEWAY_${reason.toUpperCase().replaceAll(/[^A-Z0-9]+/g, '_')}`,
+ content: parts.join(' '),
+ };
+};
+
const BASE64_CONTENT_PATTERN = /^[A-Z\d+/]+={0,2}$/i;
const MAX_INLINE_IMAGE_PIXELS = 25_000_000;
/**
@@ -570,7 +618,12 @@ class LobeAgentExecutionRuntime {
await consumeStreamUntilDone(response);
} catch (error) {
const creditErrorType = getCreditErrorType(error);
- if (!creditErrorType) throw error;
+ if (!creditErrorType) {
+ const rejection = getGatewayRejection(error);
+ if (!rejection) throw error;
+
+ return buildError(rejection.content, rejection.code);
+ }
return buildError(
`Media analysis could not run: it uses the platform model "${provider}/${model}", which is billed to the user's LobeHub credits, and those credits are exhausted (${creditErrorType}). ` +