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.

♻️ refactor(chat): introduce agentDispatcher.selectRuntimeType (#14428)

Arvin Xud83f0a0f2f27
diff --git a/docs/development/basic/chat-api.mdx b/docs/development/basic/chat-api.mdx
index 614f1d3d9c4..0b099c6554b 100644
--- a/docs/development/basic/chat-api.mdx
+++ b/docs/development/basic/chat-api.mdx
@@ -72,7 +72,7 @@ sequenceDiagram
After the user sends a message, `sendMessage()`
(`src/store/chat/slices/aiChat/actions/conversationLifecycle.ts`)
creates the user message and assistant message placeholder,
-then calls `internal_execAgentRuntime()`.
+then calls `executeClientAgent()`.
### 2. Agent Runtime Drives the Loop
@@ -325,7 +325,7 @@ depends on the scenario:
- **Client-side loop** (browser): Regular 1:1 chat,
continue generation, group orchestration decisions.
The loop runs in the browser, entry point is
- `internal_execAgentRuntime()`
+ `executeClientAgent()`
(`src/store/chat/slices/aiChat/actions/streamingExecutor.ts`)
- **Server-side loop** (queue/local):
Group chat supervisor agent, sub-agent tasks,
diff --git a/docs/development/basic/chat-api.zh-CN.mdx b/docs/development/basic/chat-api.zh-CN.mdx
index 9c252a438ff..5bdb3f161d0 100644
--- a/docs/development/basic/chat-api.zh-CN.mdx
+++ b/docs/development/basic/chat-api.zh-CN.mdx
@@ -68,7 +68,7 @@ sequenceDiagram
用户发送消息后,`sendMessage()`
(`src/store/chat/slices/aiChat/actions/conversationLifecycle.ts`)
-创建用户消息和助手消息占位,然后调用 `internal_execAgentRuntime()`。
+创建用户消息和助手消息占位,然后调用 `executeClientAgent()`。
### 2. Agent Runtime 驱动循环
@@ -293,7 +293,7 @@ Agent Runtime 循环的执行位置取决于场景:
- **客户端循环**(浏览器):常规 1:1 对话、继续生成、
群组编排决策。循环在浏览器中运行,
- 入口为 `internal_execAgentRuntime()`
+ 入口为 `executeClientAgent()`
(`src/store/chat/slices/aiChat/actions/streamingExecutor.ts`)
- **服务端循环**(队列 / 本地):群聊 supervisor agent、
子 agent 任务、API/Cron 触发。循环在服务端运行,
diff --git a/packages/agent-runtime/src/utils/stepContextComputer.ts b/packages/agent-runtime/src/utils/stepContextComputer.ts
index 556068556fc..77f9eebf0a5 100644
--- a/packages/agent-runtime/src/utils/stepContextComputer.ts
+++ b/packages/agent-runtime/src/utils/stepContextComputer.ts
@@ -27,7 +27,7 @@ export interface ComputeStepContextParams {
/**
* Compute the Step Context from pre-computed values
*
- * Called in internal_execAgentRuntime while loop before each runtime.step() call.
+ * Called in executeClientAgent while loop before each runtime.step() call.
* The stepContext is then passed through AgentRuntimeContext to Tool Executors.
*
* Note: The actual data (like todos) should be computed using selectors in the UI layer
diff --git a/packages/builtin-tool-agent-management/src/executor.ts b/packages/builtin-tool-agent-management/src/executor.ts
index 1e04b2b7fd7..6c9e7e4bd6c 100644
--- a/packages/builtin-tool-agent-management/src/executor.ts
+++ b/packages/builtin-tool-agent-management/src/executor.ts
@@ -15,8 +15,10 @@ import {
import { agentService } from '@/services/agent';
import { discoverService } from '@/services/discover';
-import { useAgentStore } from '@/store/agent';
+import { getAgentStoreState, useAgentStore } from '@/store/agent';
+import { agentSelectors } from '@/store/agent/selectors';
import { useChatStore } from '@/store/chat';
+import { selectRuntimeType } from '@/store/chat/slices/aiChat/actions/agentDispatcher';
import { dbMessageSelectors } from '@/store/chat/slices/message/selectors';
import { messageMapKey } from '@/store/chat/utils/messageMapKey';
@@ -218,7 +220,7 @@ class AgentManagementExecutor extends BaseExecutor<typeof AgentManagementApiName
const conversationContext: ConversationContext = {
agentId: ctx.agentId || '',
topicId: ctx.topicId || null,
- // subAgentId will be set when calling internal_execAgentRuntime
+ // subAgentId will be set when calling executeClientAgent
};
// Get current messages
@@ -247,15 +249,35 @@ class AgentManagementExecutor extends BaseExecutor<typeof AgentManagementApiName
]
: messages;
+ // callAgent inherits the parent's runtime selection — a hetero/gateway
+ // parent must keep the called sub-agent on the same path. See LOBE-8519.
+ const parentAgentConfig = conversationContext.agentId
+ ? agentSelectors.getAgentConfigById(conversationContext.agentId)(getAgentStoreState())
+ : undefined;
+ const runtimeType = selectRuntimeType({
+ heterogeneousProvider: parentAgentConfig?.agencyConfig?.heterogeneousProvider,
+ isGatewayMode: get().isGatewayModeEnabled(),
+ });
+
+ // TODO(LOBE-8519 follow-up): only client sub-agent dispatch is wired.
+ // Gateway / hetero callAgent invocations fall through to client and
+ // will need their own runner once Step 2 lands.
+ if (runtimeType !== 'client') {
+ console.warn(
+ `[callAgent] runtime=${runtimeType} not yet supported for sub-agent dispatch; ` +
+ 'falling through to client mode',
+ );
+ }
+
try {
- await get().internal_execAgentRuntime({
+ await get().executeClientAgent({
context: { ...conversationContext, subAgentId: agentId, scope: 'sub_agent' },
messages: messagesWithInstruction,
parentMessageId: ctx.messageId,
parentMessageType: 'tool',
});
} catch (error) {
- console.error('[callAgent] internal_execAgentRuntime failed:', error);
+ console.error('[callAgent] executeClientAgent failed:', error);
throw error;
}
});
diff --git a/packages/builtin-tool-web-browsing/src/client/Portal/Search/Footer.tsx b/packages/builtin-tool-web-browsing/src/client/Portal/Search/Footer.tsx
deleted file mode 100644
index fe555cb7310..00000000000
--- a/packages/builtin-tool-web-browsing/src/client/Portal/Search/Footer.tsx
+++ /dev/null
@@ -1,47 +0,0 @@
-import { ActionIcon, Button, Flexbox } from '@lobehub/ui';
-import { LucideNotepadText, PlusSquareIcon } from 'lucide-react';
-import { useTranslation } from 'react-i18next';
-
-import { useChatStore } from '@/store/chat';
-import { chatPortalSelectors, operationSelectors } from '@/store/chat/selectors';
-
-const Footer = () => {
- const [messageId, isAgentRuntimeRunning, triggerAIMessage, saveSearchResult] = useChatStore(
- (s) => [
- chatPortalSelectors.toolMessageId(s),
- operationSelectors.isAgentRuntimeRunning(s),
- s.triggerAIMessage,
- s.saveSearchResult,
- ],
- );
-
- const { t } = useTranslation('tool');
-
- return (
- <Flexbox horizontal gap={8} paddingBlock={12} paddingInline={12}>
- <Button
- icon={LucideNotepadText}
- loading={isAgentRuntimeRunning}
- onClick={() => {
- if (!messageId) return;
-
- triggerAIMessage({});
- }}
- >
- {t('search.summaryTooltip')}
- </Button>
- <ActionIcon
- icon={PlusSquareIcon}
- loading={isAgentRuntimeRunning}
- title={t('search.createNewSearch')}
- onClick={() => {
- if (!messageId) return;
-
- saveSearchResult(messageId);
- }}
- />
- </Flexbox>
- );
-};
-
-export default Footer;
diff --git a/packages/builtin-tool-web-browsing/src/client/Portal/Search/index.tsx b/packages/builtin-tool-web-browsing/src/client/Portal/Search/index.tsx
index a479707925e..0907a7af97d 100644
--- a/packages/builtin-tool-web-browsing/src/client/Portal/Search/index.tsx
+++ b/packages/builtin-tool-web-browsing/src/client/Portal/Search/index.tsx
@@ -7,7 +7,6 @@ import { useChatStore } from '@/store/chat';
import { chatToolSelectors } from '@/store/chat/selectors';
import SearchBar from '../../components/SearchBar';
-import Footer from './Footer';
import ResultList from './ResultList';
interface InspectorUIProps {
@@ -47,20 +46,17 @@ const Inspector = memo<InspectorUIProps>(({ query: args, messageId, response })
}
return (
- <Flexbox gap={0} height={'100%'}>
- <Flexbox gap={12} height={'100%'}>
- <SearchBar
- aiSummary={false}
- defaultEngines={defaultEngines}
- defaultQuery={args.query}
- messageId={messageId}
- tooltip={false}
- />
- <Flexbox height={'100%'} width={'100%'}>
- <ResultList dataSources={response.results} />
- </Flexbox>
+ <Flexbox gap={12} height={'100%'}>
+ <SearchBar
+ aiSummary={false}
+ defaultEngines={defaultEngines}
+ defaultQuery={args.query}
+ messageId={messageId}
+ tooltip={false}
+ />
+ <Flexbox height={'100%'} width={'100%'}>
+ <ResultList dataSources={response.results} />
</Flexbox>
- <Footer />
</Flexbox>
);
});
diff --git a/src/features/Conversation/store.test.ts b/src/features/Conversation/store.test.ts
index c8fa5f784fa..2e574307e0a 100644
--- a/src/features/Conversation/store.test.ts
+++ b/src/features/Conversation/store.test.ts
@@ -38,7 +38,7 @@ vi.mock('@/store/chat', () => ({
replaceMessages: vi.fn(),
internal_dispatchMessage: vi.fn(),
internal_dispatchTopic: vi.fn(),
- internal_execAgentRuntime: vi.fn(),
+ executeClientAgent: vi.fn(),
sendMessage: vi.fn(),
switchTopic: vi.fn(),
summaryTopicTitle: vi.fn(),
diff --git a/src/features/Conversation/store/slices/generation/action.test.ts b/src/features/Conversation/store/slices/generation/action.test.ts
index c3e132e0c40..6ba4b5ec38b 100644
--- a/src/features/Conversation/store/slices/generation/action.test.ts
+++ b/src/features/Conversation/store/slices/generation/action.test.ts
@@ -19,7 +19,7 @@ const mockSwitchMessageBranch = vi.fn();
const mockStartOperation = vi.fn(() => ({ operationId: 'test-op-id' }));
const mockCompleteOperation = vi.fn();
const mockFailOperation = vi.fn();
-const mockInternalExecAgentRuntime = vi.fn();
+const mockExecuteClientAgent = vi.fn();
const mockIsGatewayModeEnabled = vi.fn(() => false);
const mockExecuteGatewayAgent = vi.fn();
@@ -46,7 +46,7 @@ vi.mock('@/store/chat', () => ({
startOperation: mockStartOperation,
completeOperation: mockCompleteOperation,
failOperation: mockFailOperation,
- internal_execAgentRuntime: mockInternalExecAgentRuntime,
+ executeClientAgent: mockExecuteClientAgent,
isGatewayModeEnabled: mockIsGatewayModeEnabled,
executeGatewayAgent: mockExecuteGatewayAgent,
})),
@@ -172,7 +172,7 @@ describe('Generation Actions', () => {
startOperation: mockStartOperation,
completeOperation: mockCompleteOperation,
failOperation: mockFailOperation,
- internal_execAgentRuntime: mockInternalExecAgentRuntime,
+ executeClientAgent: mockExecuteClientAgent,
isGatewayModeEnabled: mockIsGatewayModeEnabled,
} as any);
@@ -212,8 +212,8 @@ describe('Generation Actions', () => {
type: 'continue',
});
- // Should call internal_execAgentRuntime with last child id as parentMessageId
- expect(mockInternalExecAgentRuntime).toHaveBeenCalledWith(
+ // Should call executeClientAgent with last child id as parentMessageId
+ expect(mockExecuteClientAgent).toHaveBeenCalledWith(
expect.objectContaining({
context,
parentMessageId: 'child-2', // last child's id
@@ -232,7 +232,7 @@ describe('Generation Actions', () => {
startOperation: mockStartOperation,
completeOperation: mockCompleteOperation,
failOperation: mockFailOperation,
- internal_execAgentRuntime: mockInternalExecAgentRuntime,
+ executeClientAgent: mockExecuteClientAgent,
isGatewayModeEnabled: mockIsGatewayModeEnabled,
} as any);
@@ -257,7 +257,7 @@ describe('Generation Actions', () => {
// Should not create operation if message is not assistantGroup
expect(mockStartOperation).not.toHaveBeenCalled();
- expect(mockInternalExecAgentRuntime).not.toHaveBeenCalled();
+ expect(mockExecuteClientAgent).not.toHaveBeenCalled();
});
it('should not continue if assistantGroup has no children', async () => {
@@ -269,7 +269,7 @@ describe('Generation Actions', () => {
startOperation: mockStartOperation,
completeOperation: mockCompleteOperation,
failOperation: mockFailOperation,
- internal_execAgentRuntime: mockInternalExecAgentRuntime,
+ executeClientAgent: mockExecuteClientAgent,
isGatewayModeEnabled: mockIsGatewayModeEnabled,
} as any);
@@ -296,7 +296,7 @@ describe('Generation Actions', () => {
// Should not create operation if no children
expect(mockStartOperation).not.toHaveBeenCalled();
- expect(mockInternalExecAgentRuntime).not.toHaveBeenCalled();
+ expect(mockExecuteClientAgent).not.toHaveBeenCalled();
});
it('should call onBeforeContinue hook and respect false return', async () => {
@@ -308,7 +308,7 @@ describe('Generation Actions', () => {
startOperation: mockStartOperation,
completeOperation: mockCompleteOperation,
failOperation: mockFailOperation,
- internal_execAgentRuntime: mockInternalExecAgentRuntime,
+ executeClientAgent: mockExecuteClientAgent,
isGatewayModeEnabled: mockIsGatewayModeEnabled,
} as any);
@@ -342,8 +342,8 @@ describe('Generation Actions', () => {
});
expect(onBeforeContinue).toHaveBeenCalledWith('group-msg-1');
- // Should not call internal_execAgentRuntime if hook returns false
- expect(mockInternalExecAgentRuntime).not.toHaveBeenCalled();
+ // Should not call executeClientAgent if hook returns false
+ expect(mockExecuteClientAgent).not.toHaveBeenCalled();
});
it('should call onContinueComplete hook after continuation', async () => {
@@ -355,7 +355,8 @@ describe('Generation Actions', () => {
startOperation: mockStartOperation,
completeOperation: mockCompleteOperation,
failOperation: mockFailOperation,
- internal_execAgentRuntime: mockInternalExecAgentRuntime.mockResolvedValue(undefined),
+ executeClientAgent: mockExecuteClientAgent.mockResolvedValue(undefined),
+ isGatewayModeEnabled: mockIsGatewayModeEnabled,
} as any);
const onContinueComplete = vi.fn();
@@ -399,7 +400,7 @@ describe('Generation Actions', () => {
startOperation: mockStartOperation,
completeOperation: mockCompleteOperation,
failOperation: mockFailOperation,
- internal_execAgentRuntime: mockInternalExecAgentRuntime,
+ executeClientAgent: mockExecuteClientAgent,
isGatewayModeEnabled: mockIsGatewayModeEnabled,
} as any);
@@ -424,7 +425,7 @@ describe('Generation Actions', () => {
// Should not create operation if message not found
expect(mockStartOperation).not.toHaveBeenCalled();
- expect(mockInternalExecAgentRuntime).not.toHaveBeenCalled();
+ expect(mockExecuteClientAgent).not.toHaveBeenCalled();
});
});
@@ -444,7 +445,7 @@ describe('Generation Actions', () => {
startOperation: mockStartOperation,
completeOperation: mockCompleteOperation,
failOperation: mockFailOperation,
- internal_execAgentRuntime: mockInternalExecAgentRuntime,
+ executeClientAgent: mockExecuteClientAgent,
isGatewayModeEnabled: mockIsGatewayModeEnabled,
} as any);
@@ -515,8 +516,8 @@ describe('Generation Actions', () => {
startOperation: mockStartOperation,
completeOperation: mockCompleteOperation,
failOperation: mockFailOperation,
- internal_execAgentRuntime: vi.fn().mockImplementation(() => {
- callOrder.push('internal_execAgentRuntime');
+ executeClientAgent: vi.fn().mockImplementation(() => {
+ callOrder.push('executeClientAgent');
return Promise.resolve();
}),
isGatewayModeEnabled: mockIsGatewayModeEnabled,
@@ -549,17 +550,17 @@ describe('Generation Actions', () => {
await store.getState().delAndRegenerateMessage('msg-2');
});
- // CRITICAL: deleteMessage must be called BEFORE switchMessageBranch and internal_execAgentRuntime
+ // CRITICAL: deleteMessage must be called BEFORE switchMessageBranch and executeClientAgent
// If regeneration (which calls switchMessageBranch) happens first, the message
// won't be found in displayMessages and deletion will fail silently.
expect(callOrder[0]).toBe('deleteMessage');
expect(callOrder).toContain('switchMessageBranch');
- expect(callOrder).toContain('internal_execAgentRuntime');
+ expect(callOrder).toContain('executeClientAgent');
// Verify deleteMessage is called before any regeneration-related calls
const deleteIndex = callOrder.indexOf('deleteMessage');
const switchIndex = callOrder.indexOf('switchMessageBranch');
- const execIndex = callOrder.indexOf('internal_execAgentRuntime');
+ const execIndex = callOrder.indexOf('executeClientAgent');
expect(deleteIndex).toBeLessThan(switchIndex);
expect(deleteIndex).toBeLessThan(execIndex);
@@ -619,7 +620,7 @@ describe('Generation Actions', () => {
switchMessageBranch: mockSwitchMessageBranch,
startOperation: mockStartOperation,
completeOperation: mockCompleteOperation,
- internal_execAgentRuntime: mockInternalExecAgentRuntime,
+ executeClientAgent: mockExecuteClientAgent,
isGatewayModeEnabled: mockIsGatewayModeEnabled,
} as any);
@@ -673,7 +674,7 @@ describe('Generation Actions', () => {
startOperation: mockStartOperation,
completeOperation: mockCompleteOperation,
failOperation: mockFailOperation,
- internal_execAgentRuntime: mockInternalExecAgentRuntime,
+ executeClientAgent: mockExecuteClientAgent,
isGatewayModeEnabled: mockIsGatewayModeEnabled,
} as any);
@@ -716,7 +717,7 @@ describe('Generation Actions', () => {
});
});
- it('should pass context to internal_execAgentRuntime', async () => {
+ it('should pass context to executeClientAgent', async () => {
// Re-setup mock with all required properties
const { useChatStore } = await import('@/store/chat');
vi.mocked(useChatStore.getState).mockReturnValue({
@@ -731,7 +732,7 @@ describe('Generation Actions', () => {
startOperation: mockStartOperation,
completeOperation: mockCompleteOperation,
failOperation: mockFailOperation,
- internal_execAgentRuntime: mockInternalExecAgentRuntime,
+ executeClientAgent: mockExecuteClientAgent,
isGatewayModeEnabled: mockIsGatewayModeEnabled,
} as any);
@@ -755,8 +756,8 @@ describe('Generation Actions', () => {
await store.getState().regenerateUserMessage('msg-1');
});
- // Should pass full context to internal_execAgentRuntime
- expect(mockInternalExecAgentRuntime).toHaveBeenCalledWith(
+ // Should pass full context to executeClientAgent
+ expect(mockExecuteClientAgent).toHaveBeenCalledWith(
expect.objectContaining({
context,
parentMessageId: 'msg-1',
@@ -780,7 +781,7 @@ describe('Generation Actions', () => {
startOperation: mockStartOperation,
completeOperation: mockCompleteOperation,
failOperation: mockFailOperation,
- internal_execAgentRuntime: mockInternalExecAgentRuntime,
+ executeClientAgent: mockExecuteClientAgent,
isGatewayModeEnabled: mockIsGatewayModeEnabled,
} as any);
@@ -826,7 +827,7 @@ describe('Generation Actions', () => {
await store.getState().regenerateUserMessage('msg-1');
});
- expect(mockInternalExecAgentRuntime).toHaveBeenCalledWith(
+ expect(mockExecuteClientAgent).toHaveBeenCalledWith(
expect.objectContaining({
initialContext: {
initialContext: {
@@ -851,7 +852,7 @@ describe('Generation Actions', () => {
failOperation: mockFailOperation,
isGatewayModeEnabled: vi.fn(() => true),
executeGatewayAgent: mockExecuteGatewayAgent,
- internal_execAgentRuntime: mockInternalExecAgentRuntime,
+ executeClientAgent: mockExecuteClientAgent,
switchMessageBranch: mockSwitchMessageBranch,
} as any);
@@ -888,8 +889,8 @@ describe('Generation Actions', () => {
}),
);
- // Should NOT call client-mode internal_execAgentRuntime
- expect(mockInternalExecAgentRuntime).not.toHaveBeenCalled();
+ // Should NOT call client-mode executeClientAgent
+ expect(mockExecuteClientAgent).not.toHaveBeenCalled();
// regenerate operation stays running until onComplete is called
expect(mockCompleteOperation).not.toHaveBeenCalled();
@@ -955,7 +956,7 @@ describe('Generation Actions', () => {
failOperation: mockFailOperation,
isGatewayModeEnabled: vi.fn(() => false),
executeGatewayAgent: mockExecuteGatewayAgent,
- internal_execAgentRuntime: mockInternalExecAgentRuntime,
+ executeClientAgent: mockExecuteClientAgent,
switchMessageBranch: mockSwitchMessageBranch,
} as any);
@@ -980,8 +981,8 @@ describe('Generation Actions', () => {
// Should NOT call executeGatewayAgent
expect(mockExecuteGatewayAgent).not.toHaveBeenCalled();
- // Should call client-mode internal_execAgentRuntime
- expect(mockInternalExecAgentRuntime).toHaveBeenCalled();
+ // Should call client-mode executeClientAgent
+ expect(mockExecuteClientAgent).toHaveBeenCalled();
});
it('should not regenerate if message is already loading', async () => {
diff --git a/src/features/Conversation/store/slices/generation/action.ts b/src/features/Conversation/store/slices/generation/action.ts
index 9c1a27e1a40..c1a64b4a2b8 100644
--- a/src/features/Conversation/store/slices/generation/action.ts
+++ b/src/features/Conversation/store/slices/generation/action.ts
@@ -2,7 +2,10 @@ import { AgentManagementIdentifier } from '@lobechat/builtin-tool-agent-manageme
import { type StateCreator } from 'zustand';
import { MESSAGE_CANCEL_FLAT } from '@/const/index';
+import { getAgentStoreState } from '@/store/agent';
+import { agentSelectors } from '@/store/agent/selectors';
import { useChatStore } from '@/store/chat';
+import { selectRuntimeType } from '@/store/chat/slices/aiChat/actions/agentDispatcher';
import {
parseMentionedAgentsFromEditorData,
parseSelectedSkillsFromEditorData,
@@ -214,6 +217,22 @@ export const generationSlice: StateCreator<
if (shouldProceed === false) return;
}
+ const agentConfig = agentSelectors.getAgentConfigById(context.agentId)(getAgentStoreState());
+ const runtimeType = selectRuntimeType({
+ heterogeneousProvider: agentConfig?.agencyConfig?.heterogeneousProvider,
+ isGatewayMode: chatStore.isGatewayModeEnabled(),
+ });
+
+ // TODO(LOBE-8519 follow-up): continue is currently only wired for the client
+ // runtime. Gateway / hetero continue both fall through to the client path
+ // here; a proper implementation needs runtime-specific resume semantics.
+ if (runtimeType !== 'client') {
+ console.warn(
+ `[continueGenerationMessage] runtime=${runtimeType} not yet supported; ` +
+ 'falling through to client mode',
+ );
+ }
+
// Create continue operation with ConversationStore context (includes groupId)
const { operationId } = chatStore.startOperation({
context: { ...context, messageId: displayMessageId },
@@ -222,7 +241,7 @@ export const generationSlice: StateCreator<
try {
// Execute agent runtime with full context from ConversationStore
- await chatStore.internal_execAgentRuntime({
+ await chatStore.executeClientAgent({
context,
messages: displayMessages,
parentMessageId: dbMessageId,
@@ -361,8 +380,14 @@ export const generationSlice: StateCreator<
operationId,
});
+ const agentConfig = agentSelectors.getAgentConfigById(context.agentId)(getAgentStoreState());
+ const runtimeType = selectRuntimeType({
+ heterogeneousProvider: agentConfig?.agencyConfig?.heterogeneousProvider,
+ isGatewayMode: chatStore.isGatewayModeEnabled(),
+ });
+
// ── Gateway mode: trigger server-side regeneration ──
- if (chatStore.isGatewayModeEnabled()) {
+ if (runtimeType === 'gateway') {
// Keep the regenerate operation running until the gateway session completes,
// so isMessageRegenerating stays true and duplicate clicks are blocked.
await chatStore.executeGatewayAgent({
@@ -381,10 +406,14 @@ export const generationSlice: StateCreator<
}
// ── Client mode: run agent locally ──
- // (switchMessageBranch already called above)
+ // TODO(LOBE-8519 follow-up): hetero regenerate is not yet implemented and
+ // currently falls through to client mode (silently uses the agent's underlying
+ // LLM instead of routing back through the heterogeneous CLI). Implementing it
+ // requires the same persistence + executeHeterogeneousAgent setup as
+ // sendMessage's hetero branch.
// Execute agent runtime with full context from ConversationStore
- await chatStore.internal_execAgentRuntime({
+ await chatStore.executeClientAgent({
context,
initialContext,
messages: contextMessages,
diff --git a/src/locales/default/chat.ts b/src/locales/default/chat.ts
index 7684dd8530d..c0d9067c93b 100644
--- a/src/locales/default/chat.ts
+++ b/src/locales/default/chat.ts
@@ -346,8 +346,6 @@ export default {
'pageSelection.reference': 'Selected Text',
'pin': 'Pin',
'pinOff': 'Unpin',
- 'prompts.summaryExpert':
- 'As a summary expert, please summarize the following content based on the system prompts above:',
'rag.referenceChunks': 'Reference Source',
'rag.userQuery.actions.delete': 'Delete Query Rewrite',
'rag.userQuery.actions.regenerate': 'Regenerate Query',
diff --git a/src/locales/default/tool.ts b/src/locales/default/tool.ts
index 9aedd53c37f..de530362482 100644
--- a/src/locales/default/tool.ts
+++ b/src/locales/default/tool.ts
@@ -164,7 +164,6 @@ export default {
'localFiles.writeFile.characters': 'characters',
'localFiles.writeFile.preview': 'Content Preview',
'localFiles.writeFile.truncated': 'truncated',
- 'search.createNewSearch': 'Create a new search record',
'search.emptyResult': 'No results found, please modify your keywords and try again',
'search.genAiMessage': 'Create Agent Message',
'search.includedTooltip':
@@ -198,7 +197,6 @@ export default {
'search.searchTimeRange.value.week': 'Within a week',
'search.searchTimeRange.value.year': 'Within a year',
'search.summary': 'Summary',
- 'search.summaryTooltip': 'Summarize the current content',
'search.viewMoreResults': 'View {{results}} more results',
'updateArgs.duplicateKeyError': 'Field key must be unique',
'updateArgs.form.add': 'Add an Item',
diff --git a/src/store/chat/agents/GroupOrchestration/__tests__/batch-exec-async-tasks.test.ts b/src/store/chat/agents/GroupOrchestration/__tests__/batch-exec-async-tasks.test.ts
index 17114f3a7b2..c5a4b04053e 100644
--- a/src/store/chat/agents/GroupOrchestration/__tests__/batch-exec-async-tasks.test.ts
+++ b/src/store/chat/agents/GroupOrchestration/__tests__/batch-exec-async-tasks.test.ts
@@ -54,7 +54,7 @@ const createMockStore = (overrides: Partial<ChatStore> = {}): ChatStore => {
return {
dbMessagesMap: {},
internal_dispatchMessage: vi.fn(),
- internal_execAgentRuntime: vi.fn().mockResolvedValue(undefined),
+ executeClientAgent: vi.fn().mockResolvedValue(undefined),
messagesMap: {},
operations,
optimisticCreateMessage: vi.fn().mockImplementation(async () => ({
diff --git a/src/store/chat/agents/GroupOrchestration/__tests__/call-supervisor.test.ts b/src/store/chat/agents/GroupOrchestration/__tests__/call-supervisor.test.ts
index ceb5a25b314..fddc9fb3132 100644
--- a/src/store/chat/agents/GroupOrchestration/__tests__/call-supervisor.test.ts
+++ b/src/store/chat/agents/GroupOrchestration/__tests__/call-supervisor.test.ts
@@ -24,7 +24,7 @@ const createMockStore = (overrides: Partial<ChatStore> = {}): ChatStore => {
return {
dbMessagesMap: {},
- internal_execAgentRuntime: vi.fn().mockResolvedValue(undefined),
+ executeClientAgent: vi.fn().mockResolvedValue(undefined),
messagesMap: {},
operations,
startOperation: vi.fn().mockImplementation((config) => {
@@ -80,7 +80,7 @@ const createInitialState = (overrides: Partial<AgentState> = {}): AgentState =>
describe('createGroupOrchestrationExecutors', () => {
describe('call_supervisor executor', () => {
- it('should NOT pass operationId to internal_execAgentRuntime (creates new child operation)', async () => {
+ it('should NOT pass operationId to executeClientAgent (creates new child operation)', async () => {
const mockStore = createMockStore({
dbMessagesMap: {
[`group_${TEST_IDS.GROUP_ID}_${TEST_IDS.TOPIC_ID}`]: [
@@ -116,12 +116,12 @@ describe('createGroupOrchestrationExecutors', () => {
createInitialState(),
);
- // Verify internal_execAgentRuntime was called
- expect(mockStore.internal_execAgentRuntime).toHaveBeenCalledTimes(1);
+ // Verify executeClientAgent was called
+ expect(mockStore.executeClientAgent).toHaveBeenCalledTimes(1);
// Verify operationId is NOT passed (should be undefined)
// This ensures a new child operation is created
- const callArgs = (mockStore.internal_execAgentRuntime as any).mock.calls[0][0];
+ const callArgs = (mockStore.executeClientAgent as any).mock.calls[0][0];
expect(callArgs.operationId).toBeUndefined();
// Verify parentOperationId is passed correctly
@@ -170,7 +170,7 @@ describe('createGroupOrchestrationExecutors', () => {
createInitialState(),
);
- const callArgs = (mockStore.internal_execAgentRuntime as any).mock.calls[0][0];
+ const callArgs = (mockStore.executeClientAgent as any).mock.calls[0][0];
// The key assertion: isSupervisor must be true
// This is used by createAgentExecutors to set metadata.isSupervisor on assistant messages
@@ -184,7 +184,7 @@ describe('createGroupOrchestrationExecutors', () => {
});
describe('call_agent executor', () => {
- it('should NOT pass operationId to internal_execAgentRuntime (creates new child operation)', async () => {
+ it('should NOT pass operationId to executeClientAgent (creates new child operation)', async () => {
const mockStore = createMockStore({
dbMessagesMap: {
[`group_${TEST_IDS.GROUP_ID}_${TEST_IDS.TOPIC_ID}`]: [
@@ -221,11 +221,11 @@ describe('createGroupOrchestrationExecutors', () => {
createInitialState(),
);
- // Verify internal_execAgentRuntime was called
- expect(mockStore.internal_execAgentRuntime).toHaveBeenCalledTimes(1);
+ // Verify executeClientAgent was called
+ expect(mockStore.executeClientAgent).toHaveBeenCalledTimes(1);
// Verify operationId is NOT passed (should be undefined)
- const callArgs = (mockStore.internal_execAgentRuntime as any).mock.calls[0][0];
+ const callArgs = (mockStore.executeClientAgent as any).mock.calls[0][0];
expect(callArgs.operationId).toBeUndefined();
// Verify parentOperationId is passed correctly
@@ -283,11 +283,11 @@ describe('createGroupOrchestrationExecutors', () => {
);
// Verify both were called
- expect(mockStore.internal_execAgentRuntime).toHaveBeenCalledTimes(2);
+ expect(mockStore.executeClientAgent).toHaveBeenCalledTimes(2);
// Get both call arguments
- const supervisorCallArgs = (mockStore.internal_execAgentRuntime as any).mock.calls[0][0];
- const agentCallArgs = (mockStore.internal_execAgentRuntime as any).mock.calls[1][0];
+ const supervisorCallArgs = (mockStore.executeClientAgent as any).mock.calls[0][0];
+ const agentCallArgs = (mockStore.executeClientAgent as any).mock.calls[1][0];
// Both should NOT have operationId (create new child operations)
expect(supervisorCallArgs.operationId).toBeUndefined();
diff --git a/src/store/chat/agents/GroupOrchestration/createGroupOrchestrationExecutors.ts b/src/store/chat/agents/GroupOrchestration/createGroupOrchestrationExecutors.ts
index 00e441317f9..972b75de5db 100644
--- a/src/store/chat/agents/GroupOrchestration/createGroupOrchestrationExecutors.ts
+++ b/src/store/chat/agents/GroupOrchestration/createGroupOrchestrationExecutors.ts
@@ -52,7 +52,7 @@ export interface GroupOrchestrationExecutorsContext {
* │
* └─► call_supervisor Executor
* │
- * ├─► internal_execAgentRuntime(Supervisor)
+ * ├─► executeClientAgent(Supervisor)
* │ │
* │ ├─► Supervisor calls speak tool
* │ │ │
@@ -123,7 +123,7 @@ export const createGroupOrchestrationExecutors = (
// Mark isSupervisor=true so assistant messages get metadata.isSupervisor for UI rendering
// Note: Don't pass operationId - let it create a new child operation (same as call_agent)
// This ensures each call has its own immutable context with isSupervisor properly set
- await get().internal_execAgentRuntime({
+ await get().executeClientAgent({
context: { ...messageContext, agentId: supervisorAgentId, isSupervisor: true },
messages,
parentMessageId: lastMessage.id,
@@ -200,7 +200,7 @@ export const createGroupOrchestrationExecutors = (
// Execute target Agent with subAgentId for agent config retrieval
// - messageContext keeps the group's main conversation context (for message storage)
// - subAgentId specifies which agent's config to use
- await get().internal_execAgentRuntime({
+ await get().executeClientAgent({
context: { ...messageContext, subAgentId: agentId },
messages: messagesWithInstruction,
parentMessageId: lastMessage.id,
@@ -282,7 +282,7 @@ export const createGroupOrchestrationExecutors = (
// - disableTools prevents broadcast agents from calling tools (expected behavior for broadcast)
await Promise.all(
agentIds.map(async (agentId) => {
- await get().internal_execAgentRuntime({
+ await get().executeClientAgent({
context: { ...messageContext, subAgentId: agentId },
disableTools,
messages: messagesWithInstruction,
@@ -334,7 +334,7 @@ export const createGroupOrchestrationExecutors = (
}
// Execute delegated Agent
- await get().internal_execAgentRuntime({
+ await get().executeClientAgent({
context: { ...messageContext, subAgentId: agentId },
messages,
parentMessageId: lastMessage.id,
@@ -595,7 +595,7 @@ export const createGroupOrchestrationExecutors = (
* Flow:
* 1. Create a task message (role: 'task') as placeholder
* 2. Create Thread via API (to get threadId for operation context)
- * 3. Execute using internal_execAgentRuntime (client-side with local tools access)
+ * 3. Execute using executeClientAgent (client-side with local tools access)
* 4. Update Thread status via API on completion
* 5. Update task message content with result
*
@@ -733,10 +733,10 @@ export const createGroupOrchestrationExecutors = (
);
get().replaceMessages(threadMessages, { context: subContext });
- // 6. Execute using internal_execAgentRuntime (client-side with local tools access)
+ // 6. Execute using executeClientAgent (client-side with local tools access)
log(`[${sessionLogId}] Starting client-side AgentRuntime execution`);
- const runtimeResult = await get().internal_execAgentRuntime({
+ const runtimeResult = await get().executeClientAgent({
context: subContext,
messages: threadMessages,
parentMessageId: userMessageId, // Use server-returned userMessageId
diff --git a/src/store/chat/agents/createAgentExecutors.ts b/src/store/chat/agents/createAgentExecutors.ts
index 8666a60f489..ac46bb29223 100644
--- a/src/store/chat/agents/createAgentExecutors.ts
+++ b/src/store/chat/agents/createAgentExecutors.ts
@@ -1988,7 +1988,7 @@ export const createAgentExecutors = (context: {
* Flow:
* 1. Create a task message (role: 'task') as placeholder
* 2. Create Thread via API (for isolation)
- * 3. Execute using internal_execAgentRuntime (client-side)
+ * 3. Execute using executeClientAgent (client-side)
* 4. Update Thread status via API on completion
* 5. Update task message content with result
* 6. Return task_result phase with result
@@ -2207,10 +2207,10 @@ export const createAgentExecutors = (context: {
context.get().replaceMessages(subMessages, { context: subContext });
}
- // 7. Execute using internal_execAgentRuntime (client-side with local tools access)
+ // 7. Execute using executeClientAgent (client-side with local tools access)
log('[%s][exec_client_task] Starting client-side AgentRuntime execution', taskLogId);
- const runtimeResult = await context.get().internal_execAgentRuntime({
+ const runtimeResult = await context.get().executeClientAgent({
context: subContext,
messages: subMessages,
parentMessageId: userMessageId, // Use server-returned userMessageId
@@ -2345,7 +2345,7 @@ export const createAgentExecutors = (context: {
* Flow:
* 1. For each task, create a task message (role: 'task') as placeholder
* 2. Create Thread via API (for isolation)
- * 3. Execute using internal_execAgentRuntime (client-side)
+ * 3. Execute using executeClientAgent (client-side)
* 4. Update Thread status via API on completion
* 5. Update task message content with result
* 6. Return tasks_batch_result phase with all results
@@ -2532,10 +2532,10 @@ export const createAgentExecutors = (context: {
context.get().replaceMessages(subMessages, { context: subContext });
}
- // 7. Execute using internal_execAgentRuntime (client-side with local tools access)
+ // 7. Execute using executeClientAgent (client-side with local tools access)
log('[%s] Starting client-side AgentRuntime execution', taskLogId);
- await context.get().internal_execAgentRuntime({
+ await context.get().executeClientAgent({
context: subContext,
messages: subMessages,
parentMessageId: userMessageId, // Use server-returned userMessageId
diff --git a/src/store/chat/slices/aiChat/actions/__tests__/agentDispatcher.test.ts b/src/store/chat/slices/aiChat/actions/__tests__/agentDispatcher.test.ts
new file mode 100644
index 00000000000..c5cbc5e83fc
--- /dev/null
+++ b/src/store/chat/slices/aiChat/actions/__tests__/agentDispatcher.test.ts
@@ -0,0 +1,69 @@
+import { describe, expect, it } from 'vitest';
+
+import { selectRuntimeType } from '../agentDispatcher';
+
+const heteroProvider = { command: 'claude', type: 'claude-code' as const };
+
+describe('selectRuntimeType', () => {
+ describe('on web (isDesktop = false)', () => {
+ const opts = { isDesktop: false };
+
+ it('returns client when no signal is set', () => {
+ expect(selectRuntimeType({ isGatewayMode: false }, opts)).toBe('client');
+ });
+
+ it('returns gateway when gateway mode is enabled', () => {
+ expect(selectRuntimeType({ isGatewayMode: true }, opts)).toBe('gateway');
+ });
+
+ it('ignores heterogeneousProvider on web — falls through to gateway/client', () => {
+ expect(
+ selectRuntimeType({ heterogeneousProvider: heteroProvider, isGatewayMode: true }, opts),
+ ).toBe('gateway');
+ expect(
+ selectRuntimeType({ heterogeneousProvider: heteroProvider, isGatewayMode: false }, opts),
+ ).toBe('client');
+ });
+ });
+
+ describe('on desktop (isDesktop = true)', () => {
+ const opts = { isDesktop: true };
+
+ it('returns hetero when a heterogeneousProvider is configured', () => {
+ expect(
+ selectRuntimeType({ heterogeneousProvider: heteroProvider, isGatewayMode: true }, opts),
+ ).toBe('hetero');
+ expect(
+ selectRuntimeType({ heterogeneousProvider: heteroProvider, isGatewayMode: false }, opts),
+ ).toBe('hetero');
+ });
+
+ it('falls back to gateway/client when no hetero provider', () => {
+ expect(selectRuntimeType({ isGatewayMode: true }, opts)).toBe('gateway');
+ expect(selectRuntimeType({ isGatewayMode: false }, opts)).toBe('client');
+ });
+ });
+
+ describe('parentRuntime override', () => {
+ it('parentRuntime wins over every other signal', () => {
+ expect(
+ selectRuntimeType(
+ {
+ parentRuntime: 'client',
+ heterogeneousProvider: heteroProvider,
+ isGatewayMode: true,
+ },
+ { isDesktop: true },
+ ),
+ ).toBe('client');
+
+ expect(
+ selectRuntimeType({ parentRuntime: 'gateway', isGatewayMode: false }, { isDesktop: false }),
+ ).toBe('gateway');
+
+ expect(
+ selectRuntimeType({ parentRuntime: 'hetero', isGatewayMode: true }, { isDesktop: false }),
+ ).toBe('hetero');
+ });
+ });
+});
diff --git a/src/store/chat/slices/aiChat/actions/__tests__/conversationControl.test.ts b/src/store/chat/slices/aiChat/actions/__tests__/conversationControl.test.ts
index 45a3b456ba2..8aacd9aa066 100644
--- a/src/store/chat/slices/aiChat/actions/__tests__/conversationControl.test.ts
+++ b/src/store/chat/slices/aiChat/actions/__tests__/conversationControl.test.ts
@@ -486,8 +486,8 @@ describe('ConversationControl actions', () => {
context: { phase: 'init' } as any,
agentConfig: createMockResolvedAgentConfig(),
});
- const internal_execAgentRuntimeSpy = vi
- .spyOn(result.current, 'internal_execAgentRuntime')
+ const executeClientAgentSpy = vi
+ .spyOn(result.current, 'executeClientAgent')
.mockResolvedValue(undefined);
// Call with builder context
@@ -509,8 +509,8 @@ describe('ConversationControl actions', () => {
}),
);
- // Verify internal_execAgentRuntime was called with builder context (now wrapped in context object)
- expect(internal_execAgentRuntimeSpy).toHaveBeenCalledWith(
+ // Verify executeClientAgent was called with builder context (now wrapped in context object)
+ expect(executeClientAgentSpy).toHaveBeenCalledWith(
expect.objectContaining({
context: expect.objectContaining({
agentId: builderAgentId,
@@ -559,8 +559,8 @@ describe('ConversationControl actions', () => {
context: { phase: 'init' } as any,
agentConfig: createMockResolvedAgentConfig(),
});
- const internal_execAgentRuntimeSpy = vi
- .spyOn(result.current, 'internal_execAgentRuntime')
+ const executeClientAgentSpy = vi
+ .spyOn(result.current, 'executeClientAgent')
.mockResolvedValue(undefined);
// Call without context (should use global state)
@@ -576,8 +576,8 @@ describe('ConversationControl actions', () => {
}),
);
- // Verify internal_execAgentRuntime was called with global context (now wrapped in context object)
- expect(internal_execAgentRuntimeSpy).toHaveBeenCalledWith(
+ // Verify executeClientAgent was called with global context (now wrapped in context object)
+ expect(executeClientAgentSpy).toHaveBeenCalledWith(
expect.objectContaining({
context: expect.objectContaining({
agentId: globalAgentId,
@@ -599,16 +599,16 @@ describe('ConversationControl actions', () => {
});
});
- const internal_execAgentRuntimeSpy = vi
- .spyOn(result.current, 'internal_execAgentRuntime')
+ const executeClientAgentSpy = vi
+ .spyOn(result.current, 'executeClientAgent')
.mockResolvedValue(undefined);
await act(async () => {
await result.current.approveToolCalling('non-existent-msg', 'group-1');
});
- // Should not call internal_execAgentRuntime when tool message not found
- expect(internal_execAgentRuntimeSpy).not.toHaveBeenCalled();
+ // Should not call executeClientAgent when tool message not found
+ expect(executeClientAgentSpy).not.toHaveBeenCalled();
});
describe('server-mode branch', () => {
@@ -655,8 +655,8 @@ describe('ConversationControl actions', () => {
const executeGatewayAgentSpy = vi
.spyOn(result.current, 'executeGatewayAgent')
.mockResolvedValue({} as any);
- const internal_execAgentRuntimeSpy = vi
- .spyOn(result.current, 'internal_execAgentRuntime')
+ const executeClientAgentSpy = vi
+ .spyOn(result.current, 'executeClientAgent')
.mockResolvedValue(undefined);
await act(async () => {
@@ -674,7 +674,7 @@ describe('ConversationControl actions', () => {
},
}),
);
- expect(internal_execAgentRuntimeSpy).not.toHaveBeenCalled();
+ expect(executeClientAgentSpy).not.toHaveBeenCalled();
// Fallback guard: the paused `execServerAgentRuntime` op in this
// context must be completed so the loading state doesn't bleed
@@ -736,8 +736,8 @@ describe('ConversationControl actions', () => {
const executeGatewayAgentSpy = vi
.spyOn(result.current, 'executeGatewayAgent')
.mockResolvedValue({} as any);
- const internal_execAgentRuntimeSpy = vi
- .spyOn(result.current, 'internal_execAgentRuntime')
+ const executeClientAgentSpy = vi
+ .spyOn(result.current, 'executeClientAgent')
.mockResolvedValue(undefined);
await act(async () => {
@@ -756,7 +756,7 @@ describe('ConversationControl actions', () => {
}),
}),
);
- expect(internal_execAgentRuntimeSpy).not.toHaveBeenCalled();
+ expect(executeClientAgentSpy).not.toHaveBeenCalled();
executeGatewayAgentSpy.mockRestore();
});
@@ -851,8 +851,8 @@ describe('ConversationControl actions', () => {
const executeGatewayAgentSpy = vi
.spyOn(result.current, 'executeGatewayAgent')
.mockResolvedValue({} as any);
- const internal_execAgentRuntimeSpy = vi
- .spyOn(result.current, 'internal_execAgentRuntime')
+ const executeClientAgentSpy = vi
+ .spyOn(result.current, 'executeClientAgent')
.mockResolvedValue(undefined);
await act(async () => {
@@ -860,7 +860,7 @@ describe('ConversationControl actions', () => {
});
expect(executeGatewayAgentSpy).not.toHaveBeenCalled();
- expect(internal_execAgentRuntimeSpy).toHaveBeenCalled();
+ expect(executeClientAgentSpy).toHaveBeenCalled();
executeGatewayAgentSpy.mockRestore();
});
@@ -908,8 +908,8 @@ describe('ConversationControl actions', () => {
const executeGatewayAgentSpy = vi
.spyOn(result.current, 'executeGatewayAgent')
.mockResolvedValue({} as any);
- const internal_execAgentRuntimeSpy = vi
- .spyOn(result.current, 'internal_execAgentRuntime')
+ const executeClientAgentSpy = vi
+ .spyOn(result.current, 'executeClientAgent')
.mockResolvedValue(undefined);
await act(async () => {
@@ -927,7 +927,7 @@ describe('ConversationControl actions', () => {
resumeApproval: expect.objectContaining({ decision: 'approved' }),
}),
);
- expect(internal_execAgentRuntimeSpy).not.toHaveBeenCalled();
+ expect(executeClientAgentSpy).not.toHaveBeenCalled();
executeGatewayAgentSpy.mockRestore();
});
@@ -1026,8 +1026,8 @@ describe('ConversationControl actions', () => {
const executeGatewayAgentSpy = vi
.spyOn(result.current, 'executeGatewayAgent')
.mockResolvedValue({} as any);
- const internal_execAgentRuntimeSpy = vi
- .spyOn(result.current, 'internal_execAgentRuntime')
+ const executeClientAgentSpy = vi
+ .spyOn(result.current, 'executeClientAgent')
.mockResolvedValue(undefined);
// Ensure client rejectToolCalling is NOT invoked in server-mode path —
// otherwise the server would see a duplicate halting `reject` before
@@ -1052,7 +1052,7 @@ describe('ConversationControl actions', () => {
},
}),
);
- expect(internal_execAgentRuntimeSpy).not.toHaveBeenCalled();
+ expect(executeClientAgentSpy).not.toHaveBeenCalled();
expect(rejectToolCallingSpy).not.toHaveBeenCalled();
executeGatewayAgentSpy.mockRestore();
@@ -1132,8 +1132,8 @@ describe('ConversationControl actions', () => {
context: initialContext,
state: {} as any,
});
- const internal_execAgentRuntimeSpy = vi
- .spyOn(result.current, 'internal_execAgentRuntime')
+ const executeClientAgentSpy = vi
+ .spyOn(result.current, 'executeClientAgent')
.mockResolvedValue(undefined);
await act(async () => {
@@ -1159,7 +1159,7 @@ describe('ConversationControl actions', () => {
}),
);
- expect(internal_execAgentRuntimeSpy).toHaveBeenCalledWith(
+ expect(executeClientAgentSpy).toHaveBeenCalledWith(
expect.objectContaining({
initialContext,
parentMessageId: userMessageId,
@@ -1239,8 +1239,8 @@ describe('ConversationControl actions', () => {
context: initialContext,
state: {} as any,
});
- const internal_execAgentRuntimeSpy = vi
- .spyOn(result.current, 'internal_execAgentRuntime')
+ const executeClientAgentSpy = vi
+ .spyOn(result.current, 'executeClientAgent')
.mockResolvedValue(undefined);
await act(async () => {
@@ -1266,7 +1266,7 @@ describe('ConversationControl actions', () => {
}),
);
- expect(internal_execAgentRuntimeSpy).toHaveBeenCalledWith(
+ expect(executeClientAgentSpy).toHaveBeenCalledWith(
expect.objectContaining({
initialContext,
parentMessageId: userMessageId,
@@ -1323,8 +1323,8 @@ describe('ConversationControl actions', () => {
context: { phase: 'init' } as any,
agentConfig: createMockResolvedAgentConfig(),
});
- const internal_execAgentRuntimeSpy = vi
- .spyOn(result.current, 'internal_execAgentRuntime')
+ const executeClientAgentSpy = vi
+ .spyOn(result.current, 'executeClientAgent')
.mockResolvedValue(undefined);
// Call with builder context
@@ -1346,8 +1346,8 @@ describe('ConversationControl actions', () => {
}),
);
- // Verify internal_execAgentRuntime was called with builder context (now wrapped in context object)
- expect(internal_execAgentRuntimeSpy).toHaveBeenCalledWith(
+ // Verify executeClientAgent was called with builder context (now wrapped in context object)
+ expect(executeClientAgentSpy).toHaveBeenCalledWith(
expect.objectContaining({
context: expect.objectContaining({
agentId: builderAgentId,
@@ -1397,8 +1397,8 @@ describe('ConversationControl actions', () => {
context: { phase: 'init' } as any,
agentConfig: createMockResolvedAgentConfig(),
});
- const internal_execAgentRuntimeSpy = vi
- .spyOn(result.current, 'internal_execAgentRuntime')
+ const executeClientAgentSpy = vi
+ .spyOn(result.current, 'executeClientAgent')
.mockResolvedValue(undefined);
// Call without context
@@ -1414,8 +1414,8 @@ describe('ConversationControl actions', () => {
}),
);
- // Verify internal_execAgentRuntime was called with global context
- expect(internal_execAgentRuntimeSpy).toHaveBeenCalledWith(
+ // Verify executeClientAgent was called with global context
+ expect(executeClientAgentSpy).toHaveBeenCalledWith(
expect.objectContaining({
context: expect.objectContaining({
agentId: globalAgentId,
diff --git a/src/store/chat/slices/aiChat/actions/__tests__/conversationLifecycle.test.ts b/src/store/chat/slices/aiChat/actions/__tests__/conversationLifecycle.test.ts
index e967c92a0d2..c754be80457 100644
--- a/src/store/chat/slices/aiChat/actions/__tests__/conversationLifecycle.test.ts
+++ b/src/store/chat/slices/aiChat/actions/__tests__/conversationLifecycle.test.ts
@@ -67,7 +67,7 @@ beforeEach(() => {
useChatStore.setState({
refreshMessages: vi.fn(),
refreshTopic: vi.fn(),
- internal_execAgentRuntime: vi.fn(),
+ executeClientAgent: vi.fn(),
mainInputEditor: null,
});
});
@@ -99,7 +99,7 @@ describe('ConversationLifecycle actions', () => {
});
});
- expect(result.current.internal_execAgentRuntime).not.toHaveBeenCalled();
+ expect(result.current.executeClientAgent).not.toHaveBeenCalled();
});
it('should not send when message is empty and no files are provided', async () => {
@@ -112,7 +112,7 @@ describe('ConversationLifecycle actions', () => {
});
});
- expect(result.current.internal_execAgentRuntime).not.toHaveBeenCalled();
+ expect(result.current.executeClientAgent).not.toHaveBeenCalled();
});
it('should not send when message is empty with empty files array', async () => {
@@ -126,7 +126,7 @@ describe('ConversationLifecycle actions', () => {
});
});
- expect(result.current.internal_execAgentRuntime).not.toHaveBeenCalled();
+ expect(result.current.executeClientAgent).not.toHaveBeenCalled();
});
});
@@ -246,7 +246,7 @@ describe('ConversationLifecycle actions', () => {
});
});
- expect(result.current.internal_execAgentRuntime).not.toHaveBeenCalled();
+ expect(result.current.executeClientAgent).not.toHaveBeenCalled();
});
it('should restore the pre-send editor snapshot when server send fails', async () => {
@@ -320,7 +320,7 @@ describe('ConversationLifecycle actions', () => {
});
});
- expect(result.current.internal_execAgentRuntime).toHaveBeenCalled();
+ expect(result.current.executeClientAgent).toHaveBeenCalled();
});
it('should persist selected slash skills into user message content before sending', async () => {
@@ -418,7 +418,7 @@ describe('ConversationLifecycle actions', () => {
}),
]),
);
- expect(result.current.internal_execAgentRuntime).toHaveBeenCalled();
+ expect(result.current.executeClientAgent).toHaveBeenCalled();
});
it('should work when sending from home page (activeAgentId is empty but context.agentId exists)', async () => {
@@ -463,7 +463,7 @@ describe('ConversationLifecycle actions', () => {
}),
expect.any(AbortController),
);
- expect(result.current.internal_execAgentRuntime).toHaveBeenCalled();
+ expect(result.current.executeClientAgent).toHaveBeenCalled();
});
it('should persist selected tool tags into user message content before runtime execution', async () => {
@@ -520,7 +520,7 @@ describe('ConversationLifecycle actions', () => {
expect(requestPayload?.newUserMessage.content).toContain('name="Notebook"');
expect(requestPayload?.newUserMessage.content).toContain('identifier="lobe-artifacts"');
expect(requestPayload?.newUserMessage.content).toContain('name="Artifacts"');
- expect(result.current.internal_execAgentRuntime).toHaveBeenCalled();
+ expect(result.current.executeClientAgent).toHaveBeenCalled();
});
it('should preserve editorData when enqueueing a queued message', async () => {
@@ -984,8 +984,7 @@ describe('ConversationLifecycle actions', () => {
});
});
- const runtimePayload = vi.mocked(result.current.internal_execAgentRuntime).mock
- .calls[0]?.[0];
+ const runtimePayload = vi.mocked(result.current.executeClientAgent).mock.calls[0]?.[0];
const runtimeUserMessage = runtimePayload?.messages.find(
(message) => message.id === TEST_IDS.USER_MESSAGE_ID,
);
@@ -1120,7 +1119,7 @@ describe('ConversationLifecycle actions', () => {
);
// But runtime should receive mentionedAgents in initialContext
- expect(result.current.internal_execAgentRuntime).toHaveBeenCalledWith(
+ expect(result.current.executeClientAgent).toHaveBeenCalledWith(
expect.objectContaining({
initialContext: expect.objectContaining({
initialContext: expect.objectContaining({
@@ -1234,7 +1233,7 @@ describe('ConversationLifecycle actions', () => {
}),
);
- const execCall = (result.current.internal_execAgentRuntime as any).mock.calls[0]?.[0];
+ const execCall = (result.current.executeClientAgent as any).mock.calls[0]?.[0];
expect(execCall).toEqual(
expect.objectContaining({
context: expect.objectContaining({
@@ -1304,7 +1303,7 @@ describe('ConversationLifecycle actions', () => {
});
expect(agentService.getAgentConfigById).not.toHaveBeenCalledWith('agent-a');
- expect(result.current.internal_execAgentRuntime).toHaveBeenCalledWith(
+ expect(result.current.executeClientAgent).toHaveBeenCalledWith(
expect.objectContaining({
initialContext: expect.objectContaining({
initialContext: expect.objectContaining({
@@ -1375,7 +1374,7 @@ describe('ConversationLifecycle actions', () => {
});
// Runtime should NOT receive mentionedAgents in group context
- const execCall = (result.current.internal_execAgentRuntime as any).mock.calls[0]?.[0];
+ const execCall = (result.current.executeClientAgent as any).mock.calls[0]?.[0];
const initialCtx = execCall?.initialContext?.initialContext;
expect(initialCtx?.mentionedAgents).toBeUndefined();
});
diff --git a/src/store/chat/slices/aiChat/actions/__tests__/streamingExecutor.test.ts b/src/store/chat/slices/aiChat/actions/__tests__/streamingExecutor.test.ts
index 3f430dedebd..6ceb9b051fa 100644
--- a/src/store/chat/slices/aiChat/actions/__tests__/streamingExecutor.test.ts
+++ b/src/store/chat/slices/aiChat/actions/__tests__/streamingExecutor.test.ts
@@ -34,7 +34,7 @@ vi.mock('@/store/serverConfig', () => ({
},
}));
-const realExecAgentRuntime = useChatStore.getState().internal_execAgentRuntime;
+const realExecAgentRuntime = useChatStore.getState().executeClientAgent;
beforeEach(() => {
resetTestEnvironment();
@@ -45,7 +45,7 @@ beforeEach(() => {
act(() => {
useChatStore.setState({
refreshMessages: vi.fn(),
- internal_execAgentRuntime: vi.fn(),
+ executeClientAgent: vi.fn(),
});
});
});
@@ -56,10 +56,10 @@ afterEach(() => {
});
describe('StreamingExecutor actions', () => {
- describe('internal_execAgentRuntime', () => {
+ describe('executeClientAgent', () => {
it('should handle the core AI message processing', async () => {
act(() => {
- useChatStore.setState({ internal_execAgentRuntime: realExecAgentRuntime });
+ useChatStore.setState({ executeClientAgent: realExecAgentRuntime });
});
const { result } = renderHook(() => useChatStore());
@@ -79,7 +79,7 @@ describe('StreamingExecutor actions', () => {
});
await act(async () => {
- await result.current.internal_execAgentRuntime({
+ await result.current.executeClientAgent({
context: { agentId: TEST_IDS.SESSION_ID, topicId: TEST_IDS.TOPIC_ID },
messages,
parentMessageId: userMessage.id,
@@ -100,7 +100,7 @@ describe('StreamingExecutor actions', () => {
it('should stop agent runtime loop when operation is cancelled before step execution', async () => {
act(() => {
- useChatStore.setState({ internal_execAgentRuntime: realExecAgentRuntime });
+ useChatStore.setState({ executeClientAgent: realExecAgentRuntime });
});
const { result } = renderHook(() => useChatStore());
@@ -139,7 +139,7 @@ describe('StreamingExecutor actions', () => {
});
await act(async () => {
- await result.current.internal_execAgentRuntime({
+ await result.current.executeClientAgent({
context: { agentId: TEST_IDS.SESSION_ID, topicId: TEST_IDS.TOPIC_ID },
messages: [userMessage],
parentMessageId: userMessage.id,
@@ -157,7 +157,7 @@ describe('StreamingExecutor actions', () => {
it('should stop agent runtime loop when operation is cancelled after step completion', async () => {
act(() => {
- useChatStore.setState({ internal_execAgentRuntime: realExecAgentRuntime });
+ useChatStore.setState({ executeClientAgent: realExecAgentRuntime });
});
const { result } = renderHook(() => useChatStore());
@@ -200,7 +200,7 @@ describe('StreamingExecutor actions', () => {
});
await act(async () => {
- await result.current.internal_execAgentRuntime({
+ await result.current.executeClientAgent({
context: { agentId: TEST_IDS.SESSION_ID, topicId: TEST_IDS.TOPIC_ID },
messages: [userMessage],
parentMessageId: userMessage.id,
@@ -228,7 +228,7 @@ describe('StreamingExecutor actions', () => {
it('should resolve aborted tools when cancelled after LLM returns tool calls', async () => {
act(() => {
- useChatStore.setState({ internal_execAgentRuntime: realExecAgentRuntime });
+ useChatStore.setState({ executeClientAgent: realExecAgentRuntime });
});
const { result } = renderHook(() => useChatStore());
@@ -279,7 +279,7 @@ describe('StreamingExecutor actions', () => {
});
await act(async () => {
- await result.current.internal_execAgentRuntime({
+ await result.current.executeClientAgent({
context: { agentId: TEST_IDS.SESSION_ID, topicId: TEST_IDS.TOPIC_ID },
messages: [userMessage],
parentMessageId: userMessage.id,
@@ -305,7 +305,7 @@ describe('StreamingExecutor actions', () => {
it('should use provided context for trace parameters', async () => {
act(() => {
useChatStore.setState({
- internal_execAgentRuntime: realExecAgentRuntime,
+ executeClientAgent: realExecAgentRuntime,
activeAgentId: 'active-session',
activeTopicId: 'active-topic',
});
@@ -325,7 +325,7 @@ describe('StreamingExecutor actions', () => {
const streamSpy = vi.spyOn(chatService, 'createAssistantMessageStream');
await act(async () => {
- await result.current.internal_execAgentRuntime({
+ await result.current.executeClientAgent({
context: { agentId: contextSessionId, topicId: contextTopicId },
messages: [userMessage],
parentMessageId: userMessage.id,
@@ -351,10 +351,10 @@ describe('StreamingExecutor actions', () => {
it('should execute afterCompletion callbacks after runtime completes', async () => {
const { result } = renderHook(() => useChatStore());
- // Restore real internal_execAgentRuntime for this test
+ // Restore real executeClientAgent for this test
act(() => {
useChatStore.setState({
- internal_execAgentRuntime: realExecAgentRuntime,
+ executeClientAgent: realExecAgentRuntime,
});
});
@@ -431,9 +431,9 @@ describe('StreamingExecutor actions', () => {
agentConfig: createMockResolvedAgentConfig(),
});
- // Execute internal_execAgentRuntime with the pre-created operationId
+ // Execute executeClientAgent with the pre-created operationId
await act(async () => {
- await result.current.internal_execAgentRuntime({
+ await result.current.executeClientAgent({
context: {
agentId: TEST_IDS.SESSION_ID,
topicId: TEST_IDS.TOPIC_ID,
@@ -453,10 +453,10 @@ describe('StreamingExecutor actions', () => {
it('should continue execution even if a callback throws an error', async () => {
const { result } = renderHook(() => useChatStore());
- // Restore real internal_execAgentRuntime for this test
+ // Restore real executeClientAgent for this test
act(() => {
useChatStore.setState({
- internal_execAgentRuntime: realExecAgentRuntime,
+ executeClientAgent: realExecAgentRuntime,
});
});
@@ -531,7 +531,7 @@ describe('StreamingExecutor actions', () => {
const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
await act(async () => {
- await result.current.internal_execAgentRuntime({
+ await result.current.executeClientAgent({
context: {
agentId: TEST_IDS.SESSION_ID,
topicId: TEST_IDS.TOPIC_ID,
@@ -549,7 +549,7 @@ describe('StreamingExecutor actions', () => {
// Error should have been logged
expect(consoleErrorSpy).toHaveBeenCalledWith(
- '[internal_execAgentRuntime] afterCompletion callback error:',
+ '[executeClientAgent] afterCompletion callback error:',
expect.any(Error),
);
@@ -559,10 +559,10 @@ describe('StreamingExecutor actions', () => {
it('should not fail when no afterCompletion callbacks are registered', async () => {
const { result } = renderHook(() => useChatStore());
- // Restore real internal_execAgentRuntime for this test
+ // Restore real executeClientAgent for this test
act(() => {
useChatStore.setState({
- internal_execAgentRuntime: realExecAgentRuntime,
+ executeClientAgent: realExecAgentRuntime,
});
});
@@ -630,7 +630,7 @@ describe('StreamingExecutor actions', () => {
// Should not throw
await act(async () => {
- await result.current.internal_execAgentRuntime({
+ await result.current.executeClientAgent({
context: {
agentId: TEST_IDS.SESSION_ID,
topicId: TEST_IDS.TOPIC_ID,
@@ -650,7 +650,7 @@ describe('StreamingExecutor actions', () => {
describe('initialContext preservation', () => {
it('should preserve initialContext through multiple steps in agent runtime loop', async () => {
act(() => {
- useChatStore.setState({ internal_execAgentRuntime: realExecAgentRuntime });
+ useChatStore.setState({ executeClientAgent: realExecAgentRuntime });
});
const { result } = renderHook(() => useChatStore());
@@ -707,7 +707,7 @@ describe('StreamingExecutor actions', () => {
});
await act(async () => {
- await result.current.internal_execAgentRuntime({
+ await result.current.executeClientAgent({
context: { agentId: TEST_IDS.SESSION_ID, topicId: TEST_IDS.TOPIC_ID },
messages: [userMessage],
parentMessageId: userMessage.id,
@@ -729,7 +729,7 @@ describe('StreamingExecutor actions', () => {
it('should preserve initialContext when result.nextContext does not include it', async () => {
act(() => {
- useChatStore.setState({ internal_execAgentRuntime: realExecAgentRuntime });
+ useChatStore.setState({ executeClientAgent: realExecAgentRuntime });
});
const { result } = renderHook(() => useChatStore());
@@ -788,7 +788,7 @@ describe('StreamingExecutor actions', () => {
});
await act(async () => {
- await result.current.internal_execAgentRuntime({
+ await result.current.executeClientAgent({
context: { agentId: TEST_IDS.SESSION_ID, topicId: TEST_IDS.TOPIC_ID },
messages: [userMessage],
parentMessageId: userMessage.id,
@@ -808,7 +808,7 @@ describe('StreamingExecutor actions', () => {
it('should merge provided initialContext with runtime page editor context', () => {
act(() => {
- useChatStore.setState({ internal_execAgentRuntime: realExecAgentRuntime });
+ useChatStore.setState({ executeClientAgent: realExecAgentRuntime });
});
const { result } = renderHook(() => useChatStore());
@@ -876,7 +876,7 @@ describe('StreamingExecutor actions', () => {
it('should not inject page editor context outside page scope', () => {
act(() => {
- useChatStore.setState({ internal_execAgentRuntime: realExecAgentRuntime });
+ useChatStore.setState({ executeClientAgent: realExecAgentRuntime });
});
const { result } = renderHook(() => useChatStore());
@@ -925,7 +925,7 @@ describe('StreamingExecutor actions', () => {
it('should merge selectedTools into generated tools when provided', () => {
act(() => {
- useChatStore.setState({ internal_execAgentRuntime: realExecAgentRuntime });
+ useChatStore.setState({ executeClientAgent: realExecAgentRuntime });
});
const { result } = renderHook(() => useChatStore());
@@ -976,7 +976,7 @@ describe('StreamingExecutor actions', () => {
it('should enable visual understanding when a previous user message has visual media', () => {
act(() => {
- useChatStore.setState({ internal_execAgentRuntime: realExecAgentRuntime });
+ useChatStore.setState({ executeClientAgent: realExecAgentRuntime });
});
serverConfigMock.enableVisualUnderstanding = true;
@@ -1030,7 +1030,7 @@ describe('StreamingExecutor actions', () => {
it('should not enable visual understanding when the active LobeHub model supports visual media natively', () => {
act(() => {
- useChatStore.setState({ internal_execAgentRuntime: realExecAgentRuntime });
+ useChatStore.setState({ executeClientAgent: realExecAgentRuntime });
});
serverConfigMock.enableVisualUnderstanding = true;
@@ -1097,7 +1097,7 @@ describe('StreamingExecutor actions', () => {
it('should use excludeDefaultToolIds (not skipDefaultTools) in manual mode for builtin agents', () => {
act(() => {
- useChatStore.setState({ internal_execAgentRuntime: realExecAgentRuntime });
+ useChatStore.setState({ executeClientAgent: realExecAgentRuntime });
});
const { result } = renderHook(() => useChatStore());
@@ -1144,7 +1144,7 @@ describe('StreamingExecutor actions', () => {
it('should use excludeDefaultToolIds in manual mode for regular agents', () => {
act(() => {
- useChatStore.setState({ internal_execAgentRuntime: realExecAgentRuntime });
+ useChatStore.setState({ executeClientAgent: realExecAgentRuntime });
});
const { result } = renderHook(() => useChatStore());
@@ -1189,7 +1189,7 @@ describe('StreamingExecutor actions', () => {
it('should not set excludeDefaultToolIds in auto mode', () => {
act(() => {
- useChatStore.setState({ internal_execAgentRuntime: realExecAgentRuntime });
+ useChatStore.setState({ executeClientAgent: realExecAgentRuntime });
});
const { result } = renderHook(() => useChatStore());
@@ -1235,7 +1235,7 @@ describe('StreamingExecutor actions', () => {
it('should preserve default model/provider payload when initialContext is provided', () => {
act(() => {
- useChatStore.setState({ internal_execAgentRuntime: realExecAgentRuntime });
+ useChatStore.setState({ executeClientAgent: realExecAgentRuntime });
});
const { result } = renderHook(() => useChatStore());
@@ -1288,7 +1288,7 @@ describe('StreamingExecutor actions', () => {
it('should pass merged resolvedAgentConfig to chatService when selectedTools are provided', async () => {
act(() => {
- useChatStore.setState({ internal_execAgentRuntime: realExecAgentRuntime });
+ useChatStore.setState({ executeClientAgent: realExecAgentRuntime });
});
const { result } = renderHook(() => useChatStore());
@@ -1344,7 +1344,7 @@ describe('StreamingExecutor actions', () => {
});
await act(async () => {
- await result.current.internal_execAgentRuntime({
+ await result.current.executeClientAgent({
context: { agentId: TEST_IDS.SESSION_ID, topicId: TEST_IDS.TOPIC_ID },
initialContext: {
phase: 'init',
@@ -1365,7 +1365,7 @@ describe('StreamingExecutor actions', () => {
describe('internal_createAgentState with disableTools', () => {
it('should return empty toolManifestMap when disableTools is true', async () => {
act(() => {
- useChatStore.setState({ internal_execAgentRuntime: realExecAgentRuntime });
+ useChatStore.setState({ executeClientAgent: realExecAgentRuntime });
});
const { result } = renderHook(() => useChatStore());
@@ -1392,7 +1392,7 @@ describe('StreamingExecutor actions', () => {
it('should return empty tools in agentConfig when disableTools is true', async () => {
act(() => {
- useChatStore.setState({ internal_execAgentRuntime: realExecAgentRuntime });
+ useChatStore.setState({ executeClientAgent: realExecAgentRuntime });
});
const { result } = renderHook(() => useChatStore());
@@ -1421,7 +1421,7 @@ describe('StreamingExecutor actions', () => {
it('should include tools in toolManifestMap when disableTools is false or undefined', async () => {
act(() => {
- useChatStore.setState({ internal_execAgentRuntime: realExecAgentRuntime });
+ useChatStore.setState({ executeClientAgent: realExecAgentRuntime });
});
const { result } = renderHook(() => useChatStore());
@@ -1473,10 +1473,10 @@ describe('StreamingExecutor actions', () => {
it('should complete operation when state is waiting_for_human', async () => {
const { result } = renderHook(() => useChatStore());
- // Restore real internal_execAgentRuntime for this test
+ // Restore real executeClientAgent for this test
act(() => {
useChatStore.setState({
- internal_execAgentRuntime: realExecAgentRuntime,
+ executeClientAgent: realExecAgentRuntime,
});
});
@@ -1546,7 +1546,7 @@ describe('StreamingExecutor actions', () => {
});
await act(async () => {
- await result.current.internal_execAgentRuntime({
+ await result.current.executeClientAgent({
context: {
agentId: TEST_IDS.SESSION_ID,
topicId: TEST_IDS.TOPIC_ID,
@@ -1568,10 +1568,10 @@ describe('StreamingExecutor actions', () => {
it('should fail operation when state is error', async () => {
const { result } = renderHook(() => useChatStore());
- // Restore real internal_execAgentRuntime for this test
+ // Restore real executeClientAgent for this test
act(() => {
useChatStore.setState({
- internal_execAgentRuntime: realExecAgentRuntime,
+ executeClientAgent: realExecAgentRuntime,
});
});
@@ -1641,7 +1641,7 @@ describe('StreamingExecutor actions', () => {
});
await act(async () => {
- await result.current.internal_execAgentRuntime({
+ await result.current.executeClientAgent({
context: {
agentId: TEST_IDS.SESSION_ID,
topicId: TEST_IDS.TOPIC_ID,
diff --git a/src/store/chat/slices/aiChat/actions/agentDispatcher.ts b/src/store/chat/slices/aiChat/actions/agentDispatcher.ts
new file mode 100644
index 00000000000..1cc5d5165c3
--- /dev/null
+++ b/src/store/chat/slices/aiChat/actions/agentDispatcher.ts
@@ -0,0 +1,51 @@
+import { isDesktop as defaultIsDesktop } from '@lobechat/const';
+import { type HeterogeneousProviderConfig } from '@lobechat/types';
+
+/**
+ * Which agent runtime should handle an operation.
+ *
+ * - `client`: in-browser AgentRuntime (default)
+ * - `gateway`: cloud sandbox via Gateway WebSocket
+ * - `hetero`: heterogeneous CLI agent (Claude Code, Codex, …) via desktop IPC or sandbox
+ */
+export type AgentRuntimeType = 'client' | 'gateway' | 'hetero';
+
+export interface RuntimeSelectionContext {
+ /** Per-agent heterogeneous provider config (desktop only — takes priority over gateway). */
+ heterogeneousProvider?: HeterogeneousProviderConfig;
+ /** Result of `chatStore.isGatewayModeEnabled()`. */
+ isGatewayMode: boolean;
+ /**
+ * Explicit override that wins over automatic selection.
+ *
+ * Used by sub-agent dispatches (`directMentionRoute`, `callAgent`) so child
+ * operations inherit the parent operation's runtime instead of re-running
+ * the global decision — a sub-agent spawned inside a Gateway run should
+ * stay on Gateway, even if its own agent config would say otherwise.
+ */
+ parentRuntime?: AgentRuntimeType;
+}
+
+interface SelectRuntimeTypeOptions {
+ /** Override of `isDesktop` for testability. Defaults to the build-time const. */
+ isDesktop?: boolean;
+}
+
+/**
+ * Centralized "which runtime should run this agent operation" decision.
+ *
+ * The same priority is applied at every entry point (sendMessage, regenerate,
+ * resume, continue, sub-agent dispatch, …) so adding a new entry point does
+ * not require re-deriving the routing rules.
+ *
+ * Priority: `parentRuntime` > `hetero` (desktop only) > `gateway` > `client`.
+ */
+export const selectRuntimeType = (
+ ctx: RuntimeSelectionContext,
+ { isDesktop = defaultIsDesktop }: SelectRuntimeTypeOptions = {},
+): AgentRuntimeType => {
+ if (ctx.parentRuntime) return ctx.parentRuntime;
+ if (isDesktop && ctx.heterogeneousProvider) return 'hetero';
+ if (ctx.isGatewayMode) return 'gateway';
+ return 'client';
+};
diff --git a/src/store/chat/slices/aiChat/actions/conversationControl.ts b/src/store/chat/slices/aiChat/actions/conversationControl.ts
index 0c0b7c905f7..7c9f5548ad0 100644
--- a/src/store/chat/slices/aiChat/actions/conversationControl.ts
+++ b/src/store/chat/slices/aiChat/actions/conversationControl.ts
@@ -3,6 +3,9 @@ import { type AgentRuntimeContext } from '@lobechat/agent-runtime';
import { MESSAGE_CANCEL_FLAT } from '@lobechat/const';
import { type ConversationContext } from '@lobechat/types';
+import { getAgentStoreState } from '@/store/agent';
+import { agentSelectors } from '@/store/agent/selectors';
+import { selectRuntimeType } from '@/store/chat/slices/aiChat/actions/agentDispatcher';
import { operationSelectors } from '@/store/chat/slices/operation/selectors';
import { AI_RUNTIME_OPERATION_TYPES } from '@/store/chat/slices/operation/types';
import { type ChatStore } from '@/store/chat/store';
@@ -33,11 +36,12 @@ export class ConversationControlActionImpl {
/**
* Decide whether approve/reject/reject_continue should go through the
* Gateway resume path (new op carrying `resumeApproval`) instead of the
- * local `internal_execAgentRuntime` path. Mirrors the "interrupt + new op"
+ * local `executeClientAgent` path. Mirrors the "interrupt + new op"
* pattern from LOBE-7142.
*
- * Uses the same `isGatewayModeEnabled()` lab flag that routes the initial
- * send, so approve/reject align with how the conversation was dispatched.
+ * Routes via `selectRuntimeType` so approve/reject align with how the
+ * conversation was dispatched at sendMessage time. Hetero resume is not yet
+ * implemented and falls through to client local resume — see LOBE-8519.
*
* We deliberately do **not** look for a living `execServerAgentRuntime`
* op here. The server's `waiting_for_human` → `agent_runtime_end` signal
@@ -47,8 +51,16 @@ export class ConversationControlActionImpl {
* scanning for it would flip us back into client-mode against a live
* Gateway backend.
*/
- #shouldUseGatewayResume = (): boolean => {
- return this.#get().isGatewayModeEnabled();
+ #shouldUseGatewayResume = (context: ConversationContext): boolean => {
+ const agentConfig = context.agentId
+ ? agentSelectors.getAgentConfigById(context.agentId)(getAgentStoreState())
+ : undefined;
+ return (
+ selectRuntimeType({
+ heterogeneousProvider: agentConfig?.agencyConfig?.heterogeneousProvider,
+ isGatewayMode: this.#get().isGatewayModeEnabled(),
+ }) === 'gateway'
+ );
};
/**
@@ -170,7 +182,7 @@ export class ConversationControlActionImpl {
_assistantGroupId: string,
context?: ConversationContext,
): Promise<void> => {
- const { internal_execAgentRuntime, startOperation, completeOperation } = this.#get();
+ const { executeClientAgent, startOperation, completeOperation } = this.#get();
// Build effective context from provided context or global state
const effectiveContext: ConversationContext = context ?? {
@@ -212,7 +224,7 @@ export class ConversationControlActionImpl {
// message, persists `intervention=approved`, dispatches the approved
// tool, and streams results back on the new op. No in-place resume of
// the paused op — simpler state + avoids stepIndex races.
- if (this.#shouldUseGatewayResume()) {
+ if (this.#shouldUseGatewayResume(effectiveContext)) {
const toolCallId = toolMessage.tool_call_id;
if (!toolCallId) {
console.warn(
@@ -277,7 +289,7 @@ export class ConversationControlActionImpl {
// 7. Execute agent runtime from tool message position
try {
- await internal_execAgentRuntime({
+ await executeClientAgent({
context: effectiveContext,
messages: currentMessages,
parentMessageId: toolMessageId, // Start from tool message
@@ -305,7 +317,7 @@ export class ConversationControlActionImpl {
context?: ConversationContext,
options?: { createUserMessage?: boolean; toolResultContent?: string },
): Promise<void> => {
- const { internal_execAgentRuntime, startOperation, completeOperation } = this.#get();
+ const { executeClientAgent, startOperation, completeOperation } = this.#get();
const effectiveContext: ConversationContext = context ?? {
agentId: this.#get().activeAgentId,
@@ -380,7 +392,7 @@ export class ConversationControlActionImpl {
};
try {
- await internal_execAgentRuntime({
+ await executeClientAgent({
context: effectiveContext,
messages: currentMessages,
parentMessageId: toolMessageId,
@@ -437,7 +449,7 @@ export class ConversationControlActionImpl {
});
try {
- await internal_execAgentRuntime({
+ await executeClientAgent({
context: effectiveContext,
messages: currentMessages,
parentMessageId: userMsg.id,
@@ -462,7 +474,7 @@ export class ConversationControlActionImpl {
reason?: string,
context?: ConversationContext,
): Promise<void> => {
- const { internal_execAgentRuntime, startOperation, completeOperation } = this.#get();
+ const { executeClientAgent, startOperation, completeOperation } = this.#get();
const effectiveContext: ConversationContext = context ?? {
agentId: this.#get().activeAgentId,
@@ -540,7 +552,7 @@ export class ConversationControlActionImpl {
});
try {
- await internal_execAgentRuntime({
+ await executeClientAgent({
context: effectiveContext,
messages: currentMessages,
parentMessageId: userMsg.id,
@@ -667,7 +679,7 @@ export class ConversationControlActionImpl {
// `rejected_continue` share the same code path (both surface the
// rejection to the LLM as user feedback), so a separate `rejected`
// decision adds complexity without behavioural difference.
- if (this.#shouldUseGatewayResume()) {
+ if (this.#shouldUseGatewayResume(effectiveContext)) {
const toolCallId = toolMessage.tool_call_id;
if (!toolCallId) {
console.warn(
@@ -706,7 +718,7 @@ export class ConversationControlActionImpl {
const toolMessage = dbMessageSelectors.getDbMessageById(messageId)(this.#get());
if (!toolMessage) return;
- const { internal_execAgentRuntime, startOperation, completeOperation } = this.#get();
+ const { executeClientAgent, startOperation, completeOperation } = this.#get();
// Build effective context from provided context or global state
const effectiveContext: ConversationContext = context ?? {
@@ -722,7 +734,7 @@ export class ConversationControlActionImpl {
// the LLM loop with the rejection content surfaced as user feedback.
// Skip the client-mode `rejectToolCalling` chain below — that would fire
// a duplicate halting `reject` before this continue signal.
- if (this.#shouldUseGatewayResume()) {
+ if (this.#shouldUseGatewayResume(effectiveContext)) {
const toolCallId = toolMessage.tool_call_id;
if (!toolCallId) {
console.warn(
@@ -823,7 +835,7 @@ export class ConversationControlActionImpl {
// Execute agent runtime from rejected tool message position to continue
try {
- await internal_execAgentRuntime({
+ await executeClientAgent({
context: effectiveContext,
messages: currentMessages,
parentMessageId: messageId,
diff --git a/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts b/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts
index e98d0dafe72..4a2b4966f6d 100644
--- a/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts
+++ b/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts
@@ -35,6 +35,7 @@ import { messageService } from '@/services/message';
import { getAgentStoreState, useAgentStore } from '@/store/agent';
import { agentByIdSelectors, agentSelectors } from '@/store/agent/selectors';
import { agentGroupByIdSelectors, getChatGroupStoreState } from '@/store/agentGroup';
+import { selectRuntimeType } from '@/store/chat/slices/aiChat/actions/agentDispatcher';
import { resolveHeteroResume } from '@/store/chat/slices/aiChat/actions/heteroResume';
import { type ChatStore } from '@/store/chat/store';
import {
@@ -191,7 +192,7 @@ export class ConversationLifecycleActionImpl {
onTopicCreated,
}: SendMessageWithContextParams): Promise<SendMessageResult | undefined> => {
let editorData = inputEditorData;
- const { internal_execAgentRuntime, mainInputEditor } = this.#get();
+ const { executeClientAgent, mainInputEditor } = this.#get();
const { agentId } = context;
const selectedSkills = parseSelectedSkillsFromEditorData(editorData);
const selectedTools = parseSelectedToolsFromEditorData(editorData);
@@ -218,6 +219,10 @@ export class ConversationLifecycleActionImpl {
const agentConfig = agentSelectors.getAgentConfigById(agentId)(getAgentStoreState());
const heterogeneousProvider = agentConfig?.agencyConfig?.heterogeneousProvider;
+ const runtimeType = selectRuntimeType({
+ heterogeneousProvider,
+ isGatewayMode: this.#get().isGatewayModeEnabled(),
+ });
// ── Command Bus: extract and process built-in commands from editorData ──
const commandOverrides: CommandSendOverrides = processCommands({
@@ -467,7 +472,7 @@ export class ConversationLifecycleActionImpl {
// ── External agent mode: delegate to heterogeneous agent CLI (desktop only) ──
// Per-agent heterogeneousProvider config takes priority over the global gateway mode.
- if (isDesktop && heterogeneousProvider) {
+ if (runtimeType === 'hetero' && heterogeneousProvider) {
// Resolve cwd up-front so the new topic is bound to a project at
// creation time. Otherwise the row stays NULL until the post-execution
// metadata write — which never lands on cancel/error and meanwhile
@@ -638,7 +643,7 @@ export class ConversationLifecycleActionImpl {
}
// ── Gateway mode: skip sendMessageInServer, let execAgentTask handle everything ──
- if (this.#get().isGatewayModeEnabled()) {
+ if (runtimeType === 'gateway') {
this.#get().completeOperation(operationId);
try {
@@ -997,7 +1002,7 @@ export class ConversationLifecycleActionImpl {
agentRuntimeInitialContext,
);
- await internal_execAgentRuntime({
+ await executeClientAgent({
context: execContext,
initialContext: mergedAgentRuntimeInitialContext,
messages: displayMessages,
@@ -1145,7 +1150,28 @@ export class ConversationLifecycleActionImpl {
]
: currentMessages;
- await this.#get().internal_execAgentRuntime({
+ // Sub-agent dispatch inherits the parent's runtime selection — a
+ // hetero/gateway parent must keep its sub-agents on the same path so
+ // events route through the same wire. See LOBE-8519.
+ const parentAgentConfig = context.agentId
+ ? agentSelectors.getAgentConfigById(context.agentId)(getAgentStoreState())
+ : undefined;
+ const runtimeType = selectRuntimeType({
+ heterogeneousProvider: parentAgentConfig?.agencyConfig?.heterogeneousProvider,
+ isGatewayMode: this.#get().isGatewayModeEnabled(),
+ });
+
+ // TODO(LOBE-8519 follow-up): only client sub-agent dispatch is
+ // implemented today. Gateway / hetero direct mentions fall through to
+ // client and will need their own runner once Step 2 lands.
+ if (runtimeType !== 'client') {
+ console.warn(
+ `[directMentionRoute] runtime=${runtimeType} not yet supported for sub-agent dispatch; ` +
+ 'falling through to client mode',
+ );
+ }
+
+ await this.#get().executeClientAgent({
context: { ...context, scope: 'sub_agent', subAgentId: targetAgentId },
inPortalThread,
messages: messagesWithInstruction,
@@ -1181,47 +1207,6 @@ export class ConversationLifecycleActionImpl {
}
}
- continueGenerationMessage = async (id: string, messageId: string): Promise<void> => {
- const message = dbMessageSelectors.getDbMessageById(id)(this.#get());
- if (!message) return;
-
- const { activeAgentId, activeTopicId, activeThreadId, activeGroupId } = this.#get();
-
- // Create base context for continue operation (using global state)
- const continueContext = {
- agentId: activeAgentId,
- topicId: activeTopicId,
- threadId: activeThreadId ?? undefined,
- groupId: activeGroupId,
- };
-
- // Create continue operation
- const { operationId } = this.#get().startOperation({
- type: 'continue',
- context: { ...continueContext, messageId },
- });
-
- try {
- const chats = displayMessageSelectors.mainAIChatsWithHistoryConfig(this.#get());
-
- await this.#get().internal_execAgentRuntime({
- context: continueContext,
- messages: chats,
- parentMessageId: id,
- parentMessageType: message.role as 'assistant' | 'tool' | 'user',
- parentOperationId: operationId,
- });
-
- this.#get().completeOperation(operationId);
- } catch (error) {
- this.#get().failOperation(operationId, {
- type: 'ContinueError',
- message: error instanceof Error ? error.message : String(error),
- });
- throw error;
- }
- };
-
/**
* Execute context compression for /compact command.
* Reuses the same service methods as the agent runtime's compress_context executor.
diff --git a/src/store/chat/slices/aiChat/actions/streamingExecutor.ts b/src/store/chat/slices/aiChat/actions/streamingExecutor.ts
index be8de4368d2..31982d412e5 100644
--- a/src/store/chat/slices/aiChat/actions/streamingExecutor.ts
+++ b/src/store/chat/slices/aiChat/actions/streamingExecutor.ts
@@ -411,13 +411,12 @@ export class StreamingExecutorActionImpl {
return { agentConfig: agentConfigWithTools, context, state, toolsEngine };
};
- internal_execAgentRuntime = async (params: {
+ executeClientAgent = async (params: {
context: ConversationContext;
disableTools?: boolean;
initialContext?: AgentRuntimeContext;
initialState?: AgentState;
inPortalThread?: boolean;
- inSearchWorkflow?: boolean;
messages: UIChatMessage[];
operationId?: string;
parentMessageId: string;
@@ -467,7 +466,7 @@ export class StreamingExecutorActionImpl {
}
log(
- '[internal_execAgentRuntime] start, operationId: %s, agentId: %s, subAgentId: %s, scope: %s, effectiveAgentId: %s, topicId: %s, messageKey: %s, parentMessageId: %s, parentMessageType: %s, messages count: %d, disableTools: %s',
+ '[executeClientAgent] start, operationId: %s, agentId: %s, subAgentId: %s, scope: %s, effectiveAgentId: %s, topicId: %s, messageKey: %s, parentMessageId: %s, parentMessageType: %s, messages count: %d, disableTools: %s',
operationId,
agentId,
subAgentId,
@@ -533,7 +532,7 @@ export class StreamingExecutorActionImpl {
// ===========================================
// Step 2: Create and Execute Agent Runtime
// ===========================================
- log('[internal_execAgentRuntime] Creating agent runtime with config', modelRuntimeConfig);
+ log('[executeClientAgent] Creating agent runtime with config', modelRuntimeConfig);
const agent = new GeneralChatAgent({
agentConfig: { maxSteps: 1000 },
@@ -569,10 +568,7 @@ export class StreamingExecutorActionImpl {
let state = initialAgentState;
let nextContext = initialAgentContext;
- log(
- '[internal_execAgentRuntime] Agent runtime loop start, initial phase: %s',
- nextContext.phase,
- );
+ log('[executeClientAgent] Agent runtime loop start, initial phase: %s', nextContext.phase);
// Compute contextKey for message queue (per-context, not per-operation)
const contextKey = messageKey;
@@ -583,7 +579,7 @@ export class StreamingExecutorActionImpl {
// Check if operation has been cancelled
const currentOperation = this.#get().operations[operationId];
if (currentOperation?.status === 'cancelled') {
- log('[internal_execAgentRuntime] Operation cancelled, marking state as interrupted');
+ log('[executeClientAgent] Operation cancelled, marking state as interrupted');
// Update state status to 'interrupted' so agent can handle abort
state = { ...state, status: 'interrupted' };
@@ -592,7 +588,7 @@ export class StreamingExecutorActionImpl {
const result = await runtime.step(state, nextContext);
state = result.newState;
- log('[internal_execAgentRuntime] Operation cancelled, stopping loop');
+ log('[executeClientAgent] Operation cancelled, stopping loop');
break;
}
@@ -626,7 +622,7 @@ export class StreamingExecutorActionImpl {
};
} catch (error) {
// Page agent runtime may not be available, ignore errors
- log('[internal_execAgentRuntime] Failed to get page XML for step: %o', error);
+ log('[executeClientAgent] Failed to get page XML for step: %o', error);
}
}
@@ -634,7 +630,7 @@ export class StreamingExecutorActionImpl {
nextContext = { ...nextContext, stepContext };
log(
- '[internal_execAgentRuntime][step-%d]: phase=%s, status=%s, state.messages=%d, dbMessagesMap[%s]=%d, stepContext=%O',
+ '[executeClientAgent][step-%d]: phase=%s, status=%s, state.messages=%d, dbMessagesMap[%s]=%d, stepContext=%O',
stepCount,
nextContext.phase,
state.status,
@@ -647,7 +643,7 @@ export class StreamingExecutorActionImpl {
const result = await runtime.step(state, nextContext);
log(
- '[internal_execAgentRuntime] Step %d completed, events: %d, newStatus=%s, newState.messages=%d',
+ '[executeClientAgent] Step %d completed, events: %d, newStatus=%s, newState.messages=%d',
stepCount,
result.events.length,
result.newState.status,
@@ -662,7 +658,7 @@ export class StreamingExecutorActionImpl {
['tasks_batch_result', 'tools_batch_result'].includes(result.nextContext?.phase)
) {
log(
- `[internal_execAgentRuntime] ${result.nextContext?.phase} completed, refreshing messages to sync state`,
+ `[executeClientAgent] ${result.nextContext?.phase} completed, refreshing messages to sync state`,
);
await this.#get().refreshMessages(context);
}
@@ -671,7 +667,7 @@ export class StreamingExecutorActionImpl {
for (const event of result.events) {
switch (event.type) {
case 'done': {
- log('[internal_execAgentRuntime] Received done event');
+ log('[executeClientAgent] Received done event');
break;
}
@@ -685,7 +681,7 @@ export class StreamingExecutorActionImpl {
}
case 'error': {
- log('[internal_execAgentRuntime] Received error event: %o', event.error);
+ log('[executeClientAgent] Received error event: %o', event.error);
// Find the assistant message to update error
const currentMessages = this.#get().messagesMap[messageKey] || [];
const assistantMessage = currentMessages.findLast((m) => m.role === 'assistant');
@@ -709,7 +705,7 @@ export class StreamingExecutorActionImpl {
const operationAfterStep = this.#get().operations[operationId];
if (operationAfterStep?.status === 'cancelled') {
log(
- '[internal_execAgentRuntime] Operation cancelled after step %d, marking state as interrupted',
+ '[executeClientAgent] Operation cancelled after step %d, marking state as interrupted',
stepCount,
);
@@ -723,13 +719,13 @@ export class StreamingExecutorActionImpl {
const abortResult = await runtime.step(state, contextForAbort);
state = abortResult.newState;
- log('[internal_execAgentRuntime] Operation cancelled, stopping loop');
+ log('[executeClientAgent] Operation cancelled, stopping loop');
break;
}
// If no nextContext, stop execution
if (!result.nextContext) {
- log('[internal_execAgentRuntime] No next context, stopping loop');
+ log('[executeClientAgent] No next context, stopping loop');
break;
}
@@ -739,7 +735,7 @@ export class StreamingExecutorActionImpl {
}
log(
- '[internal_execAgentRuntime] Agent runtime loop finished, final status: %s, total steps: %d',
+ '[executeClientAgent] Agent runtime loop finished, final status: %s, total steps: %d',
state.status,
stepCount,
);
@@ -751,7 +747,7 @@ export class StreamingExecutorActionImpl {
const afterCompletionCallbacks = operation?.metadata?.runtimeHooks?.afterCompletionCallbacks;
if (afterCompletionCallbacks && afterCompletionCallbacks.length > 0) {
log(
- '[internal_execAgentRuntime] Executing %d afterCompletion callbacks',
+ '[executeClientAgent] Executing %d afterCompletion callbacks',
afterCompletionCallbacks.length,
);
@@ -759,11 +755,11 @@ export class StreamingExecutorActionImpl {
try {
await callback();
} catch (error) {
- console.error('[internal_execAgentRuntime] afterCompletion callback error:', error);
+ console.error('[executeClientAgent] afterCompletion callback error:', error);
}
}
- log('[internal_execAgentRuntime] afterCompletion callbacks executed');
+ log('[executeClientAgent] afterCompletion callbacks executed');
}
// If completed successfully and queue has messages, drain and trigger new sendMessage.
@@ -773,7 +769,7 @@ export class StreamingExecutorActionImpl {
if (remainingQueued.length > 0) {
const merged = mergeQueuedMessages(remainingQueued);
log(
- '[internal_execAgentRuntime] %d queued messages after completion, triggering new sendMessage',
+ '[executeClientAgent] %d queued messages after completion, triggering new sendMessage',
remainingQueued.length,
);
@@ -808,10 +804,7 @@ export class StreamingExecutorActionImpl {
metadata: merged.metadata,
})
.catch((e: unknown) => {
- console.error(
- '[internal_execAgentRuntime] sendMessage for queued content failed:',
- e,
- );
+ console.error('[executeClientAgent] sendMessage for queued content failed:', e);
});
}, 100);
@@ -823,7 +816,7 @@ export class StreamingExecutorActionImpl {
switch (state.status) {
case 'done': {
this.#get().completeOperation(operationId);
- log('[internal_execAgentRuntime] Operation completed successfully');
+ log('[executeClientAgent] Operation completed successfully');
// Mark unread completion for background conversations
const completedOp = this.#get().operations[operationId];
@@ -837,19 +830,19 @@ export class StreamingExecutorActionImpl {
type: 'runtime_error',
message: 'Agent runtime execution failed',
});
- log('[internal_execAgentRuntime] Operation failed');
+ log('[executeClientAgent] Operation failed');
break;
}
case 'waiting_for_human': {
// When waiting for human intervention, complete the current operation
// A new operation will be created when user approves/rejects
this.#get().completeOperation(operationId);
- log('[internal_execAgentRuntime] Operation paused for human intervention');
+ log('[executeClientAgent] Operation paused for human intervention');
break;
}
}
- log('[internal_execAgentRuntime] completed');
+ log('[executeClientAgent] completed');
void emitClientAgentSignalSourceEvent({
payload: {
agentId,
diff --git a/src/store/chat/slices/builtinTool/actions/__tests__/search.test.ts b/src/store/chat/slices/builtinTool/actions/__tests__/search.test.ts
index 370bcd14e63..baebedd5610 100644
--- a/src/store/chat/slices/builtinTool/actions/__tests__/search.test.ts
+++ b/src/store/chat/slices/builtinTool/actions/__tests__/search.test.ts
@@ -1,7 +1,6 @@
import { WebBrowsingApiName, WebBrowsingManifest } from '@lobechat/builtin-tool-web-browsing';
import { type SearchQuery, type UIChatMessage } from '@lobechat/types';
import { act, renderHook } from '@testing-library/react';
-import { type Mock } from 'vitest';
import { beforeEach, describe, expect, it, vi } from 'vitest';
// Import after mocks
@@ -33,13 +32,7 @@ describe('search actions', () => {
activeAgentId: 'session-id',
activeTopicId: 'topic-id',
messageOperationMap: {},
- optimisticUpdateMessageContent: vi.fn(),
- optimisticUpdateMessagePluginError: vi.fn(),
optimisticUpdatePluginArguments: vi.fn(),
- optimisticUpdatePluginState: vi.fn(),
- optimisticCreateMessage: vi.fn(),
- optimisticAddToolToAssistantMessage: vi.fn(),
- openToolUI: vi.fn(),
invokeBuiltinTool: vi.fn(),
});
@@ -172,78 +165,6 @@ describe('search actions', () => {
});
});
- describe('saveSearchResult', () => {
- it('should save search result as tool message', async () => {
- const messageId = 'test-message-id';
- const parentId = 'parent-message-id';
- const mockMessage: Partial<UIChatMessage> = {
- id: messageId,
- parentId,
- sessionId: undefined,
- topicId: undefined,
- content: 'test content',
- plugin: {
- identifier: 'search',
- arguments: '{}',
- apiName: 'search',
- type: 'default',
- },
- pluginState: {},
- role: 'assistant',
- createdAt: Date.now(),
- updatedAt: Date.now(),
- };
-
- vi.spyOn(dbMessageSelectors, 'getDbMessageById').mockImplementation(
- () => () => mockMessage as UIChatMessage,
- );
-
- const { result } = renderHook(() => useChatStore());
- const { saveSearchResult } = result.current;
-
- await act(async () => {
- await saveSearchResult(messageId);
- });
-
- // Note: context is undefined when no operationId is set in messageOperationMap
- expect(result.current.optimisticCreateMessage).toHaveBeenCalledWith(
- expect.objectContaining({
- content: 'test content',
- parentId,
- plugin: mockMessage.plugin,
- pluginState: mockMessage.pluginState,
- role: 'tool',
- agentId: 'session-id',
- topicId: 'topic-id',
- }),
- undefined,
- );
-
- expect(result.current.optimisticAddToolToAssistantMessage).toHaveBeenCalledWith(
- parentId,
- expect.objectContaining({
- identifier: 'search',
- type: 'default',
- }),
- undefined,
- );
- });
-
- it('should not save if message not found', async () => {
- vi.spyOn(dbMessageSelectors, 'getDbMessageById').mockImplementation(() => () => undefined);
-
- const { result } = renderHook(() => useChatStore());
- const { saveSearchResult } = result.current;
-
- await act(async () => {
- await saveSearchResult('non-existent-id');
- });
-
- expect(result.current.optimisticCreateMessage).not.toHaveBeenCalled();
- expect(result.current.optimisticAddToolToAssistantMessage).not.toHaveBeenCalled();
- });
- });
-
describe('togglePageContent', () => {
it('should set activePageContentUrl', () => {
const { result } = renderHook(() => useChatStore());
@@ -256,68 +177,4 @@ describe('search actions', () => {
expect(useChatStore.getState().activePageContentUrl).toBe(url);
});
});
-
- describe('saveSearchResult with context', () => {
- it('should pass context to optimistic methods when operationId exists', async () => {
- const messageId = 'test-message-id';
- const parentId = 'parent-message-id';
- const contextTopicId = 'context-topic-id';
- const operationId = 'op_test';
-
- const mockMessage: Partial<UIChatMessage> = {
- id: messageId,
- parentId,
- sessionId: 'context-session-id',
- topicId: contextTopicId,
- content: 'test content',
- plugin: {
- identifier: 'search',
- arguments: '{}',
- apiName: 'search',
- type: 'default',
- },
- pluginState: {},
- role: 'tool',
- createdAt: Date.now(),
- updatedAt: Date.now(),
- };
-
- vi.spyOn(dbMessageSelectors, 'getDbMessageById').mockImplementation(
- () => () => mockMessage as UIChatMessage,
- );
-
- (useChatStore.getState().optimisticCreateMessage as Mock).mockResolvedValue({
- id: 'new-message-id',
- });
-
- // Set up messageOperationMap so saveSearchResult can get operationId
- useChatStore.setState({
- messageOperationMap: {
- [messageId]: operationId,
- },
- });
-
- const { result } = renderHook(() => useChatStore());
-
- await act(async () => {
- await result.current.saveSearchResult(messageId);
- });
-
- expect(result.current.optimisticAddToolToAssistantMessage).toHaveBeenCalledWith(
- parentId,
- expect.objectContaining({
- identifier: 'search',
- type: 'default',
- }),
- { operationId },
- );
- expect(result.current.optimisticCreateMessage).toHaveBeenCalledWith(
- expect.objectContaining({
- agentId: 'session-id',
- topicId: contextTopicId,
- }),
- { operationId },
- );
- });
- });
});
diff --git a/src/store/chat/slices/builtinTool/actions/search.ts b/src/store/chat/slices/builtinTool/actions/search.ts
index de3d61c9978..74b9d956079 100644
--- a/src/store/chat/slices/builtinTool/actions/search.ts
+++ b/src/store/chat/slices/builtinTool/actions/search.ts
@@ -1,6 +1,5 @@
import { WebBrowsingApiName, WebBrowsingManifest } from '@lobechat/builtin-tool-web-browsing';
-import { type ChatToolPayload, type CreateMessageParams, type SearchQuery } from '@lobechat/types';
-import { nanoid } from '@lobechat/utils';
+import { type ChatToolPayload, type SearchQuery } from '@lobechat/types';
import { dbMessageSelectors } from '@/store/chat/selectors';
import { type ChatStore } from '@/store/chat/store';
@@ -20,57 +19,6 @@ export class SearchActionImpl {
this.#get = get;
}
- saveSearchResult = async (id: string): Promise<void> => {
- const message = dbMessageSelectors.getDbMessageById(id)(this.#get());
- if (!message || !message.plugin) return;
-
- const { optimisticAddToolToAssistantMessage, optimisticCreateMessage, openToolUI } =
- this.#get();
-
- // Get operationId from messageOperationMap
- const operationId = this.#get().messageOperationMap[id];
- const context = operationId ? { operationId } : undefined;
-
- // 1. Create a new tool call message
- const newToolCallId = `tool_call_${nanoid()}`;
-
- const toolMessage: CreateMessageParams = {
- agentId: message.agentId ?? this.#get().activeAgentId,
- content: message.content,
- id: undefined,
- parentId: message.parentId,
- plugin: message.plugin,
- pluginState: message.pluginState,
- role: 'tool',
- tool_call_id: newToolCallId,
- topicId: message.topicId !== undefined ? message.topicId : this.#get().activeTopicId,
- };
-
- const addToolItem = async () => {
- if (!message.parentId || !message.plugin) return;
-
- await optimisticAddToolToAssistantMessage(
- message.parentId,
- {
- id: newToolCallId,
- ...message.plugin,
- },
- context,
- );
- };
-
- const [result] = await Promise.all([
- // 1. Add tool message
- optimisticCreateMessage(toolMessage, context),
- // 2. Insert this tool call message into the AI message's tools array
- addToolItem(),
- ]);
- if (!result) return;
-
- // Activate the newly created tool message
- openToolUI(result.id, message.plugin.identifier);
- };
-
togglePageContent = (url: string): void => {
this.#set({ activePageContentUrl: url });
};
diff --git a/src/store/chat/slices/plugin/action.test.ts b/src/store/chat/slices/plugin/action.test.ts
index d22e3a2fdc3..cc296654797 100644
--- a/src/store/chat/slices/plugin/action.test.ts
+++ b/src/store/chat/slices/plugin/action.test.ts
@@ -2,12 +2,10 @@ import { PLUGIN_SCHEMA_API_MD5_PREFIX, PLUGIN_SCHEMA_SEPARATOR } from '@lobechat
import { ToolNameResolver } from '@lobechat/context-engine';
import { type ChatToolPayload, type MessageToolCall, type UIChatMessage } from '@lobechat/types';
import { act, renderHook } from '@testing-library/react';
-import i18n from 'i18next';
import { type Mock } from 'vitest';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { messageService } from '@/services/message';
-import { chatSelectors } from '@/store/chat/selectors';
import { useChatStore } from '@/store/chat/store';
import { messageMapKey } from '@/store/chat/utils/messageMapKey';
import { useToolStore } from '@/store/tool';
@@ -31,161 +29,6 @@ afterEach(() => {
});
describe('ChatPluginAction', () => {
- describe('summaryPluginContent', () => {
- it('should summarize plugin content', async () => {
- const messageId = 'message-id';
- const toolMessage = {
- id: messageId,
- role: 'tool',
- content: 'Tool content to summarize',
- } as UIChatMessage;
-
- const internal_execAgentRuntimeMock = vi.fn();
-
- act(() => {
- useChatStore.setState({
- activeAgentId: 'session-id',
- messagesMap: { [messageMapKey({ agentId: 'session-id' })]: [toolMessage] },
- internal_execAgentRuntime: internal_execAgentRuntimeMock,
- });
- });
-
- const { result } = renderHook(() => useChatStore());
-
- await act(async () => {
- await result.current.summaryPluginContent(messageId);
- });
-
- expect(internal_execAgentRuntimeMock).toHaveBeenCalledWith(
- expect.objectContaining({
- context: expect.objectContaining({
- agentId: 'session-id',
- }),
- messages: [
- {
- role: 'assistant',
- content: i18n.t('prompts.summaryExpert', { ns: 'chat' }),
- },
- expect.objectContaining({
- id: toolMessage.id,
- content: toolMessage.content,
- role: 'assistant',
- }),
- ],
- parentMessageId: messageId,
- parentMessageType: 'assistant',
- }),
- );
- });
-
- it('should not summarize non-tool messages', async () => {
- const messageId = 'message-id';
- const nonToolMessage = {
- id: messageId,
- role: 'user',
- content: 'User message',
- } as UIChatMessage;
-
- const internal_execAgentRuntimeMock = vi.fn();
-
- act(() => {
- useChatStore.setState({
- activeAgentId: 'session-id',
- messagesMap: { [messageMapKey({ agentId: 'session-id' })]: [nonToolMessage] },
- internal_execAgentRuntime: internal_execAgentRuntimeMock,
- });
- });
-
- const { result } = renderHook(() => useChatStore());
-
- await act(async () => {
- await result.current.summaryPluginContent(messageId);
- });
-
- expect(internal_execAgentRuntimeMock).not.toHaveBeenCalled();
- });
- });
-
- describe('fillPluginMessageContent', () => {
- it('should update message content and trigger the ai message', async () => {
- // 设置模拟函数的返回值
- const mockCurrentChats: any[] = [];
- vi.spyOn(chatSelectors, 'activeBaseChats').mockReturnValue(mockCurrentChats);
-
- // 设置初始状态
- const initialState = {
- messages: [],
- internal_execAgentRuntime: vi.fn(),
- refreshMessages: vi.fn(),
- optimisticUpdateMessageContent: vi.fn(),
- };
- useChatStore.setState(initialState);
-
- const { result } = renderHook(() => useChatStore());
-
- const messageId = 'message-id';
- const newContent = 'Updated content';
-
- await act(async () => {
- await result.current.fillPluginMessageContent(messageId, newContent, true);
- });
-
- // 验证 optimisticUpdateMessageContent 是否被正确调用
- // The function now takes 4 args: (id, content, extra?, context?)
- expect(result.current.optimisticUpdateMessageContent).toHaveBeenCalledWith(
- messageId,
- newContent,
- undefined,
- undefined,
- );
-
- // 验证 coreProcessMessage 是否被正确调用
- expect(result.current.internal_execAgentRuntime).toHaveBeenCalledWith(
- expect.objectContaining({
- messages: mockCurrentChats,
- parentMessageId: messageId,
- parentMessageType: 'user',
- }),
- );
- });
- it('should update message content and not trigger ai message', async () => {
- // 设置模拟函数的返回值
- const mockCurrentChats: any[] = [];
- vi.spyOn(chatSelectors, 'activeBaseChats').mockReturnValue(mockCurrentChats);
-
- // 设置初始状态
- const initialState = {
- messages: [],
- coreProcessMessage: vi.fn(),
- internal_execAgentRuntime: vi.fn(),
- refreshMessages: vi.fn(),
- optimisticUpdateMessageContent: vi.fn(),
- };
- useChatStore.setState(initialState);
-
- const { result } = renderHook(() => useChatStore());
-
- const messageId = 'message-id';
- const newContent = 'Updated content';
-
- await act(async () => {
- await result.current.fillPluginMessageContent(messageId, newContent);
- });
-
- // 验证 optimisticUpdateMessageContent 是否被正确调用
- // The function now takes 4 args: (id, content, extra?, context?)
- expect(result.current.optimisticUpdateMessageContent).toHaveBeenCalledWith(
- messageId,
- newContent,
- undefined,
- undefined,
- );
-
- // 验证 coreProcessMessage 没有被正确调用
- expect(result.current.internal_execAgentRuntime).not.toHaveBeenCalled();
- });
- });
-
describe('updatePluginState', () => {
it('should update the plugin state for a message', async () => {
const messageId = 'message-id';
diff --git a/src/store/chat/slices/plugin/actions/publicApi.ts b/src/store/chat/slices/plugin/actions/publicApi.ts
index b055df7dbf5..e0b7f706c57 100644
--- a/src/store/chat/slices/plugin/actions/publicApi.ts
+++ b/src/store/chat/slices/plugin/actions/publicApi.ts
@@ -1,10 +1,8 @@
-import { type ChatToolPayload, type RuntimeStepContext, type UIChatMessage } from '@lobechat/types';
-import i18n from 'i18next';
+import { type ChatToolPayload, type RuntimeStepContext } from '@lobechat/types';
import { type ChatStore } from '@/store/chat/store';
import { type StoreSetter } from '@/store/types';
-import { type OptimisticUpdateContext } from '../../message/actions/optimisticUpdate';
import { displayMessageSelectors } from '../../message/selectors';
/**
@@ -25,19 +23,6 @@ export class PluginPublicApiActionImpl {
this.#get = get;
}
- fillPluginMessageContent = async (
- id: string,
- content: string,
- triggerAiMessage?: boolean,
- context?: OptimisticUpdateContext,
- ): Promise<void> => {
- const { triggerAIMessage, optimisticUpdateMessageContent } = this.#get();
-
- await optimisticUpdateMessageContent(id, content, undefined, context);
-
- if (triggerAiMessage) await triggerAIMessage({ parentId: id });
- };
-
reInvokeToolMessage = async (id: string): Promise<void> => {
const message = displayMessageSelectors.getDisplayMessageById(id)(this.#get());
if (!message || message.role !== 'tool' || !message.plugin) return;
@@ -56,36 +41,6 @@ export class PluginPublicApiActionImpl {
await this.#get().internal_invokeDifferentTypePlugin(id, payload);
};
- summaryPluginContent = async (id: string): Promise<void> => {
- const message = displayMessageSelectors.getDisplayMessageById(id)(this.#get());
- if (!message || message.role !== 'tool') return;
-
- const { activeAgentId, activeTopicId, activeThreadId } = this.#get();
-
- await this.#get().internal_execAgentRuntime({
- context: {
- agentId: activeAgentId,
- topicId: activeTopicId,
- threadId: activeThreadId ?? undefined,
- },
- messages: [
- {
- role: 'assistant',
- content: i18n.t('prompts.summaryExpert', { ns: 'chat' }),
- },
- {
- ...message,
- content: message.content,
- role: 'assistant',
- name: undefined,
- tool_call_id: undefined,
- },
- ] as UIChatMessage[],
- parentMessageId: message.id,
- parentMessageType: 'assistant',
- });
- };
-
internal_invokeDifferentTypePlugin = async (
id: string,
payload: ChatToolPayload,
diff --git a/src/store/chat/slices/plugin/actions/workflow.ts b/src/store/chat/slices/plugin/actions/workflow.ts
index f70ea93bde2..62cd6d8464b 100644
--- a/src/store/chat/slices/plugin/actions/workflow.ts
+++ b/src/store/chat/slices/plugin/actions/workflow.ts
@@ -4,8 +4,7 @@ import { messageService } from '@/services/message';
import { type ChatStore } from '@/store/chat/store';
import { type StoreSetter } from '@/store/types';
-import { dbMessageSelectors, displayMessageSelectors } from '../../message/selectors';
-import { threadSelectors } from '../../thread/selectors';
+import { dbMessageSelectors } from '../../message/selectors';
/**
* Workflow orchestration actions
@@ -43,37 +42,6 @@ export class PluginWorkflowActionImpl {
context: { agentId: newMessage.agentId, topicId: newMessage.topicId },
});
};
-
- triggerAIMessage = async ({
- parentId,
- threadId,
- inPortalThread,
- inSearchWorkflow,
- }: {
- parentId?: string;
- threadId?: string;
- inPortalThread?: boolean;
- inSearchWorkflow?: boolean;
- } = {}): Promise<void> => {
- const { internal_execAgentRuntime, activeAgentId, activeTopicId } = this.#get();
-
- const chats = inPortalThread
- ? threadSelectors.portalAIChatsWithHistoryConfig(this.#get())
- : displayMessageSelectors.mainAIChatsWithHistoryConfig(this.#get());
-
- await internal_execAgentRuntime({
- context: {
- agentId: activeAgentId,
- topicId: activeTopicId,
- threadId,
- },
- messages: chats,
- parentMessageId: parentId ?? chats.at(-1)!.id,
- parentMessageType: 'user',
- inPortalThread,
- inSearchWorkflow,
- });
- };
}
export type PluginWorkflowAction = Pick<PluginWorkflowActionImpl, keyof PluginWorkflowActionImpl>;