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: pause input completion after errors (#15692)

YuTengjingba6976c06310
diff --git a/apps/server/src/routers/lambda/__tests__/aiChat.test.ts b/apps/server/src/routers/lambda/__tests__/aiChat.test.ts
index 2917227a978..b7335dd71dd 100644
--- a/apps/server/src/routers/lambda/__tests__/aiChat.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/aiChat.test.ts
@@ -1032,6 +1032,56 @@ describe('aiChatRouter', () => {
}
});
+ it('marks input completion runtime 4xx errors to skip tRPC handler logging', async () => {
+ const { initModelRuntimeFromDB } = await import('@/server/modules/ModelRuntime');
+ const runtimeError = {
+ error: { message: 'rate limited' },
+ errorType: AgentRuntimeErrorType.RateLimitExceeded,
+ };
+
+ vi.mocked(initModelRuntimeFromDB).mockRejectedValueOnce(runtimeError);
+
+ const caller = aiChatRouter.createCaller({ ...mockCtx, serverDB: {} } as any);
+
+ try {
+ await caller.outputJSON({
+ messages: [{ content: 'test', role: 'user' }],
+ model: 'gpt-4o',
+ provider: 'openai',
+ tracing: { scenario: 'input_completion' },
+ });
+ throw new Error('Expected outputJSON to throw');
+ } catch (error) {
+ expect(error).toBeInstanceOf(TRPCError);
+ expect((runtimeError as any).__lobeSilentTRPCErrorLog).toBe(true);
+ }
+ });
+
+ it('does not mark non-input-completion runtime errors as silent', async () => {
+ const { initModelRuntimeFromDB } = await import('@/server/modules/ModelRuntime');
+ const runtimeError = {
+ error: { message: 'rate limited' },
+ errorType: AgentRuntimeErrorType.RateLimitExceeded,
+ };
+
+ vi.mocked(initModelRuntimeFromDB).mockRejectedValueOnce(runtimeError);
+
+ const caller = aiChatRouter.createCaller({ ...mockCtx, serverDB: {} } as any);
+
+ try {
+ await caller.outputJSON({
+ messages: [{ content: 'test', role: 'user' }],
+ model: 'gpt-4o',
+ provider: 'openai',
+ tracing: { scenario: 'topic_title' },
+ });
+ throw new Error('Expected outputJSON to throw');
+ } catch (error) {
+ expect(error).toBeInstanceOf(TRPCError);
+ 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 ce0f8fdb88e..12bf7af7c73 100644
--- a/apps/server/src/routers/lambda/aiChat.ts
+++ b/apps/server/src/routers/lambda/aiChat.ts
@@ -1,5 +1,6 @@
import { randomUUID } from 'node:crypto';
+import { TRACING_SCENARIOS } from '@lobechat/const';
import { getErrorCodeSpec } from '@lobechat/model-runtime';
import type { CreateMessageParams, SendMessageServerResponse } from '@lobechat/types';
import { AiSendMessageServerSchema, RequestTrigger, StructureOutputSchema } from '@lobechat/types';
@@ -28,6 +29,7 @@ const log = debug('lobe-lambda-router:ai-chat');
const { createPrefixedTimingContext, logTiming, runTimedStage } = createTimingHelpers(
'lobe-server:chat:lobehub:timing',
);
+const SILENT_TRPC_ERROR_LOG_KEY = '__lobeSilentTRPCErrorLog';
type TRPCErrorCode = ConstructorParameters<typeof TRPCError>[0]['code'];
type TRPCStatusCode = Parameters<typeof getStatusKeyFromCode>[0];
@@ -49,10 +51,28 @@ const getTRPCErrorCodeFromStatus = (status: number): TRPCErrorCode => {
return 'INTERNAL_SERVER_ERROR';
};
-const createRuntimeTRPCError = (error: unknown): TRPCError | undefined => {
+const markSilentTRPCErrorLog = (error: unknown) => {
+ if (!error || typeof error !== 'object') return;
+
+ try {
+ Object.defineProperty(error, SILENT_TRPC_ERROR_LOG_KEY, {
+ configurable: true,
+ value: true,
+ });
+ } catch {
+ // Best-effort logging hint; never let it mask the original runtime error.
+ }
+};
+
+const createRuntimeTRPCError = (
+ error: unknown,
+ options?: { silentHandlerLog?: boolean },
+): TRPCError | undefined => {
const errorType = getRuntimeErrorType(error);
const spec = getErrorCodeSpec(errorType);
if (errorType && spec) {
+ if (options?.silentHandlerLog && spec.httpStatus < 500) markSilentTRPCErrorLog(error);
+
return new TRPCError({
cause: error,
code: getTRPCErrorCodeFromStatus(spec.httpStatus),
@@ -67,6 +87,8 @@ const createRuntimeTRPCError = (error: unknown): TRPCError | undefined => {
// rejecting the request) pollutes server 500 monitoring.
const status = (error as { status?: unknown } | undefined)?.status;
if (typeof status === 'number' && status >= 400 && status < 500) {
+ if (options?.silentHandlerLog) markSilentTRPCErrorLog(error);
+
return new TRPCError({
cause: error,
code: getTRPCErrorCodeFromStatus(status),
@@ -129,7 +151,9 @@ export const aiChatRouter = router({
},
);
} catch (error) {
- const runtimeTRPCError = createRuntimeTRPCError(error);
+ const runtimeTRPCError = createRuntimeTRPCError(error, {
+ silentHandlerLog: input.tracing?.scenario === TRACING_SCENARIOS.InputCompletion,
+ });
if (runtimeTRPCError) throw runtimeTRPCError;
throw error;
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 177b2bc3f6e..e32d1a3477b 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -254,6 +254,10 @@
"input.costEstimate.tooltip": "Estimated from current context, tools, and model pricing. Actual cost may vary.",
"input.disclaimer": "Agents can make mistakes. Use your judgment for critical info.",
"input.errorMsg": "Send failed: {{errorMsg}}. Retry, or send again later.",
+ "input.inputCompletionError.desc": "Input suggestions stopped after an error. Retry, or adjust the suggestion model in Settings.",
+ "input.inputCompletionError.retry": "Retry",
+ "input.inputCompletionError.settings": "Settings",
+ "input.inputCompletionError.title": "Input suggestions paused",
"input.more": "More",
"input.send": "Send",
"input.sendWithCmdEnter": "Press <key/> to send",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 05e50cbff00..16d9921c8c4 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -254,6 +254,10 @@
"input.costEstimate.tooltip": "根据当前上下文、工具和模型定价估算。实际费用可能有所不同。",
"input.disclaimer": "助理也可能出错。关键信息请以你的判断为准",
"input.errorMsg": "发送遇到了问题:{{errorMsg}}。你可以重试,或稍后再发",
+ "input.inputCompletionError.desc": "输入补全遇到错误后已暂停。请重试,或到设置中调整补全模型。",
+ "input.inputCompletionError.retry": "重试",
+ "input.inputCompletionError.settings": "设置",
+ "input.inputCompletionError.title": "输入补全已暂停",
"input.more": "更多",
"input.send": "发送",
"input.sendWithCmdEnter": "按 <key/> 发送",
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index d23256a85e1..c8933c6debf 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -218,6 +218,11 @@ export default {
'Estimated from current context, tools, and model pricing. Actual cost may vary.',
'input.disclaimer': 'Agents can make mistakes. Use your judgment for critical info.',
'input.errorMsg': 'Send failed: {{errorMsg}}. Retry, or send again later.',
+ 'input.inputCompletionError.desc':
+ 'Input suggestions stopped after an error. Retry, or adjust the suggestion model in Settings.',
+ 'input.inputCompletionError.retry': 'Retry',
+ 'input.inputCompletionError.settings': 'Settings',
+ 'input.inputCompletionError.title': 'Input suggestions paused',
'input.more': 'More',
'input.send': 'Send',
'input.sendWithCmdEnter': 'Press <key/> to send',
diff --git a/src/app/(backend)/trpc/lambda/[trpc]/route.ts b/src/app/(backend)/trpc/lambda/[trpc]/route.ts
index ec176fd4e88..ebb39a0efbc 100644
--- a/src/app/(backend)/trpc/lambda/[trpc]/route.ts
+++ b/src/app/(backend)/trpc/lambda/[trpc]/route.ts
@@ -6,6 +6,15 @@ import { prepareRequestForTRPC } from '@/libs/trpc/utils/request-adapter';
import { createResponseMeta } from '@/libs/trpc/utils/responseMeta';
import { lambdaRouter } from '@/server/routers/lambda';
+const SILENT_TRPC_ERROR_LOG_KEY = '__lobeSilentTRPCErrorLog';
+
+const shouldSkipTRPCErrorLog = (cause: unknown): boolean =>
+ Boolean(
+ cause &&
+ typeof cause === 'object' &&
+ (cause as Record<string, unknown>)[SILENT_TRPC_ERROR_LOG_KEY],
+ );
+
const handler = (req: NextRequest) => {
// Clone the request to avoid "Response body object should not be disturbed or locked" error
// in Next.js 16 when the body stream has been consumed by Next.js internal mechanisms
@@ -23,6 +32,7 @@ const handler = (req: NextRequest) => {
// Filter out the error of UNAUTHORIZED, because this is normal behavior
// And it has been displayed at the front end to let the user login
if (error.code === 'UNAUTHORIZED') return;
+ if (shouldSkipTRPCErrorLog(error.cause)) return;
console.info(`Error in tRPC handler (lambda) on path: ${path}, type: ${type}`);
console.error(error);
diff --git a/src/business/client/hooks/useBusinessChatInputSendAreaPrefix.tsx b/src/business/client/hooks/useBusinessChatInputSendAreaPrefix.tsx
index 97fb8f4c678..ef5187fffa3 100644
--- a/src/business/client/hooks/useBusinessChatInputSendAreaPrefix.tsx
+++ b/src/business/client/hooks/useBusinessChatInputSendAreaPrefix.tsx
@@ -1,4 +1,8 @@
import type { ReactNode } from 'react';
-export const useBusinessChatInputSendAreaPrefix = (sendAreaPrefix?: ReactNode): ReactNode =>
+export const useBusinessChatInputCostEstimateAlert = (): ReactNode => null;
+
+export const getBusinessChatInputSendAreaPrefix = (sendAreaPrefix?: ReactNode): ReactNode =>
sendAreaPrefix;
+
+export const useBusinessChatInputSendAreaPrefix = getBusinessChatInputSendAreaPrefix;
diff --git a/src/business/client/hooks/useBusinessInputCompletionErrorAlert.tsx b/src/business/client/hooks/useBusinessInputCompletionErrorAlert.tsx
new file mode 100644
index 00000000000..f325f5ab63a
--- /dev/null
+++ b/src/business/client/hooks/useBusinessInputCompletionErrorAlert.tsx
@@ -0,0 +1,18 @@
+import type { ReactNode } from 'react';
+
+import type { InputCompletionError } from '@/features/ChatInput/store/initialState';
+
+export interface BusinessInputCompletionErrorAlertParams {
+ error?: InputCompletionError;
+ onRetry: () => void;
+}
+
+export interface BusinessInputCompletionErrorAlertResult {
+ action?: ReactNode;
+ description?: ReactNode;
+ extra?: ReactNode;
+}
+
+export const useBusinessInputCompletionErrorAlert = (
+ _params: BusinessInputCompletionErrorAlertParams,
+): BusinessInputCompletionErrorAlertResult => ({});
diff --git a/src/features/ChatInput/InputEditor/index.test.tsx b/src/features/ChatInput/InputEditor/index.test.tsx
index ed76a4ce624..295271a1779 100644
--- a/src/features/ChatInput/InputEditor/index.test.tsx
+++ b/src/features/ChatInput/InputEditor/index.test.tsx
@@ -1,5 +1,5 @@
import { render, screen } from '@testing-library/react';
-import { describe, expect, it, vi } from 'vitest';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
import InputEditor from './index';
@@ -7,19 +7,79 @@ const permission = vi.hoisted(() => ({
allowed: false,
}));
+const mocks = vi.hoisted(() => {
+ const chatInputState = {
+ clearInputCompletionError: vi.fn(() => {
+ chatInputState.inputCompletionError = undefined;
+ chatInputState.inputCompletionErrorDismissed = false;
+ }),
+ dismissInputCompletionError: vi.fn(() => {
+ chatInputState.inputCompletionErrorDismissed = true;
+ }),
+ getMessages: vi.fn(() => []),
+ inputCompletionError: undefined as { message: string } | undefined,
+ inputCompletionErrorDismissed: false,
+ pauseInputCompletion: vi.fn((error: { message: string }) => {
+ chatInputState.inputCompletionError = error;
+ chatInputState.inputCompletionErrorDismissed = false;
+ }),
+ };
+
+ return {
+ chainInputCompletion: vi.fn(),
+ chatInputState,
+ generateJSON: vi.fn(),
+ inputCompletionConfig: {
+ enabled: false,
+ model: 'gpt-4o-mini',
+ provider: 'openai',
+ },
+ recordTracingFeedback: vi.fn(),
+ };
+});
+
type StoreSelector<T = unknown> = (state: Record<PropertyKey, unknown>) => T;
-vi.mock('@lobechat/const', () => ({ isDesktop: false }));
+type AutoCompleteProps = {
+ onAutoComplete: (params: {
+ abortSignal: AbortSignal;
+ afterText: string;
+ input: string;
+ suggestionId: string;
+ }) => Promise<string | null>;
+};
+
+const getAutoCompleteProps = async (): Promise<AutoCompleteProps> => {
+ const { ReactAutoCompletePlugin } = await import('@lobehub/editor');
+ const { Editor } = await import('@lobehub/editor/react');
+ const autoCompleteCall = vi
+ .mocked(Editor.withProps)
+ .mock.calls.find(([plugin]) => plugin === ReactAutoCompletePlugin);
+ const autoCompleteProps = autoCompleteCall?.[1] as AutoCompleteProps | undefined;
+
+ expect(autoCompleteProps).toBeDefined();
+
+ return autoCompleteProps!;
+};
+
+vi.mock('@lobechat/const', () => ({
+ isDesktop: false,
+ TRACING_SCENARIOS: { InputCompletion: 'input_completion' },
+}));
vi.mock('@lobechat/const/hotkeys', () => ({
HotkeyEnum: { AddUserMessage: 'add-user-message' },
KeyEnum: { Alt: 'alt', Enter: 'enter' },
}));
vi.mock('@lobechat/heterogeneous-agents', () => ({ HETEROGENEOUS_TYPE_LABELS: {} }));
vi.mock('@lobechat/prompts', () => ({
- chainInputCompletion: vi.fn(),
+ chainInputCompletion: mocks.chainInputCompletion,
escapeXmlAttr: (value: string) => value,
+ INPUT_COMPLETION_PROMPT_VERSION: 'v1',
+ INPUT_COMPLETION_SCHEMA_NAME: 'InputCompletion',
}));
vi.mock('@lobechat/utils', () => ({
+ isRecord: (value: unknown): value is Record<PropertyKey, unknown> =>
+ Boolean(value) && typeof value === 'object' && !Array.isArray(value),
isCommandPressed: vi.fn(() => false),
merge: vi.fn((...args) => Object.assign({}, ...args)),
}));
@@ -78,7 +138,12 @@ vi.mock('@/hooks/usePermission', () => ({
usePermission: () => ({ allowed: permission.allowed, reason: '' }),
}));
vi.mock('@/services/chat', () => ({ chatService: { fetchPresetTaskResult: vi.fn() } }));
-vi.mock('@/services/aiChat', () => ({ aiChatService: new Proxy({}, { get: () => vi.fn() }) }));
+vi.mock('@/services/aiChat', () => ({
+ aiChatService: {
+ generateJSON: mocks.generateJSON,
+ recordTracingFeedback: mocks.recordTracingFeedback,
+ },
+}));
vi.mock('@/store/chat', () => ({
useChatStore: Object.assign(<T,>(selector: StoreSelector<T>) => selector({}), {
getState: () => ({ activeTopicId: undefined }),
@@ -108,7 +173,7 @@ vi.mock('@/store/user/selectors', () => ({
labPreferSelectors: { enableInputMarkdown: () => false },
settingsSelectors: { getHotkeyById: () => () => 'alt+enter' },
systemAgentSelectors: {
- inputCompletion: () => ({ enabled: false }),
+ inputCompletion: () => mocks.inputCompletionConfig,
},
}));
@@ -131,7 +196,7 @@ vi.mock('../store', () => {
return {
useChatInputStore: <T,>(selector: StoreSelector<T>) => selector(state),
useStoreApi: () => ({
- getState: () => ({ getMessages: vi.fn() }),
+ getState: () => mocks.chatInputState,
subscribe: vi.fn(() => vi.fn()),
}),
};
@@ -158,11 +223,104 @@ vi.mock('./useLocalFileMention', () => ({
vi.mock('./useMentionCategories', () => ({ useMentionCategories: () => [] }));
describe('ChatInput InputEditor', () => {
- it('renders as read-only when create-content permission is denied', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
permission.allowed = false;
+ mocks.inputCompletionConfig.enabled = false;
+ mocks.inputCompletionConfig.model = 'gpt-4o-mini';
+ mocks.inputCompletionConfig.provider = 'openai';
+ mocks.chatInputState.inputCompletionError = undefined;
+ mocks.chatInputState.inputCompletionErrorDismissed = false;
+ mocks.chainInputCompletion.mockReturnValue({
+ messages: [],
+ schema: {
+ name: 'InputCompletion',
+ schema: { type: 'object' },
+ },
+ });
+ });
+ it('renders as read-only when create-content permission is denied', () => {
render(<InputEditor />);
expect(screen.getByTestId('mock-editor')).toHaveAttribute('data-editable', 'false');
});
+
+ it('pauses autocomplete after a non-abort generation error', async () => {
+ permission.allowed = true;
+ mocks.inputCompletionConfig.enabled = true;
+ mocks.generateJSON.mockRejectedValueOnce(new Error('InsufficientBudgetForModel'));
+
+ render(<InputEditor />);
+
+ const autoCompleteProps = await getAutoCompleteProps();
+
+ const abortController = new AbortController();
+ await expect(
+ autoCompleteProps.onAutoComplete({
+ abortSignal: abortController.signal,
+ afterText: '',
+ input: 'hello',
+ suggestionId: 'suggestion-1',
+ }),
+ ).resolves.toBeNull();
+
+ expect(mocks.generateJSON).toHaveBeenCalledTimes(1);
+ expect(mocks.chatInputState.inputCompletionError?.message).toBe('InsufficientBudgetForModel');
+
+ await expect(
+ autoCompleteProps.onAutoComplete({
+ abortSignal: abortController.signal,
+ afterText: '',
+ input: 'hello again',
+ suggestionId: 'suggestion-2',
+ }),
+ ).resolves.toBeNull();
+
+ expect(mocks.generateJSON).toHaveBeenCalledTimes(1);
+ });
+
+ it('keeps autocomplete paused when an older in-flight request resolves after a failure', async () => {
+ permission.allowed = true;
+ mocks.inputCompletionConfig.enabled = true;
+
+ let resolveOlderRequest!: (value: { data: { completion: string } }) => void;
+ mocks.generateJSON
+ .mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ resolveOlderRequest = resolve;
+ }),
+ )
+ .mockRejectedValueOnce(new Error('InsufficientBudgetForModel'));
+
+ render(<InputEditor />);
+
+ const autoCompleteProps = await getAutoCompleteProps();
+ const olderAbortController = new AbortController();
+ const newerAbortController = new AbortController();
+
+ const olderCompletion = autoCompleteProps.onAutoComplete({
+ abortSignal: olderAbortController.signal,
+ afterText: '',
+ input: 'older request',
+ suggestionId: 'suggestion-1',
+ });
+
+ await expect(
+ autoCompleteProps.onAutoComplete({
+ abortSignal: newerAbortController.signal,
+ afterText: '',
+ input: 'newer request',
+ suggestionId: 'suggestion-2',
+ }),
+ ).resolves.toBeNull();
+
+ expect(mocks.chatInputState.inputCompletionError?.message).toBe('InsufficientBudgetForModel');
+
+ resolveOlderRequest({ data: { completion: 'older completion' } });
+
+ await expect(olderCompletion).resolves.toBeNull();
+ expect(mocks.chatInputState.inputCompletionError?.message).toBe('InsufficientBudgetForModel');
+ });
});
diff --git a/src/features/ChatInput/InputEditor/index.tsx b/src/features/ChatInput/InputEditor/index.tsx
index d9cdc69020f..ed9c1df806b 100644
--- a/src/features/ChatInput/InputEditor/index.tsx
+++ b/src/features/ChatInput/InputEditor/index.tsx
@@ -41,6 +41,7 @@ import {
type InsertActionTagPayload,
useSlashActionItems,
} from './ActionTag';
+import { createInputCompletionError, isInputCompletionAbortError } from './inputCompletionError';
import { createMentionMenu } from './MentionMenu';
import type { MentionMenuState } from './MentionMenu/types';
import { mentionFilledClassName } from './mentionStyle';
@@ -193,6 +194,10 @@ const InputEditor = memo<{
const inputCompletionConfig = useUserStore(systemAgentSelectors.inputCompletion);
const isAutoCompleteEnabled = isInputCompletionEnabled && inputCompletionConfig.enabled;
+ useEffect(() => {
+ storeApi.getState().clearInputCompletionError();
+ }, [inputCompletionConfig.model, inputCompletionConfig.provider, storeApi]);
+
const getMessagesRef = useRef(storeApi.getState().getMessages);
useEffect(() => {
return storeApi.subscribe((s) => {
@@ -223,6 +228,8 @@ const InputEditor = memo<{
// Skip autocomplete during IME composition (e.g. Chinese input method)
if (isComposingRef.current) return null;
+ if (storeApi.getState().inputCompletionError) return null;
+
if (!input.trim()) return null;
// Skip when cursor is not at end of paragraph — inserting a placeholder
@@ -260,12 +267,19 @@ const InputEditor = memo<{
},
abortController,
)) as { data?: { completion?: string } | null; tracingId?: string } | null;
- } catch {
+ } catch (error) {
+ if (!isInputCompletionAbortError(error)) {
+ storeApi.getState().pauseInputCompletion(createInputCompletionError(error));
+ }
return null;
}
if (abortSignal.aborted) return null;
+ // Another in-flight request may have failed while this one was waiting.
+ // Keep the breaker active and drop this stale suggestion in that race.
+ if (storeApi.getState().inputCompletionError) return null;
+
const completion = envelope?.data?.completion?.trimEnd();
if (!completion) return null;
@@ -274,7 +288,7 @@ const InputEditor = memo<{
}
return completion;
},
- [isComposingRef, agentId],
+ [isComposingRef, storeApi, agentId],
);
const handleSuggestionAccepted = useCallback(
diff --git a/src/features/ChatInput/InputEditor/inputCompletionError.test.ts b/src/features/ChatInput/InputEditor/inputCompletionError.test.ts
new file mode 100644
index 00000000000..fe3da818e27
--- /dev/null
+++ b/src/features/ChatInput/InputEditor/inputCompletionError.test.ts
@@ -0,0 +1,45 @@
+import { describe, expect, it } from 'vitest';
+
+import { createInputCompletionError, isInputCompletionAbortError } from './inputCompletionError';
+
+describe('inputCompletionError', () => {
+ describe('isInputCompletionAbortError', () => {
+ it('treats AbortError as a cancelled autocomplete request', () => {
+ expect(
+ isInputCompletionAbortError({ message: 'The operation was aborted', name: 'AbortError' }),
+ ).toBe(true);
+ });
+
+ it('treats nested AbortError as a cancelled autocomplete request', () => {
+ expect(
+ isInputCompletionAbortError({
+ cause: { message: 'signal is aborted without reason', name: 'AbortError' },
+ message: 'TRPC request failed',
+ }),
+ ).toBe(true);
+ });
+
+ it('does not treat regular failures as cancellation', () => {
+ expect(isInputCompletionAbortError(new Error('InsufficientBudgetForModel'))).toBe(false);
+ });
+ });
+
+ describe('createInputCompletionError', () => {
+ it('extracts tRPC error metadata for the paused alert', () => {
+ expect(
+ createInputCompletionError({
+ data: {
+ errorData: { budget: { requiredCredits: 10 }, errorType: 'InsufficientBudgetForModel' },
+ httpStatus: 402,
+ },
+ message: 'Insufficient budget for model',
+ }),
+ ).toEqual({
+ body: { budget: { requiredCredits: 10 }, errorType: 'InsufficientBudgetForModel' },
+ errorType: 'InsufficientBudgetForModel',
+ httpStatus: 402,
+ message: 'Insufficient budget for model',
+ });
+ });
+ });
+});
diff --git a/src/features/ChatInput/InputEditor/inputCompletionError.ts b/src/features/ChatInput/InputEditor/inputCompletionError.ts
new file mode 100644
index 00000000000..be955c624ef
--- /dev/null
+++ b/src/features/ChatInput/InputEditor/inputCompletionError.ts
@@ -0,0 +1,51 @@
+import { isRecord } from '@lobechat/utils';
+
+import type { InputCompletionError } from '../store/initialState';
+
+const getRecordField = (record: Record<PropertyKey, unknown> | undefined, key: string) => {
+ const value = record?.[key];
+ return isRecord(value) ? value : undefined;
+};
+
+const getStringField = (record: Record<PropertyKey, unknown> | undefined, key: string) => {
+ const value = record?.[key];
+ return typeof value === 'string' ? value : undefined;
+};
+
+const getNumberField = (record: Record<PropertyKey, unknown> | undefined, key: string) => {
+ const value = record?.[key];
+ return typeof value === 'number' ? value : undefined;
+};
+
+export const isInputCompletionAbortError = (error: unknown): boolean => {
+ const record = isRecord(error) ? error : undefined;
+ const cause = getRecordField(record, 'cause');
+ const message = getStringField(record, 'message') ?? '';
+ const causeMessage = getStringField(cause, 'message') ?? '';
+ const normalizedMessage = `${message} ${causeMessage}`.toLowerCase();
+
+ return (
+ getStringField(record, 'name') === 'AbortError' ||
+ getStringField(cause, 'name') === 'AbortError' ||
+ normalizedMessage.includes('aborted') ||
+ normalizedMessage.includes('aborterror') ||
+ normalizedMessage.includes('signal is aborted without reason')
+ );
+};
+
+export const createInputCompletionError = (error: unknown): InputCompletionError => {
+ const record = isRecord(error) ? error : undefined;
+ const data = getRecordField(record, 'data');
+ const errorData = getRecordField(data, 'errorData');
+ const message = getStringField(record, 'message') ?? 'Input completion failed';
+
+ return {
+ body: errorData,
+ errorType:
+ getStringField(errorData, 'errorType') ??
+ getStringField(data, 'code') ??
+ getStringField(record, 'message'),
+ httpStatus: getNumberField(data, 'httpStatus'),
+ message,
+ };
+};
diff --git a/src/features/ChatInput/store/action.test.ts b/src/features/ChatInput/store/action.test.ts
new file mode 100644
index 00000000000..c6c51e8a6da
--- /dev/null
+++ b/src/features/ChatInput/store/action.test.ts
@@ -0,0 +1,19 @@
+import { describe, expect, it } from 'vitest';
+
+import { createStore, selectors } from '.';
+
+describe('ChatInput store actions', () => {
+ it('clears the autocomplete breaker when dismissing its error', () => {
+ const store = createStore();
+
+ store.getState().pauseInputCompletion({ message: 'InsufficientBudgetForModel' });
+
+ expect(selectors.inputCompletionPaused(store.getState())).toBe(true);
+
+ store.getState().dismissInputCompletionError();
+
+ expect(store.getState().inputCompletionError).toBeUndefined();
+ expect(selectors.inputCompletionPaused(store.getState())).toBe(false);
+ expect(selectors.inputCompletionErrorVisible(store.getState())).toBeUndefined();
+ });
+});
diff --git a/src/features/ChatInput/store/action.ts b/src/features/ChatInput/store/action.ts
index 692429c69c5..5ae771ab0d1 100644
--- a/src/features/ChatInput/store/action.ts
+++ b/src/features/ChatInput/store/action.ts
@@ -5,10 +5,13 @@ import { type PublicState, type State } from './initialState';
import { initialState } from './initialState';
export interface Action {
+ clearInputCompletionError: () => void;
+ dismissInputCompletionError: () => void;
getJSONState: () => Record<string, any> | undefined;
getMarkdownContent: () => string;
handleSendButton: () => void;
handleStop: () => void;
+ pauseInputCompletion: (error: State['inputCompletionError']) => void;
setDocument: (type: string, content: any, options?: Record<string, unknown>) => void;
setExpand: (expend: boolean) => void;
setJSONState: (content: any) => void;
@@ -26,6 +29,14 @@ export const store: CreateStore = (publicState) => (set, get) => ({
...initialState,
...publicState,
+ clearInputCompletionError: () => {
+ set({ inputCompletionError: undefined, inputCompletionErrorDismissed: false });
+ },
+
+ dismissInputCompletionError: () => {
+ set({ inputCompletionError: undefined, inputCompletionErrorDismissed: false });
+ },
+
getJSONState: () => {
return get().editor?.getDocument('json') as Record<string, any> | undefined;
},
@@ -63,6 +74,10 @@ export const store: CreateStore = (publicState) => (set, get) => ({
get().sendButtonProps?.onStop?.({ editor: get().editor! });
},
+ pauseInputCompletion: (inputCompletionError) => {
+ set({ inputCompletionError, inputCompletionErrorDismissed: false });
+ },
+
setDocument: (type, content, options) => {
get().editor?.setDocument(type, content, options);
},
diff --git a/src/features/ChatInput/store/initialState.ts b/src/features/ChatInput/store/initialState.ts
index 407b2a6e923..8545535af1a 100644
--- a/src/features/ChatInput/store/initialState.ts
+++ b/src/features/ChatInput/store/initialState.ts
@@ -38,6 +38,13 @@ export interface ChatInputFeature {
slash?: boolean;
}
+export interface InputCompletionError {
+ body?: unknown;
+ errorType?: string;
+ httpStatus?: number;
+ message: string;
+}
+
export const DEFAULT_CHAT_INPUT_FEATURE = {
inputCompletion: true,
mention: true,
@@ -70,6 +77,8 @@ export interface PublicState {
export interface State extends PublicState {
_savedEditorState?: Record<string, any>;
editor?: IEditor;
+ inputCompletionError?: InputCompletionError;
+ inputCompletionErrorDismissed: boolean;
isContentEmpty: boolean;
markdownContent: string;
slashMenuRef: ChatInputProps['slashMenuRef'];
@@ -79,6 +88,7 @@ export const initialState: State = {
allowExpand: true,
expand: false,
feature: DEFAULT_CHAT_INPUT_FEATURE,
+ inputCompletionErrorDismissed: false,
isContentEmpty: false,
leftActions: [],
markdownContent: '',
diff --git a/src/features/ChatInput/store/selectors.ts b/src/features/ChatInput/store/selectors.ts
index be04aa16202..5482790fe7e 100644
--- a/src/features/ChatInput/store/selectors.ts
+++ b/src/features/ChatInput/store/selectors.ts
@@ -1,6 +1,10 @@
-import { type SendButtonProps, type State } from './initialState';
+import { type InputCompletionError, type SendButtonProps, type State } from './initialState';
import { initialSendButtonState } from './initialState';
export const selectors = {
+ inputCompletionError: (s: State): InputCompletionError | undefined => s.inputCompletionError,
+ inputCompletionErrorVisible: (s: State): InputCompletionError | undefined =>
+ s.inputCompletionErrorDismissed ? undefined : s.inputCompletionError,
+ inputCompletionPaused: (s: State): boolean => Boolean(s.inputCompletionError),
sendButtonProps: (s: State): SendButtonProps => s.sendButtonProps || initialSendButtonState,
};
diff --git a/src/features/Conversation/ChatInput/index.tsx b/src/features/Conversation/ChatInput/index.tsx
index c39d8957158..86cf0c76daf 100644
--- a/src/features/Conversation/ChatInput/index.tsx
+++ b/src/features/Conversation/ChatInput/index.tsx
@@ -2,16 +2,22 @@
import { type SlashOptions } from '@lobehub/editor';
import { type ChatInputActionsProps } from '@lobehub/editor/react';
-import { type MenuProps } from '@lobehub/ui';
-import { Alert, Flexbox } from '@lobehub/ui';
+import { Alert, Button, Flexbox, type MenuProps } from '@lobehub/ui';
import { type ReactNode } from 'react';
import { memo, useCallback, useEffect, useMemo, useRef } from 'react';
import { useTranslation } from 'react-i18next';
+import { Link } from 'react-router-dom';
-import { useBusinessChatInputSendAreaPrefix } from '@/business/client/hooks/useBusinessChatInputSendAreaPrefix';
+import {
+ getBusinessChatInputSendAreaPrefix,
+ useBusinessChatInputCostEstimateAlert,
+} from '@/business/client/hooks/useBusinessChatInputSendAreaPrefix';
+import { useBusinessInputCompletionErrorAlert } from '@/business/client/hooks/useBusinessInputCompletionErrorAlert';
import type { ActionKeys, ChatInputFeature } from '@/features/ChatInput';
import { ChatInputProvider, DesktopChatInput } from '@/features/ChatInput';
+import { selectors as chatInputSelectors, useChatInputStore } from '@/features/ChatInput/store';
import {
+ type InputCompletionError,
type SendButtonHandler,
type SendButtonProps,
} from '@/features/ChatInput/store/initialState';
@@ -38,6 +44,55 @@ const toChatInputMessages = (messages: ReturnType<typeof dataSelectors.dbMessage
role: m.role as 'user' | 'assistant' | 'system',
}));
+const InputCompletionErrorAlertContent = memo<{
+ inputCompletionError: InputCompletionError;
+}>(({ inputCompletionError }) => {
+ const { t } = useTranslation('chat');
+ const clearInputCompletionError = useChatInputStore((s) => s.clearInputCompletionError);
+ const businessAlert = useBusinessInputCompletionErrorAlert({
+ error: inputCompletionError,
+ onRetry: clearInputCompletionError,
+ });
+
+ const action = businessAlert.action ?? (
+ <Flexbox horizontal align={'center'} gap={8} wrap={'wrap'}>
+ <Button size={'small'} type={'primary'} onClick={clearInputCompletionError}>
+ {t('input.inputCompletionError.retry')}
+ </Button>
+ <Link to={'/settings/agent'}>
+ <Button size={'small'}>{t('input.inputCompletionError.settings')}</Button>
+ </Link>
+ </Flexbox>
+ );
+
+ return (
+ <>
+ <Flexbox paddingBlock={'0 6px'} paddingInline={12}>
+ <Alert
+ showIcon
+ action={action}
+ description={businessAlert.description ?? t('input.inputCompletionError.desc')}
+ title={t('input.inputCompletionError.title')}
+ type={'warning'}
+ />
+ </Flexbox>
+ {businessAlert.extra}
+ </>
+ );
+});
+
+InputCompletionErrorAlertContent.displayName = 'InputCompletionErrorAlertContent';
+
+const InputCompletionErrorAlert = memo(() => {
+ const inputCompletionError = useChatInputStore(chatInputSelectors.inputCompletionErrorVisible);
+
+ if (!inputCompletionError) return null;
+
+ return <InputCompletionErrorAlertContent inputCompletionError={inputCompletionError} />;
+});
+
+InputCompletionErrorAlert.displayName = 'InputCompletionErrorAlert';
+
export interface ChatInputProps {
/**
* Custom style for the action bar container
@@ -232,7 +287,8 @@ const ChatInput = memo<ChatInputProps>(
// When disableQueue is set (e.g. onboarding), block sending while loading.
const disabled = isInputEmpty || isUploadingFiles || (!!disableQueue && isInputLoading);
const shouldUsePlainSendButton = !showSendMenu && !!sendMenu;
- const businessSendAreaPrefix = useBusinessChatInputSendAreaPrefix(sendAreaPrefix);
+ const businessCostEstimateAlert = useBusinessChatInputCostEstimateAlert();
+ const businessSendAreaPrefix = getBusinessChatInputSendAreaPrefix(sendAreaPrefix);
// Send handler - gets message, clears editor immediately, then sends
const handleSend: SendButtonHandler = useCallback(
@@ -304,6 +360,8 @@ const ChatInput = memo<ChatInputProps>(
/>
</Flexbox>
)}
+ <InputCompletionErrorAlert />
+ {businessCostEstimateAlert}
<Flexbox
paddingInline={12}
ref={overlayRef}