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.

✨ feat: improve error UI and error handling across chat and image generation (#13302)

YuTengjingd2a16d0714e5
diff --git a/locales/en-US/error.json b/locales/en-US/error.json
index 2a693015ed9..efd1d8b5005 100644
--- a/locales/en-US/error.json
+++ b/locales/en-US/error.json
@@ -4,6 +4,9 @@
"error.retry": "Reload",
"error.stack": "Error Stack",
"error.title": "Oops, something went wrong..",
+ "exceededContext.compact": "Compact Context",
+ "exceededContext.desc": "The conversation has exceeded the context window limit. You can compact the context to compress history and continue chatting.",
+ "exceededContext.title": "Context Window Exceeded",
"fetchError.detail": "Error details",
"fetchError.title": "Request failed",
"import.importConfigFile.description": "Error reason: {{reason}}",
@@ -108,7 +111,7 @@
"response.PluginSettingsInvalid": "This skill needs to be correctly configured before it can be used. Please check if your configuration is correct",
"response.ProviderBizError": "Error requesting {{provider}} service, please troubleshoot or retry based on the following information",
"response.QuotaLimitReached": "Sorry, the token usage or request count has reached the quota limit for this key. Please increase the key's quota or try again later.",
- "response.QuotaLimitReachedCloud": "The model service is currently under heavy load. Please try again later.",
+ "response.QuotaLimitReachedCloud": "The model service is currently under heavy load. Please try again later or switch to another model.",
"response.ServerAgentRuntimeError": "Sorry, the Agent service is currently unavailable. Please try again later or contact us via email for support.",
"response.StreamChunkError": "Error parsing the message chunk of the streaming request. Please check if the current API interface complies with the standard specifications, or contact your API provider for assistance.",
"response.SubscriptionKeyMismatch": "We apologize for the inconvenience. Due to a temporary system malfunction, your current subscription usage is inactive. Please click the button below to restore your subscription, or contact us via email for support.",
@@ -120,6 +123,10 @@
"supervisor.decisionFailed": "The group host is unable to function. Please check your host configuration to ensure the correct model, API Key, and API endpoint are set.",
"testConnectionFailed": "Test connection failed: {{error}}",
"tts.responseError": "Service request failed, please check the configuration or try again",
+ "unknownError.copyTraceId": "Trace ID Copied",
+ "unknownError.desc": "An unexpected error occurred. You can retry or report on",
+ "unknownError.retry": "Retry",
+ "unknownError.title": "Oops, the request took a nap",
"unlock.addProxyUrl": "Add OpenAI proxy URL (optional)",
"unlock.apiKey.description": "Enter your {{name}} API Key to start the session",
"unlock.apiKey.imageGenerationDescription": "Enter your {{name}} API Key to start generating",
diff --git a/locales/zh-CN/error.json b/locales/zh-CN/error.json
index 00e4892ab88..a9d9781fcaa 100644
--- a/locales/zh-CN/error.json
+++ b/locales/zh-CN/error.json
@@ -4,6 +4,9 @@
"error.retry": "重新加载",
"error.stack": "错误堆栈",
"error.title": "页面暂时不可用",
+ "exceededContext.compact": "压缩上下文",
+ "exceededContext.desc": "对话已超出模型上下文窗口限制。你可以压缩上下文来压缩历史记录并继续对话。",
+ "exceededContext.title": "上下文窗口超出限制",
"fetchError.detail": "查看详情",
"fetchError.title": "请求未能完成",
"import.importConfigFile.description": "原因:{{reason}}",
@@ -108,7 +111,7 @@
"response.PluginSettingsInvalid": "该技能需要完成配置后才能使用,请检查技能配置",
"response.ProviderBizError": "模型服务商返回错误。请根据以下信息排查,或稍后重试",
"response.QuotaLimitReached": "Token 用量或请求次数已达配额上限。请提升配额或稍后再试",
- "response.QuotaLimitReachedCloud": "当前模型服务负载较高,请稍后重试。",
+ "response.QuotaLimitReachedCloud": "当前模型服务负载较高,请稍后重试或切换其他模型。",
"response.ServerAgentRuntimeError": "助理运行服务暂不可用。请稍后再试,或邮件联系我们",
"response.StreamChunkError": "流式响应解析失败。请检查接口是否符合规范,或联系模型服务商",
"response.SubscriptionKeyMismatch": "订阅状态同步异常。你可以点击下方按钮恢复订阅,或邮件联系我们",
@@ -120,6 +123,10 @@
"supervisor.decisionFailed": "群组主持人运行失败。请检查主持人配置(模型、API Key 与 API 地址)后重试",
"testConnectionFailed": "测试连接失败:{{error}}",
"tts.responseError": "请求失败。请检查配置后重试",
+ "unknownError.copyTraceId": "Trace ID 已复制",
+ "unknownError.desc": "遇到了意外错误,请重试或反馈至",
+ "unknownError.retry": "重试",
+ "unknownError.title": "糟糕,请求打了个盹",
"unlock.addProxyUrl": "添加 OpenAI 代理地址(可选)",
"unlock.apiKey.description": "输入你的 {{name}} API Key,即可开始会话",
"unlock.apiKey.imageGenerationDescription": "输入你的 {{name}} API Key,即可开始生成",
diff --git a/packages/model-runtime/src/core/RouterRuntime/createRuntime.test.ts b/packages/model-runtime/src/core/RouterRuntime/createRuntime.test.ts
index 6a4de6eed92..2767fedb6ac 100644
--- a/packages/model-runtime/src/core/RouterRuntime/createRuntime.test.ts
+++ b/packages/model-runtime/src/core/RouterRuntime/createRuntime.test.ts
@@ -1,3 +1,4 @@
+import { AgentRuntimeErrorType } from '@lobechat/types';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import type { LobeRuntimeAI } from '../BaseAI';
@@ -421,6 +422,83 @@ describe('createRouterRuntime', () => {
).rejects.toThrow('empty provider options');
});
+ it('should not retry when ExceededContextWindow error is thrown', async () => {
+ const exceededError = {
+ errorType: AgentRuntimeErrorType.ExceededContextWindow,
+ error: { message: 'Too many input tokens' },
+ provider: 'test',
+ };
+
+ const mockChatFail = vi.fn().mockRejectedValue(exceededError);
+ const mockChatSuccess = vi.fn().mockResolvedValue('success');
+
+ class FailRuntime implements LobeRuntimeAI {
+ chat = mockChatFail;
+ }
+
+ class SuccessRuntime implements LobeRuntimeAI {
+ chat = mockChatSuccess;
+ }
+
+ const Runtime = createRouterRuntime({
+ id: 'test-runtime',
+ routers: [
+ {
+ apiType: 'openai',
+ options: [
+ { apiKey: 'key-1', runtime: FailRuntime as any },
+ { apiKey: 'key-2', runtime: SuccessRuntime as any },
+ ],
+ runtime: FailRuntime as any,
+ models: ['gpt-4'],
+ },
+ ],
+ });
+
+ const runtime = new Runtime();
+ await expect(
+ runtime.chat({ model: 'gpt-4', messages: [], temperature: 0.7 }),
+ ).rejects.toEqual(exceededError);
+
+ // Second channel should never be called
+ expect(mockChatFail).toHaveBeenCalledTimes(1);
+ expect(mockChatSuccess).not.toHaveBeenCalled();
+ });
+
+ it('should still retry on other error types', async () => {
+ const bizError = {
+ errorType: AgentRuntimeErrorType.ProviderBizError,
+ error: { message: 'Server error' },
+ provider: 'test',
+ };
+
+ const mockChatFail = vi.fn().mockRejectedValue(bizError);
+
+ class FailRuntime implements LobeRuntimeAI {
+ chat = mockChatFail;
+ }
+
+ const Runtime = createRouterRuntime({
+ id: 'test-runtime',
+ routers: [
+ {
+ apiType: 'openai',
+ options: [{ apiKey: 'key-1' }, { apiKey: 'key-2' }],
+ runtime: FailRuntime as any,
+ models: ['gpt-4'],
+ },
+ ],
+ });
+
+ const runtime = new Runtime();
+ await expect(
+ runtime.chat({ model: 'gpt-4', messages: [], temperature: 0.7 }),
+ ).rejects.toEqual(bizError);
+
+ // Both channels should be tried
+ expect(mockChatFail).toHaveBeenCalledTimes(2);
+ });
+
it('should use apiType from option item when specified for fallback', async () => {
const constructorCalls: any[] = [];
diff --git a/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts b/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts
index 6daa9a01e8c..7a0f81434a5 100644
--- a/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts
+++ b/packages/model-runtime/src/core/RouterRuntime/createRuntime.ts
@@ -2,7 +2,7 @@
* @see https://github.com/lobehub/lobe-chat/discussions/6563
*/
import type { GoogleGenAIOptions } from '@google/genai';
-import type { ChatModelCard } from '@lobechat/types';
+import { AgentRuntimeErrorType, type ChatModelCard } from '@lobechat/types';
import debug from 'debug';
import type { ClientOptions } from 'openai';
import type OpenAI from 'openai';
@@ -392,6 +392,14 @@ export const createRouterRuntime = ({
log('onRouteAttempt callback error: %O', e);
});
+ // Non-retryable errors: the request itself is invalid, retrying with another channel won't help
+ if (
+ (error as ChatCompletionErrorPayload)?.errorType ===
+ AgentRuntimeErrorType.ExceededContextWindow
+ ) {
+ throw error;
+ }
+
if (attempt < totalOptions) {
log(
'attempt %d/%d failed (model=%s apiType=%s channelId=%s remark=%s), trying next',
diff --git a/packages/model-runtime/src/providers/bedrock/index.test.ts b/packages/model-runtime/src/providers/bedrock/index.test.ts
index 9541a4215f9..9515cce9614 100644
--- a/packages/model-runtime/src/providers/bedrock/index.test.ts
+++ b/packages/model-runtime/src/providers/bedrock/index.test.ts
@@ -703,6 +703,29 @@ describe('LobeBedrockAI', () => {
}),
);
});
+
+ it('should throw ExceededContextWindow when error message indicates context window exceeded', async () => {
+ const errorMessage =
+ 'Too many input tokens. Max input tokens for this model is 200000, but 250000 were provided.';
+ const errorMetadata = { statusCode: 400 };
+ const mockError = new Error(errorMessage);
+ (mockError as any).$metadata = errorMetadata;
+ (instance['client'].send as Mock).mockRejectedValue(mockError);
+
+ await expect(
+ instance.chat({
+ max_tokens: 100,
+ messages: [{ content: 'Hello', role: 'user' }],
+ model: 'anthropic.claude-v2:1',
+ temperature: 0,
+ }),
+ ).rejects.toThrow(
+ expect.objectContaining({
+ errorType: AgentRuntimeErrorType.ExceededContextWindow,
+ provider: ModelProvider.Bedrock,
+ }),
+ );
+ });
});
describe('Llama Model', () => {
diff --git a/packages/model-runtime/src/providers/bedrock/index.ts b/packages/model-runtime/src/providers/bedrock/index.ts
index 9ead246785c..b95977d8190 100644
--- a/packages/model-runtime/src/providers/bedrock/index.ts
+++ b/packages/model-runtime/src/providers/bedrock/index.ts
@@ -28,6 +28,7 @@ import { AgentRuntimeErrorType } from '../../types/error';
import { AgentRuntimeError } from '../../utils/createError';
import { debugStream } from '../../utils/debugStream';
import { getModelPricing } from '../../utils/getModelPricing';
+import { isExceededContextWindowError } from '../../utils/isExceededContextWindowError';
import { StreamingResponse } from '../../utils/response';
/**
@@ -284,6 +285,9 @@ export class LobeBedrockAI implements LobeRuntimeAI {
);
} catch (e) {
const err = e as Error & { $metadata: any };
+ const errorType = isExceededContextWindowError(err.message)
+ ? AgentRuntimeErrorType.ExceededContextWindow
+ : AgentRuntimeErrorType.ProviderBizError;
throw AgentRuntimeError.chat({
error: {
@@ -291,7 +295,7 @@ export class LobeBedrockAI implements LobeRuntimeAI {
message: err.message,
type: err.name,
},
- errorType: AgentRuntimeErrorType.ProviderBizError,
+ errorType,
provider: this.id,
region: this.region,
});
diff --git a/packages/model-runtime/src/providers/fal/index.ts b/packages/model-runtime/src/providers/fal/index.ts
index 8019276fc95..d946095cad6 100644
--- a/packages/model-runtime/src/providers/fal/index.ts
+++ b/packages/model-runtime/src/providers/fal/index.ts
@@ -103,6 +103,22 @@ export class LobeFalAI implements LobeRuntimeAI {
});
}
+ // 422 ValidationError with content_policy_violation — show a clean message
+ if (error instanceof Error && 'status' in error && error.status === 422) {
+ const body = 'body' in error ? (error as any).body : undefined;
+ const hasContentPolicyViolation =
+ Array.isArray(body?.detail) &&
+ body.detail.some((d: any) => d.type === 'content_policy_violation');
+
+ if (hasContentPolicyViolation) {
+ throw AgentRuntimeError.createError(AgentRuntimeErrorType.ProviderBizError, {
+ error,
+ message:
+ 'The request content violates content policy. Please modify your prompt and try again.',
+ });
+ }
+ }
+
throw AgentRuntimeError.createError(AgentRuntimeErrorType.ProviderBizError, { error });
}
}
diff --git a/src/features/ChatInput/ActionBar/Token/TokenProgress.test.ts b/src/features/ChatInput/ActionBar/Token/TokenProgress.test.ts
new file mode 100644
index 00000000000..f47906a61eb
--- /dev/null
+++ b/src/features/ChatInput/ActionBar/Token/TokenProgress.test.ts
@@ -0,0 +1,25 @@
+import { describe, expect, it } from 'vitest';
+
+import { formatToken } from './TokenProgress';
+
+describe('formatToken', () => {
+ it('should format numbers >= 1M with M suffix', () => {
+ expect(formatToken(1_000_000)).toBe('1M');
+ expect(formatToken(1_500_000)).toBe('1.5M');
+ expect(formatToken(2_000_000)).toBe('2M');
+ expect(formatToken(10_000_000)).toBe('10M');
+ });
+
+ it('should format numbers >= 1K with K suffix', () => {
+ expect(formatToken(1_000)).toBe('1K');
+ expect(formatToken(14_251)).toBe('14.3K');
+ expect(formatToken(985_749)).toBe('985.7K');
+ expect(formatToken(999_999)).toBe('1000K');
+ });
+
+ it('should format numbers < 1K with comma separator', () => {
+ expect(formatToken(0)).toBe('0');
+ expect(formatToken(1)).toBe('1');
+ expect(formatToken(999)).toBe('999');
+ });
+});
diff --git a/src/features/ChatInput/ActionBar/Token/TokenProgress.tsx b/src/features/ChatInput/ActionBar/Token/TokenProgress.tsx
index 7837acb87bb..a025e1a73ac 100644
--- a/src/features/ChatInput/ActionBar/Token/TokenProgress.tsx
+++ b/src/features/ChatInput/ActionBar/Token/TokenProgress.tsx
@@ -17,7 +17,11 @@ interface TokenProgressProps {
showTotal?: string;
}
-const format = (number: number) => numeral(number).format('0,0');
+export const formatToken = (number: number) => {
+ if (number >= 1_000_000) return numeral(number / 1_000_000).format('0.[0]') + 'M';
+ if (number >= 1_000) return numeral(number / 1_000).format('0.[0]') + 'K';
+ return numeral(number).format('0,0');
+};
const TokenProgress = memo<TokenProgressProps>(({ data, showIcon, showTotal }) => {
const total = data.reduce((acc, item) => acc + item.value, 0);
@@ -59,7 +63,7 @@ const TokenProgress = memo<TokenProgressProps>(({ data, showIcon, showTotal }) =
)}
<div style={{ color: cssVar.colorTextSecondary }}>{item.title}</div>
</Flexbox>
- <div style={{ fontWeight: 500 }}>{format(item.value)}</div>
+ <div style={{ fontWeight: 500 }}>{formatToken(item.value)}</div>
</Flexbox>
))}
{showTotal && (
@@ -67,7 +71,7 @@ const TokenProgress = memo<TokenProgressProps>(({ data, showIcon, showTotal }) =
<Divider style={{ marginBlock: 8 }} />
<Flexbox horizontal align={'center'} gap={4} justify={'space-between'}>
<div style={{ color: cssVar.colorTextSecondary }}>{showTotal}</div>
- <div style={{ fontWeight: 500 }}>{format(total)}</div>
+ <div style={{ fontWeight: 500 }}>{formatToken(total)}</div>
</Flexbox>
</>
)}
diff --git a/src/features/Conversation/Error/ExceededContextWindowError.tsx b/src/features/Conversation/Error/ExceededContextWindowError.tsx
new file mode 100644
index 00000000000..b1b4e82d313
--- /dev/null
+++ b/src/features/Conversation/Error/ExceededContextWindowError.tsx
@@ -0,0 +1,57 @@
+import { Icon } from '@lobehub/ui';
+import { Button } from 'antd';
+import { Minimize2 } from 'lucide-react';
+import { memo, useCallback, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useChatStore } from '@/store/chat';
+
+import { useConversationStore } from '../store';
+import BaseErrorForm from './BaseErrorForm';
+
+interface ExceededContextWindowErrorProps {
+ id: string;
+}
+
+const ExceededContextWindowError = memo<ExceededContextWindowErrorProps>(({ id }) => {
+ const { t } = useTranslation('error');
+ const [loading, setLoading] = useState(false);
+
+ const context = useConversationStore((s) => s.context);
+ const regenerateUserMessage = useConversationStore((s) => s.regenerateUserMessage);
+ const parentId = useConversationStore(
+ (s) => s.displayMessages.find((m) => m.id === id)?.parentId,
+ );
+
+ const handleCompact = useCallback(async () => {
+ if (!context.topicId || !parentId) return;
+
+ setLoading(true);
+ try {
+ await useChatStore.getState().executeCompression(context, '');
+ await regenerateUserMessage(parentId);
+ } finally {
+ setLoading(false);
+ }
+ }, [context, parentId, regenerateUserMessage]);
+
+ return (
+ <BaseErrorForm
+ avatar={<Icon icon={Minimize2} size={24} />}
+ desc={t('exceededContext.desc')}
+ title={t('exceededContext.title')}
+ action={
+ <Button
+ disabled={!context.topicId}
+ loading={loading}
+ type={'primary'}
+ onClick={handleCompact}
+ >
+ {t('exceededContext.compact')}
+ </Button>
+ }
+ />
+ );
+});
+
+export default ExceededContextWindowError;
diff --git a/src/features/Conversation/Error/index.tsx b/src/features/Conversation/Error/index.tsx
index 62c3c731803..93ec128cccb 100644
--- a/src/features/Conversation/Error/index.tsx
+++ b/src/features/Conversation/Error/index.tsx
@@ -38,6 +38,11 @@ const loading = () => (
</Block>
);
+const ExceededContextWindowError = dynamic(() => import('./ExceededContextWindowError'), {
+ loading,
+ ssr: false,
+});
+
const OllamaBizError = dynamic(() => import('./OllamaBizError'), { loading, ssr: false });
const OllamaSetupGuide = dynamic(() => import('./OllamaSetupGuide'), {
@@ -130,6 +135,10 @@ const ErrorMessageExtra = memo<ErrorExtraProps>(({ error: alertError, data }) =>
return <OllamaBizError {...data} />;
}
+ case AgentRuntimeErrorType.ExceededContextWindow: {
+ return <ExceededContextWindowError id={data.id} />;
+ }
+
/* ↓ cloud slot ↓ */
/* ↑ cloud slot ↑ */
diff --git a/src/locales/default/error.ts b/src/locales/default/error.ts
index b6bb2a71d54..ed6e74cd1ed 100644
--- a/src/locales/default/error.ts
+++ b/src/locales/default/error.ts
@@ -104,12 +104,22 @@ export default {
'The request returned empty. Please check if the API proxy address does not end with `/v1`.',
'response.CreateMessageError':
'Sorry, the message could not be sent successfully. Please copy the content and try sending it again. This message will not be retained after refreshing the page.',
+ 'exceededContext.compact': 'Compact Context',
+ 'exceededContext.desc':
+ 'The conversation has exceeded the context window limit. You can compact the context to compress history and continue chatting.',
+ 'exceededContext.title': 'Context Window Exceeded',
+
+ 'unknownError.copyTraceId': 'Trace ID Copied',
+ 'unknownError.desc': 'An unexpected error occurred. You can retry or report on',
+ 'unknownError.retry': 'Retry',
+ 'unknownError.title': 'Oops, the request took a nap',
+
'response.ExceededContextWindow':
'The current request content exceeds the length that the model can handle. Please reduce the amount of content and try again.',
'response.ExceededContextWindowCloud':
'The conversation is too long to process. Please edit your last message to reduce input or delete some messages and try again.',
'response.QuotaLimitReachedCloud':
- 'The model service is currently under heavy load. Please try again later.',
+ 'The model service is currently under heavy load. Please try again later or switch to another model.',
'response.FreePlanLimit':
'You are currently a free user and cannot use this feature. Please upgrade to a paid plan to continue using it.',
'response.InsufficientBudgetForModel':
diff --git a/src/routes/(main)/(create)/image/features/GenerationFeed/GenerationItem/LoadingState.tsx b/src/routes/(main)/(create)/image/features/GenerationFeed/GenerationItem/LoadingState.tsx
index b9f03b92bc1..178dbe1309b 100644
--- a/src/routes/(main)/(create)/image/features/GenerationFeed/GenerationItem/LoadingState.tsx
+++ b/src/routes/(main)/(create)/image/features/GenerationFeed/GenerationItem/LoadingState.tsx
@@ -22,7 +22,7 @@ export const LoadingState = memo<LoadingStateProps>(
return (
<Block
align={'center'}
- className={styles.placeholderContainer}
+ className={`${styles.placeholderContainer} ${styles.placeholderContainerLoading}`}
justify={'center'}
variant={'filled'}
style={{
@@ -30,7 +30,7 @@ export const LoadingState = memo<LoadingStateProps>(
maxWidth: getThumbnailMaxWidth(generation, generationBatch),
}}
>
- <div className={styles.placeholderContainer} />
+ <div className={`${styles.placeholderContainer} ${styles.placeholderContainerLoading}`} />
<Center gap={8} style={{ zIndex: 2 }}>
<NeuralNetworkLoading size={48} />
<ElapsedTime generationId={generation.id} isActive={isGenerating} />
diff --git a/src/routes/(main)/(create)/image/features/GenerationFeed/GenerationItem/styles.ts b/src/routes/(main)/(create)/image/features/GenerationFeed/GenerationItem/styles.ts
index 3529e65c9c2..a41f7a47dac 100644
--- a/src/routes/(main)/(create)/image/features/GenerationFeed/GenerationItem/styles.ts
+++ b/src/routes/(main)/(create)/image/features/GenerationFeed/GenerationItem/styles.ts
@@ -43,6 +43,12 @@ export const styles = createStaticStyles(({ css, cssVar }) => ({
overflow: hidden;
width: 100%;
+ &:hover .generation-actions {
+ opacity: 1;
+ }
+ `,
+
+ placeholderContainerLoading: css`
&::before {
content: '';
@@ -54,10 +60,6 @@ export const styles = createStaticStyles(({ css, cssVar }) => ({
animation: ${shimmer} 2s linear infinite;
}
-
- &:hover .generation-actions {
- opacity: 1;
- }
`,
spinIcon: css`
diff --git a/src/routes/(main)/settings/hooks/useCategory.tsx b/src/routes/(main)/settings/hooks/useCategory.tsx
index c04e9c37c64..4764e924028 100644
--- a/src/routes/(main)/settings/hooks/useCategory.tsx
+++ b/src/routes/(main)/settings/hooks/useCategory.tsx
@@ -127,7 +127,7 @@ export const useCategory = () => {
// Agent group
const agentItems: CategoryItem[] = [
- {
+ (!enableBusinessFeatures || isDevMode) && {
icon: Brain,
key: SettingsTabs.Provider,
label: t('tab.provider'),
diff --git a/src/server/routers/async/image.ts b/src/server/routers/async/image.ts
index 3e3823386f9..7ff00348eb6 100644
--- a/src/server/routers/async/image.ts
+++ b/src/server/routers/async/image.ts
@@ -155,6 +155,22 @@ const categorizeError = (
};
}
+ // Content moderation / policy violation — return a clean, generic message
+ const errorMsg: string = error.message || error.error?.message || '';
+ const errorCode: string = error.code || error.error?.code || '';
+ if (
+ errorCode === 'InputTextSensitiveContentDetected' ||
+ errorCode === 'content_policy_violation' ||
+ errorMsg.toLowerCase().includes('content policy') ||
+ errorMsg.toLowerCase().includes('sensitive information')
+ ) {
+ return {
+ errorMessage:
+ 'The request content may violate content policy. Please modify your prompt and try again.',
+ errorType: AsyncTaskErrorType.ServerError,
+ };
+ }
+
if (error instanceof AsyncTaskError) {
return {
errorMessage: typeof error.body === 'string' ? error.body : error.body.detail,
diff --git a/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts b/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts
index 2b8289372fc..90a412cf425 100644
--- a/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts
+++ b/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts
@@ -149,7 +149,7 @@ export class ConversationLifecycleActionImpl {
compressContext.topicId &&
!hasRunningCompressionOperation(Object.values(this.#get().operations), compressContext)
) {
- await this.#executeCompression(compressContext, '');
+ await this.executeCompression(compressContext, '');
}
return;
}
@@ -596,7 +596,7 @@ export class ConversationLifecycleActionImpl {
* Execute context compression for /compact command.
* Reuses the same service methods as the agent runtime's compress_context executor.
*/
- #executeCompression = async (
+ executeCompression = async (
context: Record<string, any>,
parentOperationId: string,
): Promise<void> => {
diff --git a/src/store/file/slices/chat/action.ts b/src/store/file/slices/chat/action.ts
index ba5efba35ec..96464e1270a 100644
--- a/src/store/file/slices/chat/action.ts
+++ b/src/store/file/slices/chat/action.ts
@@ -170,8 +170,7 @@ export class FileActionImpl {
// image don't need to be chunked and embedding
if (isChunkingUnsupported(file.type)) return;
- const data = await ragService.parseFileContent(fileResult.id);
- console.info('parseFileContent data:', data);
+ await ragService.parseFileContent(fileResult.id);
});
await Promise.all(pools);