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: stop retrying Google content blocks and end client runs immediately (#17937)

sxjeruf6ddb0675efa
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/llmErrorClassification.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/llmErrorClassification.test.ts
index 859c79524eb..d2ba2612925 100644
--- a/apps/server/src/modules/AgentRuntime/__tests__/llmErrorClassification.test.ts
+++ b/apps/server/src/modules/AgentRuntime/__tests__/llmErrorClassification.test.ts
@@ -65,6 +65,8 @@ describe('classifyLLMError', () => {
// straight from the spec table.
it.each([
['ContentModeration', 'Content Exists Risk'],
+ // Google promptFeedback / blocked finishReason map to this type so callLlm does not retry.
+ ['ProviderContentPolicyViolation', 'The content may contain prohibited content'],
['InvalidRequestFormat', 'Range of input length should be 1 to 8192'],
['UserConfigError', 'Invalid URL (POST /v1/v1beta'],
['NoAvailableChannel', 'No available keys in pool'],
diff --git a/packages/agent-runtime/src/utils/llmErrorClassifier.test.ts b/packages/agent-runtime/src/utils/llmErrorClassifier.test.ts
index 90b2a91856e..46b0c3f4c9f 100644
--- a/packages/agent-runtime/src/utils/llmErrorClassifier.test.ts
+++ b/packages/agent-runtime/src/utils/llmErrorClassifier.test.ts
@@ -10,6 +10,10 @@ const specsByCode: Record<string, LLMErrorCodeSpecLike> = {
AgentRuntimeError: { code: 'AgentRuntimeError', retryable: false },
ExceededToolLimit: { code: 'ExceededToolLimit', retryable: false },
InvalidProviderAPIKey: { code: 'InvalidProviderAPIKey', retryable: false },
+ ProviderContentPolicyViolation: {
+ code: 'ProviderContentPolicyViolation',
+ retryable: false,
+ },
RateLimitExceeded: { code: 'RateLimitExceeded', retryable: true },
};
@@ -66,6 +70,21 @@ describe('llmErrorClassifier', () => {
).toBe('retry');
});
+ it('stops ProviderContentPolicyViolation instead of retrying content blocks', () => {
+ expect(
+ classifyWithSpecs({
+ body: {
+ context: { promptFeedback: { blockReason: 'PROHIBITED_CONTENT' } },
+ message: 'The content may contain prohibited content. Please adjust it and try again.',
+ provider: 'google',
+ },
+ errorType: 'ProviderContentPolicyViolation',
+ message: 'The content may contain prohibited content. Please adjust it and try again.',
+ type: 'ProviderContentPolicyViolation',
+ }).kind,
+ ).toBe('stop');
+ });
+
it('falls back to numeric status and keyword classification without injected specs', () => {
expect(classifyLLMError({ code: 401, message: 'upstream refused' }).kind).toBe('stop');
expect(classifyLLMError({ code: 429, message: 'upstream refused' }).kind).toBe('retry');
diff --git a/packages/model-runtime/src/core/streams/google/google-ai.test.ts b/packages/model-runtime/src/core/streams/google/google-ai.test.ts
index 313245d214d..95ace19de44 100644
--- a/packages/model-runtime/src/core/streams/google/google-ai.test.ts
+++ b/packages/model-runtime/src/core/streams/google/google-ai.test.ts
@@ -1698,7 +1698,7 @@ describe('GoogleGenerativeAIStream', () => {
expect(chunks).toEqual([
'id: chat_1\n',
'event: error\n',
- `data: {"body":{"context":{"promptFeedback":{"blockReason":"PROHIBITED_CONTENT"}},"message":"The content may contain prohibited content. Please adjust it and try again.","provider":"google"},"type":"ProviderBizError"}\n\n`,
+ `data: {"body":{"context":{"promptFeedback":{"blockReason":"PROHIBITED_CONTENT"}},"message":"The content may contain prohibited content. Please adjust it and try again.","provider":"google"},"type":"ProviderContentPolicyViolation"}\n\n`,
]);
});
@@ -1740,7 +1740,7 @@ describe('GoogleGenerativeAIStream', () => {
`data: {"inputTextTokens":10,"outputImageTokens":0,"outputTextTokens":2,"totalInputTokens":10,"totalOutputTokens":2,"totalTokens":12}\n\n`,
'id: chat_1\n',
'event: error\n',
- `data: {"body":{"context":{"finishMessage":"The model output could not be generated. This output contains sensitive words that violate policies.","finishReason":"PROHIBITED_CONTENT"},"message":"The content may contain prohibited content. Please adjust it and try again.","provider":"google"},"type":"ProviderBizError"}\n\n`,
+ `data: {"body":{"context":{"finishMessage":"The model output could not be generated. This output contains sensitive words that violate policies.","finishReason":"PROHIBITED_CONTENT"},"message":"The content may contain prohibited content. Please adjust it and try again.","provider":"google"},"type":"ProviderContentPolicyViolation"}\n\n`,
]);
});
diff --git a/packages/model-runtime/src/core/streams/google/index.ts b/packages/model-runtime/src/core/streams/google/index.ts
index 8a2f3f37363..e0054fd57a0 100644
--- a/packages/model-runtime/src/core/streams/google/index.ts
+++ b/packages/model-runtime/src/core/streams/google/index.ts
@@ -58,12 +58,9 @@ const transformGoogleGenerativeAIStream = (
};
}
// Handle promptFeedback with blockReason (e.g., PROHIBITED_CONTENT)
+ // Content blocks are terminal policy rejections — never retryable ProviderBizError.
if ('promptFeedback' in chunk && (chunk as any).promptFeedback?.blockReason) {
const blockReason = (chunk as any).promptFeedback.blockReason;
- const errorType =
- blockReason === 'IMAGE_PROHIBITED_CONTENT'
- ? AgentRuntimeErrorType.ProviderContentPolicyViolation
- : AgentRuntimeErrorType.ProviderBizError;
const humanFriendlyMessage = getBlockReasonMessage(blockReason);
return {
@@ -75,7 +72,7 @@ const transformGoogleGenerativeAIStream = (
message: humanFriendlyMessage,
provider: 'google',
},
- type: errorType,
+ type: AgentRuntimeErrorType.ProviderContentPolicyViolation,
},
id: context?.id || 'error',
type: 'error',
@@ -89,15 +86,12 @@ const transformGoogleGenerativeAIStream = (
serializeScopedSignature(signature, payload?.thoughtSignatureScope, 'thought_signature');
// Handle blocked terminal candidate finishReason (e.g., PROHIBITED_CONTENT, SAFETY)
+ // Same as promptFeedback: policy blocks must stop the attempt, not trigger LLM retry.
const blockedReason = getCandidateBlockedReason(candidate);
if (blockedReason) {
const convertedUsage = usageMetadata
? convertGoogleAIUsage(usageMetadata, payload?.pricing)
: undefined;
- const errorType =
- blockedReason === 'IMAGE_PROHIBITED_CONTENT'
- ? AgentRuntimeErrorType.ProviderContentPolicyViolation
- : AgentRuntimeErrorType.ProviderBizError;
const humanFriendlyMessage = getBlockReasonMessage(blockedReason);
return [
@@ -114,7 +108,7 @@ const transformGoogleGenerativeAIStream = (
message: humanFriendlyMessage,
provider: 'google',
},
- type: errorType,
+ type: AgentRuntimeErrorType.ProviderContentPolicyViolation,
},
id: context?.id || 'error',
type: 'error' as const,
diff --git a/src/store/chat/agents/transports/ClientLLMTransport.test.ts b/src/store/chat/agents/transports/ClientLLMTransport.test.ts
index aea1b6063eb..3569b614550 100644
--- a/src/store/chat/agents/transports/ClientLLMTransport.test.ts
+++ b/src/store/chat/agents/transports/ClientLLMTransport.test.ts
@@ -63,27 +63,32 @@ vi.mock('../StreamingHandler', () => ({
},
}));
-const createTransport = () => {
+const createTransport = (context: Record<string, unknown> = {}) => {
const operation = {
abortController: new AbortController(),
- context: { agentId: 'agent-1', topicId: 'topic-1' },
+ context: { agentId: 'agent-1', topicId: 'topic-1', ...context },
status: 'running',
};
const store = {
associateMessageWithOperation: vi.fn(),
completeOperation: vi.fn(),
+ failOperation: vi.fn(),
internal_dispatchMessage: vi.fn(),
internal_toggleToolCallingStreaming: vi.fn(),
internal_transformToolCalls: vi.fn((calls: unknown) => calls),
operations: { 'op-1': operation },
startOperation: vi.fn(() => ({ operationId: 'reasoning-op' })),
+ updateTopicStatus: vi.fn().mockResolvedValue(undefined),
} as unknown as ChatStore;
- return new ClientLLMTransport({
- get: () => store,
- operationId: 'op-1',
- session: { assistantMessageId: 'msg-1' } as any,
- });
+ return {
+ store,
+ transport: new ClientLLMTransport({
+ get: () => store,
+ operationId: 'op-1',
+ session: { assistantMessageId: 'msg-1' } as any,
+ }),
+ };
};
const input = {
@@ -107,7 +112,7 @@ describe('ClientLLMTransport.runAttempt · empty-completion grounding guard', ()
it('keeps a grounding-only completion (empty content, positive output tokens) as a success', async () => {
finishGrounding = grounding;
- const result = await createTransport().runAttempt(input);
+ const result = await createTransport().transport.runAttempt(input);
expect(result.ok).toBe(true);
expect(result.output.grounding).toEqual(grounding);
@@ -115,13 +120,129 @@ describe('ClientLLMTransport.runAttempt · empty-completion grounding guard', ()
it('still flags a truly empty completion (no content, no grounding) as ModelEmptyError', async () => {
finishGrounding = null;
- const result = await createTransport().runAttempt(input);
+ const { transport } = createTransport();
+ const result = await transport.runAttempt(input);
expect(result.ok).toBe(false);
if (result.ok === false) {
expect(result.error).toBeInstanceOf(ModelEmptyError);
expect((result.error as ModelEmptyError).diagnostics).toMatchObject({ cost: 5.980_015 });
- expect(createTransport().retryPolicy.classifyError(result.error).kind).toBe('stop');
+ expect(transport.retryPolicy.classifyError(result.error).kind).toBe('stop');
}
});
});
+
+describe('ClientLLMTransport.retryPolicy.onError · terminal operation teardown', () => {
+ it('writes the message error and fails the running operation immediately', () => {
+ const { store, transport } = createTransport();
+
+ transport.retryPolicy.onError?.({
+ error: {
+ body: {
+ message: 'The content may contain prohibited content. Please adjust it and try again.',
+ provider: 'google',
+ },
+ message: 'The content may contain prohibited content. Please adjust it and try again.',
+ type: 'ProviderContentPolicyViolation',
+ },
+ events: [],
+ interrupted: false,
+ });
+
+ expect(store.internal_dispatchMessage).toHaveBeenCalledWith(
+ {
+ id: 'msg-1',
+ type: 'updateMessage',
+ value: {
+ error: expect.objectContaining({
+ message: 'The content may contain prohibited content. Please adjust it and try again.',
+ type: 'ProviderContentPolicyViolation',
+ }),
+ },
+ },
+ { operationId: 'op-1' },
+ );
+ expect(store.failOperation).toHaveBeenCalledWith('op-1', {
+ message: 'The content may contain prohibited content. Please adjust it and try again.',
+ type: 'ProviderContentPolicyViolation',
+ });
+ expect(store.updateTopicStatus).toHaveBeenCalledWith({
+ agentId: 'agent-1',
+ groupId: undefined,
+ status: 'active',
+ topicId: 'topic-1',
+ });
+ });
+
+ it('resets group-scoped topic status with the operation scope', () => {
+ const { store, transport } = createTransport({
+ groupId: 'group-1',
+ scope: 'group',
+ });
+
+ transport.retryPolicy.onError?.({
+ error: {
+ message: 'The content may contain prohibited content. Please adjust it and try again.',
+ type: 'ProviderContentPolicyViolation',
+ },
+ events: [],
+ interrupted: false,
+ });
+
+ expect(store.updateTopicStatus).toHaveBeenCalledWith({
+ agentId: 'agent-1',
+ groupId: 'group-1',
+ scope: 'group',
+ status: 'active',
+ topicId: 'topic-1',
+ });
+ });
+
+ it('does not fail the operation when the run was interrupted by the user', () => {
+ const { store, transport } = createTransport();
+
+ transport.retryPolicy.onError?.({
+ error: { message: 'aborted', type: 'AbortError' },
+ events: [],
+ interrupted: true,
+ });
+
+ expect(store.internal_dispatchMessage).not.toHaveBeenCalled();
+ expect(store.failOperation).not.toHaveBeenCalled();
+ expect(store.updateTopicStatus).not.toHaveBeenCalled();
+ });
+
+ it('does not fail an operation that is no longer running', () => {
+ const { store, transport } = createTransport();
+ store.operations['op-1'].status = 'cancelled';
+
+ transport.retryPolicy.onError?.({
+ error: {
+ message: 'The content may contain prohibited content. Please adjust it and try again.',
+ type: 'ProviderContentPolicyViolation',
+ },
+ events: [],
+ interrupted: false,
+ });
+
+ expect(store.internal_dispatchMessage).toHaveBeenCalled();
+ expect(store.failOperation).not.toHaveBeenCalled();
+ expect(store.updateTopicStatus).not.toHaveBeenCalled();
+ });
+
+ it('does not reset topic status for nested sub-agent operations', () => {
+ const { store, transport } = createTransport({ scope: 'sub_agent' });
+
+ transport.retryPolicy.onError?.({
+ error: {
+ message: 'The content may contain prohibited content. Please adjust it and try again.',
+ type: 'ProviderContentPolicyViolation',
+ },
+ events: [],
+ interrupted: false,
+ });
+
+ expect(store.failOperation).toHaveBeenCalled();
+ expect(store.updateTopicStatus).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/store/chat/agents/transports/ClientLLMTransport.ts b/src/store/chat/agents/transports/ClientLLMTransport.ts
index 6d6ec59787b..1f6b0779575 100644
--- a/src/store/chat/agents/transports/ClientLLMTransport.ts
+++ b/src/store/chat/agents/transports/ClientLLMTransport.ts
@@ -145,6 +145,34 @@ class ClientLLMRetryPolicy implements LLMRetryPolicy {
},
{ operationId: this.operationId },
);
+
+ // callLlm only invokes onError for the terminal attempt. End the operation
+ // here so Stop/loading clear with the message error, not after outer completeRun.
+ const operation = this.get().operations[this.operationId];
+ if (operation?.status === 'running') {
+ this.get().failOperation(this.operationId, {
+ message: localizedError.message || 'LLM execution failed',
+ type: String(localizedError.type ?? 'runtime_error'),
+ });
+
+ // Match completeRun's client failed-path topic reset. streamingExecutor
+ // writes status:'running' at start; without this, the sidebar keeps the
+ // spinner until the outer loop later reaches completeRun.
+ const { agentId, groupId, scope, topicId } = operation.context;
+ if (topicId && scope !== 'sub_agent') {
+ void this.get()
+ .updateTopicStatus?.({
+ agentId,
+ groupId,
+ ...(scope === 'group' || scope === 'group_agent' ? { scope } : {}),
+ status: 'active',
+ topicId,
+ })
+ ?.catch((error) => {
+ console.error('[ClientLLMTransport] topic status reset failed:', error);
+ });
+ }
+ }
}
onRetry(_input: LLMRetryInput) {