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(editor): implement AI input auto-completion (#13458)

Arvin Xu251e12c7d1bd
diff --git a/locales/en-US/setting.json b/locales/en-US/setting.json
index 363cafe0f18..1f0937dabec 100644
--- a/locales/en-US/setting.json
+++ b/locales/en-US/setting.json
@@ -768,6 +768,9 @@
"systemAgent.historyCompress.label": "Model",
"systemAgent.historyCompress.modelDesc": "Specify the model used to compress conversation history",
"systemAgent.historyCompress.title": "Conversation History Compression Agent",
+ "systemAgent.inputCompletion.label": "Model",
+ "systemAgent.inputCompletion.modelDesc": "Model used for input auto-completion suggestions (like GitHub Copilot ghost text)",
+ "systemAgent.inputCompletion.title": "Input Auto-Completion Agent",
"systemAgent.queryRewrite.label": "Model",
"systemAgent.queryRewrite.modelDesc": "Specify the model used to optimize user inquiries",
"systemAgent.queryRewrite.title": "Library query rewrite Agent",
diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.json
index 533bc266329..ee3798abe4d 100644
--- a/locales/zh-CN/setting.json
+++ b/locales/zh-CN/setting.json
@@ -768,6 +768,9 @@
"systemAgent.historyCompress.label": "模型",
"systemAgent.historyCompress.modelDesc": "指定用于压缩会话历史的模型",
"systemAgent.historyCompress.title": "会话历史压缩助理",
+ "systemAgent.inputCompletion.label": "模型",
+ "systemAgent.inputCompletion.modelDesc": "指定用于输入自动补全建议的模型(类似 GitHub Copilot 幽灵文本)",
+ "systemAgent.inputCompletion.title": "输入自动补全助理",
"systemAgent.queryRewrite.label": "模型",
"systemAgent.queryRewrite.modelDesc": "指定用于优化用户提问的模型",
"systemAgent.queryRewrite.title": "资源库提问重写助理",
diff --git a/packages/const/src/settings/systemAgent.ts b/packages/const/src/settings/systemAgent.ts
index f8a864423a0..dbc98d2a7aa 100644
--- a/packages/const/src/settings/systemAgent.ts
+++ b/packages/const/src/settings/systemAgent.ts
@@ -23,10 +23,17 @@ export const DEFAULT_QUERY_REWRITE_SYSTEM_AGENT_ITEM: QueryRewriteSystemAgent =
provider: DEFAULT_MINI_SYSTEM_AGENT_ITEM.provider,
};
+export const DEFAULT_INPUT_COMPLETION_SYSTEM_AGENT_ITEM: SystemAgentItem = {
+ enabled: true,
+ model: DEFAULT_MINI_SYSTEM_AGENT_ITEM.model,
+ provider: DEFAULT_MINI_SYSTEM_AGENT_ITEM.provider,
+};
+
export const DEFAULT_SYSTEM_AGENT_CONFIG: UserSystemAgentConfig = {
agentMeta: DEFAULT_SYSTEM_AGENT_ITEM,
generationTopic: DEFAULT_MINI_SYSTEM_AGENT_ITEM,
historyCompress: DEFAULT_SYSTEM_AGENT_ITEM,
+ inputCompletion: DEFAULT_INPUT_COMPLETION_SYSTEM_AGENT_ITEM,
queryRewrite: DEFAULT_QUERY_REWRITE_SYSTEM_AGENT_ITEM,
thread: DEFAULT_SYSTEM_AGENT_ITEM,
topic: DEFAULT_MINI_SYSTEM_AGENT_ITEM,
diff --git a/packages/prompts/src/chains/index.ts b/packages/prompts/src/chains/index.ts
index dbfa25f333c..8efe8751161 100644
--- a/packages/prompts/src/chains/index.ts
+++ b/packages/prompts/src/chains/index.ts
@@ -1,6 +1,7 @@
export * from './abstractChunk';
export * from './answerWithContext';
export * from './compressContext';
+export * from './inputCompletion';
export * from './langDetect';
export * from './pickEmoji';
export * from './rewriteQuery';
diff --git a/packages/prompts/src/chains/inputCompletion.ts b/packages/prompts/src/chains/inputCompletion.ts
new file mode 100644
index 00000000000..bd4168c1692
--- /dev/null
+++ b/packages/prompts/src/chains/inputCompletion.ts
@@ -0,0 +1,37 @@
+import type { ChatStreamPayload, OpenAIChatMessage } from '@lobechat/types';
+
+export const chainInputCompletion = (
+ beforeCursor: string,
+ afterCursor: string,
+ context?: OpenAIChatMessage[],
+): Partial<ChatStreamPayload> => {
+ let contextBlock = '';
+ if (context?.length) {
+ contextBlock = `\n\nCurrent conversation context:
+${context.map((m) => `${m.role}: ${m.content}`).join('\n')}`;
+ }
+
+ return {
+ max_tokens: 100,
+ messages: [
+ {
+ content: `Complete the user's partially typed message. Output ONLY the missing text to insert at the cursor. Keep it short and natural. No explanations.
+
+Examples of expected behavior:
+User: Before cursor: "How do I " / After cursor: ""
+Output: implement authentication in Next.js?
+
+User: Before cursor: "Can you explain the difference between " / After cursor: ""
+Output: useEffect and useLayoutEffect in React?
+
+User: Before cursor: "我想了解一下" / After cursor: ""
+Output: 如何在项目中使用 TypeScript 的泛型${contextBlock}`,
+ role: 'system',
+ },
+ {
+ content: `Before cursor: "${beforeCursor}"\nAfter cursor: "${afterCursor}"`,
+ role: 'user',
+ },
+ ],
+ };
+};
diff --git a/packages/types/src/user/settings/systemAgent.ts b/packages/types/src/user/settings/systemAgent.ts
index 759f09362c8..b95bbe47888 100644
--- a/packages/types/src/user/settings/systemAgent.ts
+++ b/packages/types/src/user/settings/systemAgent.ts
@@ -13,6 +13,7 @@ export interface UserSystemAgentConfig {
agentMeta: SystemAgentItem;
generationTopic: SystemAgentItem;
historyCompress: SystemAgentItem;
+ inputCompletion: SystemAgentItem;
queryRewrite: QueryRewriteSystemAgent;
thread: SystemAgentItem;
topic: SystemAgentItem;
diff --git a/src/features/ChatInput/ChatInputProvider.tsx b/src/features/ChatInput/ChatInputProvider.tsx
index d8742b75a03..3c38244476c 100644
--- a/src/features/ChatInput/ChatInputProvider.tsx
+++ b/src/features/ChatInput/ChatInputProvider.tsx
@@ -25,6 +25,7 @@ export const ChatInputProvider = memo<ChatInputProviderProps>(
mentionItems,
allowExpand = true,
slashPlacement,
+ getMessages,
}) => {
const editor = useEditor();
const slashMenuRef = useRef<HTMLDivElement>(null);
@@ -50,6 +51,7 @@ export const ChatInputProvider = memo<ChatInputProviderProps>(
agentId={agentId}
allowExpand={allowExpand}
chatInputEditorRef={chatInputEditorRef}
+ getMessages={getMessages}
leftActions={leftActions}
mentionItems={mentionItems}
mobile={mobile}
diff --git a/src/features/ChatInput/InputEditor/index.tsx b/src/features/ChatInput/InputEditor/index.tsx
index e55378f8775..8c330599452 100644
--- a/src/features/ChatInput/InputEditor/index.tsx
+++ b/src/features/ChatInput/InputEditor/index.tsx
@@ -1,7 +1,8 @@
import { isDesktop } from '@lobechat/const';
+import { chainInputCompletion } from '@lobechat/prompts';
import { HotkeyEnum, KeyEnum } from '@lobechat/types';
-import { isCommandPressed } from '@lobechat/utils';
-import { INSERT_MENTION_COMMAND, ReactMathPlugin } from '@lobehub/editor';
+import { isCommandPressed, merge } from '@lobechat/utils';
+import { INSERT_MENTION_COMMAND, ReactAutoCompletePlugin, ReactMathPlugin } from '@lobehub/editor';
import { Editor, FloatMenu, useEditorState } from '@lobehub/editor/react';
import { combineKeys } from '@lobehub/ui';
import { css, cx } from 'antd-style';
@@ -11,10 +12,16 @@ import { useHotkeysContext } from 'react-hotkeys-hook';
import { usePasteFile, useUploadFiles } from '@/components/DragUploadZone';
import { useIMECompositionEvent } from '@/hooks/useIMECompositionEvent';
+import { chatService } from '@/services/chat';
import { useAgentStore } from '@/store/agent';
import { agentByIdSelectors } from '@/store/agent/selectors';
import { useUserStore } from '@/store/user';
-import { labPreferSelectors, preferenceSelectors, settingsSelectors } from '@/store/user/selectors';
+import {
+ labPreferSelectors,
+ preferenceSelectors,
+ settingsSelectors,
+ systemAgentSelectors,
+} from '@/store/user/selectors';
import { useAgentId } from '../hooks/useAgentId';
import { useChatInputStore, useStoreApi } from '../store';
@@ -125,31 +132,94 @@ const InputEditor = memo<{ defaultRows?: number }>(({ defaultRows = 2 }) => {
[slashActionItems],
);
- const richRenderProps = useMemo(
- () =>
- !enableRichRender
- ? {
- enablePasteMarkdown: false,
- markdownOption: false,
- plugins: CHAT_INPUT_EMBED_PLUGINS,
- }
- : {
- plugins: createChatInputRichPlugins({
- mathPlugin: Editor.withProps(ReactMathPlugin, {
- renderComp: expand
- ? undefined
- : (props) => (
- <FloatMenu
- {...props}
- getPopupContainer={() => (slashMenuRef as any)?.current}
- />
- ),
- }),
- }),
+ // --- Auto-completion ---
+ const inputCompletionConfig = useUserStore(systemAgentSelectors.inputCompletion);
+ const isAutoCompleteEnabled = inputCompletionConfig.enabled;
+
+ const getMessagesRef = useRef(storeApi.getState().getMessages);
+ useEffect(() => {
+ return storeApi.subscribe((s) => {
+ getMessagesRef.current = s.getMessages;
+ });
+ }, [storeApi]);
+
+ const handleAutoComplete = useCallback(
+ async ({
+ abortSignal,
+ afterText,
+ input,
+ }: {
+ abortSignal: AbortSignal;
+ afterText: string;
+ editor: any;
+ input: string;
+ selectionType: string;
+ }): Promise<string | null> => {
+ if (!input.trim()) return null;
+
+ const { enabled: _, ...config } = systemAgentSelectors.inputCompletion(
+ useUserStore.getState(),
+ );
+ const context = getMessagesRef.current?.();
+ const chainParams = chainInputCompletion(input, afterText, context);
+
+ const abortController = new AbortController();
+ abortSignal.addEventListener('abort', () => abortController.abort());
+
+ let result = '';
+
+ try {
+ await chatService.fetchPresetTaskResult({
+ abortController,
+ onMessageHandle: (chunk) => {
+ if (chunk.type === 'text') {
+ result += chunk.text;
+ }
},
- [enableRichRender, expand, slashMenuRef],
+ params: merge(config, chainParams),
+ });
+ } catch {
+ return null;
+ }
+
+ if (abortSignal.aborted) return null;
+
+ return result || null;
+ },
+ [],
+ );
+
+ const autoCompletePlugin = useMemo(
+ () =>
+ isAutoCompleteEnabled
+ ? Editor.withProps(ReactAutoCompletePlugin, {
+ delay: 600,
+ onAutoComplete: handleAutoComplete,
+ })
+ : null,
+ [isAutoCompleteEnabled, handleAutoComplete],
);
+ const richRenderProps = useMemo(() => {
+ const basePlugins = !enableRichRender
+ ? CHAT_INPUT_EMBED_PLUGINS
+ : createChatInputRichPlugins({
+ mathPlugin: Editor.withProps(ReactMathPlugin, {
+ renderComp: expand
+ ? undefined
+ : (props) => (
+ <FloatMenu {...props} getPopupContainer={() => (slashMenuRef as any)?.current} />
+ ),
+ }),
+ });
+
+ const plugins = autoCompletePlugin ? [...basePlugins, autoCompletePlugin] : basePlugins;
+
+ return !enableRichRender
+ ? { enablePasteMarkdown: false, markdownOption: false, plugins }
+ : { plugins };
+ }, [enableRichRender, expand, slashMenuRef, autoCompletePlugin]);
+
return (
<Editor
autoFocus
diff --git a/src/features/ChatInput/StoreUpdater.tsx b/src/features/ChatInput/StoreUpdater.tsx
index ef4d7414251..4a5258c0643 100644
--- a/src/features/ChatInput/StoreUpdater.tsx
+++ b/src/features/ChatInput/StoreUpdater.tsx
@@ -27,6 +27,7 @@ const StoreUpdater = memo<StoreUpdaterProps>(
mentionItems,
allowExpand,
slashPlacement,
+ getMessages,
}) => {
const storeApi = useStoreApi();
const useStoreUpdater = createStoreUpdater(storeApi);
@@ -40,6 +41,7 @@ const StoreUpdater = memo<StoreUpdaterProps>(
useStoreUpdater('rightActions', rightActions!);
useStoreUpdater('allowExpand', allowExpand);
useStoreUpdater('slashPlacement', slashPlacement);
+ useStoreUpdater('getMessages', getMessages);
useStoreUpdater('sendButtonProps', sendButtonProps);
useStoreUpdater('onSend', onSend);
diff --git a/src/features/ChatInput/store/initialState.ts b/src/features/ChatInput/store/initialState.ts
index 9ad7d9e25b9..97878357544 100644
--- a/src/features/ChatInput/store/initialState.ts
+++ b/src/features/ChatInput/store/initialState.ts
@@ -1,3 +1,4 @@
+import { type OpenAIChatMessage } from '@lobechat/types';
import { type IEditor, type SlashOptions } from '@lobehub/editor';
import { type ChatInputProps } from '@lobehub/editor/react';
import { type MenuProps } from '@lobehub/ui';
@@ -31,6 +32,7 @@ export interface PublicState {
agentId?: string;
allowExpand?: boolean;
expand?: boolean;
+ getMessages?: () => OpenAIChatMessage[];
leftActions: ActionKeys[];
mentionItems?: SlashOptions['items'];
mobile?: boolean;
diff --git a/src/features/Conversation/ChatInput/index.tsx b/src/features/Conversation/ChatInput/index.tsx
index 795daf6c57b..fc71ea75fa7 100644
--- a/src/features/Conversation/ChatInput/index.tsx
+++ b/src/features/Conversation/ChatInput/index.tsx
@@ -20,9 +20,33 @@ import { fileChatSelectors, useFileStore } from '@/store/file';
import WideScreenContainer from '../../WideScreenContainer';
import InterventionBar from '../InterventionBar';
-import { dataSelectors, messageStateSelectors, useConversationStore } from '../store';
+import {
+ dataSelectors,
+ messageStateSelectors,
+ useConversationStore,
+ useConversationStoreApi,
+} from '../store';
import QueueTray from './QueueTray';
+/** Max recent messages to feed into auto-complete context (≈10 conversation turns) */
+const MAX_CONTEXT_MESSAGES = 25;
+
+const useGetMessages = () => {
+ const storeApi = useConversationStoreApi();
+ return useCallback(
+ () =>
+ dataSelectors
+ .dbMessages(storeApi.getState())
+ .filter((m) => m.role === 'user' || m.role === 'assistant' || m.role === 'tool')
+ .slice(-MAX_CONTEXT_MESSAGES)
+ .map((m) => ({
+ content: typeof m.content === 'string' ? m.content : '',
+ role: m.role as 'user' | 'assistant' | 'system',
+ })),
+ [storeApi],
+ );
+};
+
export interface ChatInputProps {
/**
* Custom style for the action bar container
@@ -108,6 +132,8 @@ const ChatInput = memo<ChatInputProps>(
}) => {
const { t } = useTranslation('chat');
+ const getMessages = useGetMessages();
+
// ConversationStore state
const context = useConversationStore((s) => s.context);
const [agentId, inputMessage, sendMessage, stopGenerating] = useConversationStore((s) => [
@@ -249,6 +275,7 @@ const ChatInput = memo<ChatInputProps>(
<ChatInputProvider
agentId={agentId}
allowExpand={allowExpand}
+ getMessages={getMessages}
leftActions={leftActions}
mentionItems={mentionItems}
rightActions={rightActions}
diff --git a/src/locales/default/setting.ts b/src/locales/default/setting.ts
index b4dfc7fd81b..3dc702de4eb 100644
--- a/src/locales/default/setting.ts
+++ b/src/locales/default/setting.ts
@@ -886,6 +886,10 @@ When I am ___, I need ___
'systemAgent.historyCompress.modelDesc':
'Specify the model used to compress conversation history',
'systemAgent.historyCompress.title': 'Conversation History Compression Agent',
+ 'systemAgent.inputCompletion.label': 'Model',
+ 'systemAgent.inputCompletion.modelDesc':
+ 'Model used for input auto-completion suggestions (like GitHub Copilot ghost text)',
+ 'systemAgent.inputCompletion.title': 'Input Auto-Completion Agent',
'systemAgent.queryRewrite.label': 'Model',
'systemAgent.queryRewrite.modelDesc': 'Specify the model used to optimize user inquiries',
'systemAgent.queryRewrite.title': 'Library query rewrite Agent',
diff --git a/src/routes/(main)/settings/agent/index.tsx b/src/routes/(main)/settings/agent/index.tsx
index 9fd5f75482b..b03151d727c 100644
--- a/src/routes/(main)/settings/agent/index.tsx
+++ b/src/routes/(main)/settings/agent/index.tsx
@@ -19,6 +19,7 @@ const Page = () => {
<SystemAgentForm systemAgentKey="translation" />
<SystemAgentForm systemAgentKey="historyCompress" />
<SystemAgentForm systemAgentKey="agentMeta" />
+ <SystemAgentForm allowDisable systemAgentKey="inputCompletion" />
{enableKnowledgeBase && (
<SystemAgentForm
allowCustomPrompt
diff --git a/src/routes/(main)/settings/service-model/index.tsx b/src/routes/(main)/settings/service-model/index.tsx
index 796a09faad1..ef4e73620a2 100644
--- a/src/routes/(main)/settings/service-model/index.tsx
+++ b/src/routes/(main)/settings/service-model/index.tsx
@@ -23,6 +23,7 @@ const Page = () => {
<SystemAgentForm systemAgentKey="translation" />
<SystemAgentForm systemAgentKey="historyCompress" />
<SystemAgentForm systemAgentKey="agentMeta" />
+ <SystemAgentForm allowDisable systemAgentKey="inputCompletion" />
{enableKnowledgeBase && (
<SystemAgentForm
allowCustomPrompt
diff --git a/src/store/user/slices/settings/selectors/__snapshots__/settings.test.ts.snap b/src/store/user/slices/settings/selectors/__snapshots__/settings.test.ts.snap
index 638db791609..cce5848398b 100644
--- a/src/store/user/slices/settings/selectors/__snapshots__/settings.test.ts.snap
+++ b/src/store/user/slices/settings/selectors/__snapshots__/settings.test.ts.snap
@@ -63,6 +63,11 @@ exports[`settingsSelectors > currentSystemAgent > should merge DEFAULT_SYSTEM_AG
"model": "claude-sonnet-4-6",
"provider": "anthropic",
},
+ "inputCompletion": {
+ "enabled": true,
+ "model": "gpt-5.4-mini",
+ "provider": "openai",
+ },
"queryRewrite": {
"enabled": true,
"model": "gpt-5.4-mini",
diff --git a/src/store/user/slices/settings/selectors/systemAgent.ts b/src/store/user/slices/settings/selectors/systemAgent.ts
index 7228a4cd42e..2ae8943c4ed 100644
--- a/src/store/user/slices/settings/selectors/systemAgent.ts
+++ b/src/store/user/slices/settings/selectors/systemAgent.ts
@@ -14,11 +14,13 @@ const agentMeta = (s: UserStore) => currentSystemAgent(s).agentMeta;
const queryRewrite = (s: UserStore) => currentSystemAgent(s).queryRewrite;
const historyCompress = (s: UserStore) => currentSystemAgent(s).historyCompress;
const generationTopic = (s: UserStore) => currentSystemAgent(s).generationTopic;
+const inputCompletion = (s: UserStore) => currentSystemAgent(s).inputCompletion;
export const systemAgentSelectors = {
agentMeta,
generationTopic,
historyCompress,
+ inputCompletion,
queryRewrite,
thread,
topic,