🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
🐛 fix: tool engine and input-loading (#12908)
Arvin Xu9c9e8e8ecee4
diff --git a/packages/builtin-tools/src/index.ts b/packages/builtin-tools/src/index.tsindex 804f52257f0..85cd2e10f10 100644--- a/packages/builtin-tools/src/index.ts+++ b/packages/builtin-tools/src/index.ts@@ -33,6 +33,12 @@ export const defaultToolIds = [CloudSandboxManifest.identifier,];+/**+ * Tool IDs that are always enabled regardless of user selection.+ * These are core system tools that the agent needs to function properly.+ */+export const alwaysOnToolIds = [LobeToolsManifest.identifier, SkillsManifest.identifier];+export const builtinTools: LobeBuiltinTool[] = [{discoverable: false,diff --git a/packages/context-engine/src/engine/tools/__tests__/ToolsEngine.test.ts b/packages/context-engine/src/engine/tools/__tests__/ToolsEngine.test.tsindex c1dfb75b919..89293ef9a3a 100644--- a/packages/context-engine/src/engine/tools/__tests__/ToolsEngine.test.ts+++ b/packages/context-engine/src/engine/tools/__tests__/ToolsEngine.test.ts@@ -1,5 +1,6 @@import { describe, expect, it, vi } from 'vitest';+import { createEnableChecker } from '../enableCheckerFactory';import { ToolsEngine } from '../ToolsEngine';import type { LobeToolManifest } from '../types';@@ -1057,6 +1058,101 @@ describe('ToolsEngine', () => {});});+ describe('explicit activation with always-on builtins', () => {+ const builtinManifests: LobeToolManifest[] = [+ {+ identifier: 'lobe-tools',+ api: [{ name: 'run', description: 'Run tool', parameters: {} }],+ meta: { title: 'Tools' },+ type: 'builtin',+ },+ {+ identifier: 'lobe-skills',+ api: [{ name: 'run', description: 'Run skill', parameters: {} }],+ meta: { title: 'Skills' },+ type: 'builtin',+ },+ {+ identifier: 'lobe-skill-store',+ api: [{ name: 'search', description: 'Search', parameters: {} }],+ meta: { title: 'Skill Store' },+ type: 'builtin',+ },+ {+ identifier: 'lobe-web-browsing',+ api: [{ name: 'search', description: 'Search web', parameters: {} }],+ meta: { title: 'Web Browsing' },+ type: 'builtin',+ },+ {+ identifier: 'lobe-knowledge-base',+ api: [{ name: 'query', description: 'Query KB', parameters: {} }],+ meta: { title: 'Knowledge Base' },+ type: 'builtin',+ },+ {+ identifier: 'lobe-user-memory',+ api: [{ name: 'recall', description: 'Recall', parameters: {} }],+ meta: { title: 'Memory' },+ type: 'builtin',+ },+ {+ identifier: 'lobe-notebook',+ api: [{ name: 'write', description: 'Write note', parameters: {} }],+ meta: { title: 'Notebook' },+ type: 'builtin',+ },+ ];++ it('should only enable notebook + always-on builtins when user selected only notebook', () => {+ const userSelectedPlugins = ['lobe-notebook'];+ const defaultToolIds = [+ 'lobe-tools',+ 'lobe-skills',+ 'lobe-skill-store',+ 'lobe-web-browsing',+ 'lobe-knowledge-base',+ 'lobe-user-memory',+ ];++ // Build rules: user-selected plugins + always-on builtins + system conditions+ const rules: Record<string, boolean> = {+ // User-selected plugins+ ...Object.fromEntries(userSelectedPlugins.map((id) => [id, true])),+ // Always-on builtin tools+ 'lobe-tools': true,+ 'lobe-skills': true,+ // System-level rules+ 'lobe-knowledge-base': false, // no knowledge bases enabled+ 'lobe-user-memory': false, // memory disabled+ 'lobe-web-browsing': true, // search enabled+ };++ const engine = new ToolsEngine({+ manifestSchemas: builtinManifests,+ defaultToolIds,+ enableChecker: createEnableChecker({ rules }),+ functionCallChecker: () => true,+ });++ const result = engine.generateToolsDetailed({+ toolIds: userSelectedPlugins,+ model: 'gpt-4',+ provider: 'openai',+ });++ // notebook + web-browsing + always-on builtins (lobe-tools, lobe-skills) should be enabled+ expect(result.enabledToolIds).toContain('lobe-notebook');+ expect(result.enabledToolIds).toContain('lobe-web-browsing');+ expect(result.enabledToolIds).toContain('lobe-tools');+ expect(result.enabledToolIds).toContain('lobe-skills');+ // lobe-skill-store should NOT be enabled (not always-on, not user-selected)+ expect(result.enabledToolIds).not.toContain('lobe-skill-store');+ expect(result.enabledToolIds).not.toContain('lobe-knowledge-base');+ expect(result.enabledToolIds).not.toContain('lobe-user-memory');+ });+ });+describe('deduplication', () => {it('should deduplicate tool IDs in toolIds array', () => {const engine = new ToolsEngine({diff --git a/packages/context-engine/src/engine/tools/__tests__/enableCheckerFactory.test.ts b/packages/context-engine/src/engine/tools/__tests__/enableCheckerFactory.test.tsindex 81715e70b11..53f7c7a85ff 100644--- a/packages/context-engine/src/engine/tools/__tests__/enableCheckerFactory.test.ts+++ b/packages/context-engine/src/engine/tools/__tests__/enableCheckerFactory.test.ts@@ -18,10 +18,10 @@ const makeParams = (pluginId: string, overrides: Record<string, any> = {}) => ({describe('createEnableChecker', () => {describe('default behavior', () => {- it('should enable all tools by default', () => {+ it('should disable tools by default when no rule matches', () => {const checker = createEnableChecker({});- expect(checker(makeParams('any-tool'))).toBe(true);+ expect(checker(makeParams('any-tool'))).toBe(false);});});@@ -32,7 +32,7 @@ describe('createEnableChecker', () => {});expect(checker(makeParams('web-search'))).toBe(false);- expect(checker(makeParams('other-tool'))).toBe(true);+ expect(checker(makeParams('other-tool'))).toBe(false);});it('should enable tools matching a true rule', () => {@@ -55,7 +55,7 @@ describe('createEnableChecker', () => {expect(checker(makeParams('local-system'))).toBe(false);expect(checker(makeParams('web-search'))).toBe(false);expect(checker(makeParams('knowledge-base'))).toBe(true);- expect(checker(makeParams('unrelated-tool'))).toBe(true);+ expect(checker(makeParams('unrelated-tool'))).toBe(false);});});@@ -167,8 +167,8 @@ describe('createEnableChecker', () => {// Rule blocksexpect(checker(makeParams('rule-blocked'))).toBe(false);- // Default enables- expect(checker(makeParams('other-tool'))).toBe(true);+ // Default disables+ expect(checker(makeParams('other-tool'))).toBe(false);});});});diff --git a/packages/context-engine/src/engine/tools/enableCheckerFactory.ts b/packages/context-engine/src/engine/tools/enableCheckerFactory.tsindex 14e9887463c..6b1a0fb9687 100644--- a/packages/context-engine/src/engine/tools/enableCheckerFactory.ts+++ b/packages/context-engine/src/engine/tools/enableCheckerFactory.ts@@ -20,7 +20,7 @@ export interface EnableCheckerConfig {/*** Tool-specific enable rules, keyed by pluginId.* If a pluginId is present in this map, its value determines whether the tool is enabled.- * If not present, the tool is enabled by default.+ * If not present, the tool is disabled by default.*/rules?: Record<string, boolean>;}@@ -46,7 +46,7 @@ export function createEnableChecker(config: EnableCheckerConfig): PluginEnableChreturn config.rules[pluginId];}- // 4. Default: enabled- return true;+ // 4. Default: disabled (tools must be explicitly enabled via rules)+ return false;};}diff --git a/src/features/Conversation/ChatInput/index.tsx b/src/features/Conversation/ChatInput/index.tsxindex 03d8d17cd80..4f01f268428 100644--- a/src/features/Conversation/ChatInput/index.tsx+++ b/src/features/Conversation/ChatInput/index.tsx@@ -110,8 +110,8 @@ const ChatInput = memo<ChatInputProps>(const updateInputMessage = useConversationStore((s) => s.updateInputMessage);const setEditor = useConversationStore((s) => s.setEditor);- // Generation state from ConversationStore (bridged from ChatStore)- const isAIGenerating = useConversationStore(messageStateSelectors.isAIGenerating);+ // Loading state from ConversationStore (bridged from ChatStore)+ const isInputLoading = useConversationStore(messageStateSelectors.isInputLoading);// Send message error from ConversationStoreconst sendMessageErrorMsg = useConversationStore(messageStateSelectors.sendMessageError);@@ -124,7 +124,7 @@ const ChatInput = memo<ChatInputProps>(// Computed stateconst isInputEmpty = !inputMessage.trim() && fileList.length === 0 && contextList.length === 0;- const disabled = isInputEmpty || isUploadingFiles || isAIGenerating;+ const disabled = isInputEmpty || isUploadingFiles || isInputLoading;// Send handler - gets message, clears editor immediately, then sendsconst handleSend: SendButtonHandler = useCallback(@@ -135,7 +135,7 @@ const ChatInput = memo<ChatInputProps>(const currentIsUploading = fileChatSelectors.isUploadingFiles(fileStore);const currentContextList = fileChatSelectors.chatContextSelections(fileStore);- if (currentIsUploading || isAIGenerating) return;+ if (currentIsUploading || isInputLoading) return;// Get content before clearingconst message = getMarkdownContent();@@ -158,12 +158,12 @@ const ChatInput = memo<ChatInputProps>(// Fire and forget - send with captured messageawait sendMessage({ files: currentFileList, message, pageSelections });},- [isAIGenerating, sendMessage],+ [isInputLoading, sendMessage],);const sendButtonProps: SendButtonProps = {disabled,- generating: isAIGenerating,+ generating: isInputLoading,onStop: stopGenerating,...customSendButtonProps,};diff --git a/src/features/Conversation/store/slices/generation/action.test.ts b/src/features/Conversation/store/slices/generation/action.test.tsindex 571be3f1a0b..d054ae249af 100644--- a/src/features/Conversation/store/slices/generation/action.test.ts+++ b/src/features/Conversation/store/slices/generation/action.test.ts@@ -1,7 +1,7 @@import { act } from '@testing-library/react';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { AI_RUNTIME_OPERATION_TYPES } from '@/store/chat/slices/operation/types';+import { INPUT_LOADING_OPERATION_TYPES } from '@/store/chat/slices/operation/types';import { type ConversationContext, type ConversationHooks } from '../../../types';import { createStore } from '../../index';@@ -9,6 +9,7 @@ import { createStore } from '../../index';// Mock useChatStoreconst mockCancelOperations = vi.fn();const mockCancelOperation = vi.fn();+const mockCancelSendMessageInServer = vi.fn();const mockRegenerateUserMessage = vi.fn();const mockRegenerateAssistantMessage = vi.fn();const mockContinueGenerationMessage = vi.fn();@@ -32,6 +33,7 @@ vi.mock('@/store/chat', () => ({messageLoadingIds: [],cancelOperations: mockCancelOperations,cancelOperation: mockCancelOperation,+ cancelSendMessageInServer: mockCancelSendMessageInServer,regenerateUserMessage: mockRegenerateUserMessage,regenerateAssistantMessage: mockRegenerateAssistantMessage,continueGenerationMessage: mockContinueGenerationMessage,@@ -71,7 +73,7 @@ describe('Generation Actions', () => {expect(mockCancelOperations).toHaveBeenCalledWith({- type: AI_RUNTIME_OPERATION_TYPES,+ type: INPUT_LOADING_OPERATION_TYPES,status: 'running',agentId: 'session-1',topicId: 'topic-1',diff --git a/src/features/Conversation/store/slices/generation/action.ts b/src/features/Conversation/store/slices/generation/action.tsindex ba727cd2116..5cecf962bb3 100644--- a/src/features/Conversation/store/slices/generation/action.ts+++ b/src/features/Conversation/store/slices/generation/action.ts@@ -2,7 +2,7 @@ import { type StateCreator } from 'zustand';import { MESSAGE_CANCEL_FLAT } from '@/const/index';import { useChatStore } from '@/store/chat';-import { AI_RUNTIME_OPERATION_TYPES } from '@/store/chat/slices/operation/types';+import { INPUT_LOADING_OPERATION_TYPES } from '@/store/chat/slices/operation/types';import { type Store as ConversationStore } from '../../action';@@ -353,13 +353,16 @@ export const generationSlice: StateCreator<const chatStore = useChatStore.getState();- // Cancel all running AI runtime operations in this conversation context- // Includes both client-side (execAgentRuntime) and server-side (execServerAgentRuntime) operations+ // Cancel all running operations in this conversation context+ // Includes sendMessage, AI runtime (client-side and server-side), and agent mode streamchatStore.cancelOperations(- { agentId, status: 'running', topicId, type: AI_RUNTIME_OPERATION_TYPES },+ { agentId, status: 'running', topicId, type: INPUT_LOADING_OPERATION_TYPES },MESSAGE_CANCEL_FLAT,);+ // Restore editor content if a sendMessage operation was cancelled+ chatStore.cancelSendMessageInServer(topicId ?? undefined);+// ===== Hook: onGenerationStop =====if (hooks.onGenerationStop) {hooks.onGenerationStop();diff --git a/src/features/Conversation/store/slices/messageState/selectors.ts b/src/features/Conversation/store/slices/messageState/selectors.tsindex 1644854be51..ffb999ee9f7 100644--- a/src/features/Conversation/store/slices/messageState/selectors.ts+++ b/src/features/Conversation/store/slices/messageState/selectors.ts@@ -41,6 +41,11 @@ const messageLoadingIds = (s: State) => s.messageLoadingIds;*/const isAIGenerating = (s: State) => s.operationState.isAIGenerating;+/**+ * Check if input should be in loading state (from sendMessage through AI generation)+ */+const isInputLoading = (s: State) => s.operationState.isInputLoading;+/*** Get send message error for this context (if any)*/@@ -138,6 +143,7 @@ const isThreadMode = (_s: State) => {export const messageStateSelectors = {hasThreadBySourceMsgId,isAIGenerating,+ isInputLoading,isMessageCollapsed,isMessageContinuing,isMessageCreating,diff --git a/src/features/Conversation/types/operation.ts b/src/features/Conversation/types/operation.tsindex f591dca6d53..a6b6745d7e9 100644--- a/src/features/Conversation/types/operation.ts+++ b/src/features/Conversation/types/operation.ts@@ -87,6 +87,11 @@ export interface OperationState {*/isAIGenerating: boolean;+ /**+ * Check if input should be in loading state (from sendMessage through AI generation)+ */+ isInputLoading: boolean;+/*** Send message error for this context (if any)*/@@ -120,5 +125,6 @@ export const DEFAULT_OPERATION_STATE: OperationState = {getMessageOperationState: () => DEFAULT_MESSAGE_OPERATION_STATE,getToolOperationState: () => DEFAULT_TOOL_OPERATION_STATE,isAIGenerating: false,+ isInputLoading: false,sendMessageError: undefined,};diff --git a/src/helpers/toolEngineering/index.test.ts b/src/helpers/toolEngineering/index.test.tsindex fa14a5e23ed..83f53d0a9d5 100644--- a/src/helpers/toolEngineering/index.test.ts+++ b/src/helpers/toolEngineering/index.test.ts@@ -83,6 +83,24 @@ vi.mock('../isCanUseFC', () => ({isCanUseFC: () => true,}));+let mockCurrentAgentPlugins: string[] = [];++vi.mock('@/store/agent', () => ({+ getAgentStoreState: () => ({}),+}));++vi.mock('@/store/agent/selectors', () => ({+ agentSelectors: {+ currentAgentPlugins: () => mockCurrentAgentPlugins,+ hasEnabledKnowledgeBases: () => false,+ },+ agentChatConfigSelectors: {+ isCloudSandboxEnabled: () => false,+ isLocalSystemEnabled: () => false,+ isMemoryToolEnabled: () => false,+ },+}));+let mockUseApplicationBuiltinSearchTool = true;vi.mock('@/helpers/getSearchConfig', () => ({@@ -98,6 +116,7 @@ describe('toolEngineering', () => {mockGetInstalledPluginById = () => () => undefined;mockInstalledPluginManifestList = () => [];mockUseApplicationBuiltinSearchTool = true;+ mockCurrentAgentPlugins = [];});describe('createToolsEngine', () => {@@ -172,6 +191,8 @@ describe('toolEngineering', () => {});it('should include web browsing tool alongside user-provided tools', () => {+ mockCurrentAgentPlugins = ['search'];+const toolsEngine = createAgentToolsEngine({model: 'gpt-4',provider: 'openai',@@ -244,6 +265,7 @@ describe('toolEngineering', () => {id === 'stdio-mcp-plugin'? { customParams: { mcp: { type: 'stdio' } }, identifier: id }: undefined;+ mockCurrentAgentPlugins = ['stdio-mcp-plugin'];const toolsEngine = createAgentToolsEngine({ model: 'gpt-4', provider: 'openai' });const result = toolsEngine.generateToolsDetailed({@@ -293,6 +315,7 @@ describe('toolEngineering', () => {id === 'stdio-mcp-plugin'? { customParams: { mcp: { type: 'stdio' } }, identifier: id }: undefined;+ mockCurrentAgentPlugins = ['stdio-mcp-plugin'];const toolsEngine = createAgentToolsEngine({ model: 'gpt-4', provider: 'openai' });const result = toolsEngine.generateToolsDetailed({@@ -310,6 +333,7 @@ describe('toolEngineering', () => {id === 'http-mcp-plugin'? { customParams: { mcp: { type: 'http' } }, identifier: id }: undefined;+ mockCurrentAgentPlugins = ['http-mcp-plugin'];const toolsEngine = createAgentToolsEngine({ model: 'gpt-4', provider: 'openai' });const result = toolsEngine.generateToolsDetailed({diff --git a/src/helpers/toolEngineering/index.ts b/src/helpers/toolEngineering/index.tsindex ca6e31016df..9ae0a8eef47 100644--- a/src/helpers/toolEngineering/index.ts+++ b/src/helpers/toolEngineering/index.ts@@ -6,7 +6,7 @@ import { KnowledgeBaseManifest } from '@lobechat/builtin-tool-knowledge-base';import { LocalSystemManifest } from '@lobechat/builtin-tool-local-system';import { MemoryManifest } from '@lobechat/builtin-tool-memory';import { WebBrowsingManifest } from '@lobechat/builtin-tool-web-browsing';-import { defaultToolIds } from '@lobechat/builtin-tools';+import { alwaysOnToolIds, defaultToolIds } from '@lobechat/builtin-tools';import { isDesktop } from '@lobechat/const';import { createEnableChecker, type PluginEnableChecker } from '@lobechat/context-engine';import { ToolsEngine } from '@lobechat/context-engine';@@ -83,9 +83,14 @@ export const createToolsEngine = (config: ToolsEngineConfig = {}): ToolsEngine =});};-export const createAgentToolsEngine = (workingModel: WorkingModel) => {+export const createAgentToolsEngine = (+ workingModel: WorkingModel,+ /** Runtime-resolved plugin IDs (from agentConfigResolver), may include tools beyond the active agent */+ pluginIds?: string[],+) => {const searchConfig = getSearchConfig(workingModel.model, workingModel.provider);const agentState = getAgentStoreState();+ const userPlugins = agentSelectors.currentAgentPlugins(agentState);return createToolsEngine({defaultToolIds,@@ -104,6 +109,14 @@ export const createAgentToolsEngine = (workingModel: WorkingModel) => {return undefined; // fall through to rules},rules: {+ // Runtime-resolved plugins (from agentConfigResolver for the effective agent,+ // may include sub-agent/group/page scope plugins not on the active agent)+ ...(pluginIds && Object.fromEntries(pluginIds.map((id) => [id, true]))),+ // User-selected plugins (from the active agent)+ ...Object.fromEntries(userPlugins.map((id) => [id, true])),+ // Always-on builtin tools+ ...Object.fromEntries(alwaysOnToolIds.map((id) => [id, true])),+ // System-level rules (may override user selection for specific tools)[CloudSandboxManifest.identifier]:agentChatConfigSelectors.isCloudSandboxEnabled(agentState),[KnowledgeBaseManifest.identifier]: agentSelectors.hasEnabledKnowledgeBases(agentState),diff --git a/src/hooks/useOperationState.ts b/src/hooks/useOperationState.tsindex 71f6921dc78..d3decb16d33 100644--- a/src/hooks/useOperationState.ts+++ b/src/hooks/useOperationState.ts@@ -39,6 +39,11 @@ export const useOperationState = (context: ConversationContext): OperationStateoperationSelectors.isAgentRuntimeRunningByContext(context)(s),);+ // Check if input should show loading (sendMessage + AI runtime)+ const isInputLoading = useChatStore((s) =>+ operationSelectors.isInputLoadingByContext(context)(s),+ );+// Get send message error for this contextconst sendMessageError = useMemo(() => {const operationIds = operationsByContext[contextKey] || [];@@ -101,9 +106,17 @@ export const useOperationState = (context: ConversationContext): OperationState};},isAIGenerating,+ isInputLoading,sendMessageError,};- }, [operations, operationsByMessage, toolCallingStreamIds, isAIGenerating, sendMessageError]);+ }, [+ operations,+ operationsByMessage,+ toolCallingStreamIds,+ isAIGenerating,+ isInputLoading,+ sendMessageError,+ ]);return operationState;};diff --git a/src/server/modules/Mecha/AgentToolsEngine/index.ts b/src/server/modules/Mecha/AgentToolsEngine/index.tsindex f381c3a7d28..778fda8e953 100644--- a/src/server/modules/Mecha/AgentToolsEngine/index.ts+++ b/src/server/modules/Mecha/AgentToolsEngine/index.ts@@ -15,7 +15,7 @@ import { LocalSystemManifest } from '@lobechat/builtin-tool-local-system';import { MemoryManifest } from '@lobechat/builtin-tool-memory';import { RemoteDeviceManifest } from '@lobechat/builtin-tool-remote-device';import { WebBrowsingManifest } from '@lobechat/builtin-tool-web-browsing';-import { builtinTools, defaultToolIds } from '@lobechat/builtin-tools';+import { alwaysOnToolIds, builtinTools, defaultToolIds } from '@lobechat/builtin-tools';import { createEnableChecker, type LobeToolManifest } from '@lobechat/context-engine';import { ToolsEngine } from '@lobechat/context-engine';import debug from 'debug';@@ -125,6 +125,11 @@ export const createServerAgentToolsEngine = (defaultToolIds,enableChecker: createEnableChecker({rules: {+ // User-selected plugins+ ...Object.fromEntries((agentConfig.plugins ?? []).map((id) => [id, true])),+ // Always-on builtin tools+ ...Object.fromEntries(alwaysOnToolIds.map((id) => [id, true])),+ // System-level rules (may override user selection for specific tools)[CloudSandboxManifest.identifier]: runtimeMode === 'cloud',[KnowledgeBaseManifest.identifier]: hasEnabledKnowledgeBases,[LocalSystemManifest.identifier]:diff --git a/src/store/chat/slices/aiChat/actions/streamingExecutor.ts b/src/store/chat/slices/aiChat/actions/streamingExecutor.tsindex 060ef9ddd2c..b6c2583e005 100644--- a/src/store/chat/slices/aiChat/actions/streamingExecutor.ts+++ b/src/store/chat/slices/aiChat/actions/streamingExecutor.ts@@ -141,10 +141,10 @@ export class StreamingExecutorActionImpl {// Generate tools using ToolsEngine (centralized here, passed to chatService via agentConfig)// When disableTools is true (broadcast mode), skipDefaultTools prevents default tools from being added- const toolsEngine = createAgentToolsEngine({- model: agentConfigData.model,- provider: agentConfigData.provider!,- });+ const toolsEngine = createAgentToolsEngine(+ { model: agentConfigData.model, provider: agentConfigData.provider! },+ pluginIds,+ );const toolsDetailed = toolsEngine.generateToolsDetailed({model: agentConfigData.model,diff --git a/src/store/chat/slices/operation/selectors.ts b/src/store/chat/slices/operation/selectors.tsindex fee3d87dd9d..78a87c4cdfb 100644--- a/src/store/chat/slices/operation/selectors.ts+++ b/src/store/chat/slices/operation/selectors.ts@@ -2,7 +2,7 @@ import { type ChatStoreState } from '@/store/chat/initialState';import { messageMapKey } from '@/store/chat/utils/messageMapKey';import { type Operation, type OperationType } from './types';-import { AI_RUNTIME_OPERATION_TYPES } from './types';+import { AI_RUNTIME_OPERATION_TYPES, INPUT_LOADING_OPERATION_TYPES } from './types';// === Basic Queries ===/**@@ -234,6 +234,45 @@ const isAgentRuntimeRunningByContext =);};+/**+ * Check if input should show loading state in a specific context+ * Includes sendMessage in addition to AI runtime operations,+ * so the input stays in loading state from the moment user sends until AI finishes+ */+const isInputLoadingByContext =+ (context: {+ agentId?: string;+ groupId?: string;+ threadId?: string | null;+ topicId?: string | null;+ }) =>+ (s: ChatStoreState): boolean => {+ if (!context.agentId) return false;++ const contextKey = messageMapKey({+ agentId: context.agentId,+ groupId: context.groupId,+ topicId: context.topicId,+ });++ const operationIds = s.operationsByContext[contextKey] || [];+ const operations = operationIds+ .map((id) => s.operations[id])+ .filter((op): op is Operation => {+ if (!op) return false;+ const opThreadId = op.context.threadId ?? null;+ const contextThreadId = context.threadId ?? null;+ return opThreadId === contextThreadId;+ });++ return operations.some(+ (op) =>+ INPUT_LOADING_OPERATION_TYPES.includes(op.type) &&+ op.status === 'running' &&+ !op.metadata.isAborting,+ );+ };+// === Backward Compatibility ===/**@@ -523,6 +562,7 @@ export const operationSelectors = {isAgentRuntimeRunning,isAgentUnreadCompleted,isAgentRuntimeRunningByContext,+ isInputLoadingByContext,isAnyMessageLoading,isContinuing,isInSearchWorkflow,diff --git a/src/store/chat/slices/operation/types.ts b/src/store/chat/slices/operation/types.tsindex 1ab321861d6..04e6ca2c2ee 100644--- a/src/store/chat/slices/operation/types.ts+++ b/src/store/chat/slices/operation/types.ts@@ -208,3 +208,13 @@ export const AI_RUNTIME_OPERATION_TYPES: OperationType[] = ['execAgentRuntime','execServerAgentRuntime',];++/**+ * Operation types that should block input and show loading state+ * Superset of AI_RUNTIME_OPERATION_TYPES, also includes sendMessage+ * since the input should be in loading state from the moment user sends until AI finishes+ */+export const INPUT_LOADING_OPERATION_TYPES: OperationType[] = [+ ...AI_RUNTIME_OPERATION_TYPES,+ 'sendMessage',+];