Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat: support client tasks mode (#11666)

Arvin Xu98cf57bc2c98
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index fd60b6a517f..b0a1ce6dfeb 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -204,6 +204,7 @@
"noSelectedAgents": "No members selected yet",
"openInNewWindow": "Open in New Window",
"operation.execAgentRuntime": "Preparing response",
+ "operation.execClientTask": "Executing task",
"operation.sendMessage": "Sending message",
"owner": "Group owner",
"pageCopilot.title": "Page Agent",
@@ -322,13 +323,17 @@
"tab.profile": "Agent Profile",
"tab.search": "Search",
"task.activity.calling": "Calling Skill...",
+ "task.activity.clientExecuting": "Executing locally...",
"task.activity.generating": "Generating response...",
"task.activity.gotResult": "Tool result received",
"task.activity.toolCalling": "Calling {{toolName}}...",
"task.activity.toolResult": "{{toolName}} result received",
"task.batchTasks": "{{count}} Batch Subtasks",
+ "task.instruction": "Task Instruction",
+ "task.intermediateSteps": "{{count}} intermediate steps",
+ "task.metrics.duration": "(took {{duration}})",
"task.metrics.stepsShort": "steps",
- "task.metrics.toolCallsShort": "tool uses",
+ "task.metrics.toolCallsShort": "skill uses",
"task.status.cancelled": "Task Cancelled",
"task.status.failed": "Task Failed",
"task.status.initializing": "Initializing task...",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 28284965545..e3798efdacc 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -204,6 +204,7 @@
"noSelectedAgents": "还未选择成员",
"openInNewWindow": "在新窗口打开",
"operation.execAgentRuntime": "准备响应中",
+ "operation.execClientTask": "执行任务中",
"operation.sendMessage": "消息发送中",
"owner": "群主",
"pageCopilot.title": "文稿助理",
@@ -322,11 +323,15 @@
"tab.profile": "助理档案",
"tab.search": "搜索",
"task.activity.calling": "正在调用技能…",
+ "task.activity.clientExecuting": "本地执行中…",
"task.activity.generating": "正在生成回复…",
"task.activity.gotResult": "已获取技能结果",
"task.activity.toolCalling": "正在调用 {{toolName}}…",
"task.activity.toolResult": "已获取 {{toolName}} 结果",
"task.batchTasks": "{{count}} 个批量子任务",
+ "task.instruction": "任务说明",
+ "task.intermediateSteps": "{{count}} 个中间步骤",
+ "task.metrics.duration": "(用时 {{duration}})",
"task.metrics.stepsShort": "步",
"task.metrics.toolCallsShort": "次技能调用",
"task.status.cancelled": "任务已取消",
diff --git a/packages/agent-runtime/src/agents/GeneralChatAgent.ts b/packages/agent-runtime/src/agents/GeneralChatAgent.ts
index 9b121830407..e559be3c26f 100644
--- a/packages/agent-runtime/src/agents/GeneralChatAgent.ts
+++ b/packages/agent-runtime/src/agents/GeneralChatAgent.ts
@@ -359,6 +359,30 @@ export class GeneralChatAgent implements Agent {
type: 'exec_tasks',
};
}
+
+ // GTD client-side async task (single, desktop only)
+ if (stateType === 'execClientTask') {
+ const { parentMessageId: execParentId, task } = data.state as {
+ parentMessageId: string;
+ task: any;
+ };
+ return {
+ payload: { parentMessageId: execParentId, task },
+ type: 'exec_client_task',
+ };
+ }
+
+ // GTD client-side async tasks (multiple, desktop only)
+ if (stateType === 'execClientTasks') {
+ const { parentMessageId: execParentId, tasks } = data.state as {
+ parentMessageId: string;
+ tasks: any[];
+ };
+ return {
+ payload: { parentMessageId: execParentId, tasks },
+ type: 'exec_client_tasks',
+ };
+ }
}
// Check if there are still pending tool messages waiting for approval
diff --git a/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts b/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts
index 8712979e3ae..e2f1b37ebcf 100644
--- a/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts
+++ b/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts
@@ -368,6 +368,216 @@ describe('GeneralChatAgent', () => {
});
describe('tool_result phase', () => {
+ describe('GTD async tasks', () => {
+ it('should return exec_task for single async task (execTask)', async () => {
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ operationId: 'test-session',
+ modelRuntimeConfig: mockModelRuntimeConfig,
+ });
+
+ const state = createMockState();
+ const context = createMockContext('tool_result', {
+ parentMessageId: 'tool-msg-1',
+ stop: true,
+ data: {
+ state: {
+ type: 'execTask',
+ parentMessageId: 'exec-parent-msg',
+ task: { instruction: 'Do something async', timeout: 30000 },
+ },
+ },
+ });
+
+ const result = await agent.runner(context, state);
+
+ expect(result).toEqual({
+ type: 'exec_task',
+ payload: {
+ parentMessageId: 'exec-parent-msg',
+ task: { instruction: 'Do something async', timeout: 30000 },
+ },
+ });
+ });
+
+ it('should return exec_tasks for multiple async tasks (execTasks)', async () => {
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ operationId: 'test-session',
+ modelRuntimeConfig: mockModelRuntimeConfig,
+ });
+
+ const state = createMockState();
+ const tasks = [
+ { instruction: 'Task 1', timeout: 30000 },
+ { instruction: 'Task 2', timeout: 30000 },
+ ];
+ const context = createMockContext('tool_result', {
+ parentMessageId: 'tool-msg-1',
+ stop: true,
+ data: {
+ state: {
+ type: 'execTasks',
+ parentMessageId: 'exec-parent-msg',
+ tasks,
+ },
+ },
+ });
+
+ const result = await agent.runner(context, state);
+
+ expect(result).toEqual({
+ type: 'exec_tasks',
+ payload: {
+ parentMessageId: 'exec-parent-msg',
+ tasks,
+ },
+ });
+ });
+
+ it('should return exec_client_task for single client-side async task (execClientTask)', async () => {
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ operationId: 'test-session',
+ modelRuntimeConfig: mockModelRuntimeConfig,
+ });
+
+ const state = createMockState();
+ const context = createMockContext('tool_result', {
+ parentMessageId: 'tool-msg-1',
+ stop: true,
+ data: {
+ state: {
+ type: 'execClientTask',
+ parentMessageId: 'exec-parent-msg',
+ task: { type: 'localFile', path: '/path/to/file' },
+ },
+ },
+ });
+
+ const result = await agent.runner(context, state);
+
+ expect(result).toEqual({
+ type: 'exec_client_task',
+ payload: {
+ parentMessageId: 'exec-parent-msg',
+ task: { type: 'localFile', path: '/path/to/file' },
+ },
+ });
+ });
+
+ it('should return exec_client_tasks for multiple client-side async tasks (execClientTasks)', async () => {
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ operationId: 'test-session',
+ modelRuntimeConfig: mockModelRuntimeConfig,
+ });
+
+ const state = createMockState();
+ const tasks = [
+ { type: 'localFile', path: '/path/to/file1' },
+ { type: 'localFile', path: '/path/to/file2' },
+ ];
+ const context = createMockContext('tool_result', {
+ parentMessageId: 'tool-msg-1',
+ stop: true,
+ data: {
+ state: {
+ type: 'execClientTasks',
+ parentMessageId: 'exec-parent-msg',
+ tasks,
+ },
+ },
+ });
+
+ const result = await agent.runner(context, state);
+
+ expect(result).toEqual({
+ type: 'exec_client_tasks',
+ payload: {
+ parentMessageId: 'exec-parent-msg',
+ tasks,
+ },
+ });
+ });
+
+ it('should not trigger exec_task when stop is false', async () => {
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ operationId: 'test-session',
+ modelRuntimeConfig: mockModelRuntimeConfig,
+ });
+
+ const state = createMockState({
+ messages: [
+ { role: 'user', content: 'Hello' },
+ { role: 'assistant', content: '' },
+ { role: 'tool', content: 'Result', tool_call_id: 'call-1' },
+ ] as any,
+ });
+ const context = createMockContext('tool_result', {
+ parentMessageId: 'tool-msg-1',
+ stop: false, // stop is false, should not trigger exec_task
+ data: {
+ state: {
+ type: 'execTask',
+ parentMessageId: 'exec-parent-msg',
+ task: { instruction: 'Do something async' },
+ },
+ },
+ });
+
+ const result = await agent.runner(context, state);
+
+ // Should return call_llm instead of exec_task
+ expect(result).toEqual({
+ type: 'call_llm',
+ payload: {
+ messages: state.messages,
+ model: 'gpt-4o-mini',
+ parentMessageId: 'tool-msg-1',
+ provider: 'openai',
+ tools: undefined,
+ },
+ });
+ });
+
+ it('should not trigger exec_task when data.state is undefined', async () => {
+ const agent = new GeneralChatAgent({
+ agentConfig: { maxSteps: 100 },
+ operationId: 'test-session',
+ modelRuntimeConfig: mockModelRuntimeConfig,
+ });
+
+ const state = createMockState({
+ messages: [
+ { role: 'user', content: 'Hello' },
+ { role: 'assistant', content: '' },
+ { role: 'tool', content: 'Result', tool_call_id: 'call-1' },
+ ] as any,
+ });
+ const context = createMockContext('tool_result', {
+ parentMessageId: 'tool-msg-1',
+ stop: true,
+ data: {}, // No state property
+ });
+
+ const result = await agent.runner(context, state);
+
+ // Should return call_llm instead of exec_task
+ expect(result).toEqual({
+ type: 'call_llm',
+ payload: {
+ messages: state.messages,
+ model: 'gpt-4o-mini',
+ parentMessageId: 'tool-msg-1',
+ provider: 'openai',
+ tools: undefined,
+ },
+ });
+ });
+ });
+
it('should return call_llm when no pending tools', async () => {
const agent = new GeneralChatAgent({
agentConfig: { maxSteps: 100 },
diff --git a/packages/agent-runtime/src/types/instruction.ts b/packages/agent-runtime/src/types/instruction.ts
index 34238bb17ad..f3d72e17481 100644
--- a/packages/agent-runtime/src/types/instruction.ts
+++ b/packages/agent-runtime/src/types/instruction.ts
@@ -236,12 +236,26 @@ export interface ExecTaskItem {
inheritMessages?: boolean;
/** Detailed instruction/prompt for the task execution */
instruction: string;
+ /**
+ * Whether to execute the task on the client side (desktop only).
+ * When true and running on desktop, the task will be executed locally
+ * with access to local tools (file system, shell commands, etc.).
+ *
+ * IMPORTANT: This MUST be set to true when the task requires:
+ * - Reading/writing local files via `local-system` tool
+ * - Executing shell commands
+ * - Any other desktop-only local tool operations
+ *
+ * If not specified or false, the task runs on the server (default behavior).
+ * On non-desktop platforms (web), this flag is ignored and tasks always run on server.
+ */
+ runInClient?: boolean;
/** Timeout in milliseconds (optional, default 30 minutes) */
timeout?: number;
}
/**
- * Instruction to execute a single async task
+ * Instruction to execute a single async task (server-side)
*/
export interface AgentInstructionExecTask {
payload: {
@@ -254,7 +268,7 @@ export interface AgentInstructionExecTask {
}
/**
- * Instruction to execute multiple async tasks in parallel
+ * Instruction to execute multiple async tasks in parallel (server-side)
*/
export interface AgentInstructionExecTasks {
payload: {
@@ -266,6 +280,34 @@ export interface AgentInstructionExecTasks {
type: 'exec_tasks';
}
+/**
+ * Instruction to execute a single async task on the client (desktop only)
+ * Used when task requires local tools like file system or shell commands
+ */
+export interface AgentInstructionExecClientTask {
+ payload: {
+ /** Parent message ID (tool message that triggered the task) */
+ parentMessageId: string;
+ /** Task to execute */
+ task: ExecTaskItem;
+ };
+ type: 'exec_client_task';
+}
+
+/**
+ * Instruction to execute multiple async tasks on the client in parallel (desktop only)
+ * Used when tasks require local tools like file system or shell commands
+ */
+export interface AgentInstructionExecClientTasks {
+ payload: {
+ /** Parent message ID (tool message that triggered the tasks) */
+ parentMessageId: string;
+ /** Array of tasks to execute */
+ tasks: ExecTaskItem[];
+ };
+ type: 'exec_client_tasks';
+}
+
/**
* Payload for task_result phase (single task)
*/
@@ -318,6 +360,8 @@ export type AgentInstruction =
| AgentInstructionCallToolsBatch
| AgentInstructionExecTask
| AgentInstructionExecTasks
+ | AgentInstructionExecClientTask
+ | AgentInstructionExecClientTasks
| AgentInstructionRequestHumanPrompt
| AgentInstructionRequestHumanSelect
| AgentInstructionRequestHumanApprove
diff --git a/packages/builtin-tool-gtd/src/const.ts b/packages/builtin-tool-gtd/src/const.ts
new file mode 100644
index 00000000000..7531177a7e9
--- /dev/null
+++ b/packages/builtin-tool-gtd/src/const.ts
@@ -0,0 +1 @@
+export const isDesktop = process.env.NEXT_PUBLIC_IS_DESKTOP_APP === '1';
diff --git a/packages/builtin-tool-gtd/src/executor/index.ts b/packages/builtin-tool-gtd/src/executor/index.ts
index a6198ae3fd9..916ea2862fd 100644
--- a/packages/builtin-tool-gtd/src/executor/index.ts
+++ b/packages/builtin-tool-gtd/src/executor/index.ts
@@ -407,18 +407,20 @@ class GTDExecutor extends BaseExecutor<typeof GTDApiNameEnum> {
* Execute a single async task
*
* This method triggers async task execution by returning a special state.
- * The AgentRuntime's executor will recognize this state and trigger the exec_task instruction.
+ * The AgentRuntime's executor will recognize this state and trigger the appropriate instruction.
*
* Flow:
- * 1. GTD tool returns stop: true with state.type = 'execTask'
- * 2. AgentRuntime executor recognizes the state and triggers exec_task instruction
- * 3. exec_task executor creates task message and polls for completion
+ * 1. GTD tool returns stop: true with state.type = 'execTask' or 'execClientTask'
+ * 2. AgentRuntime executor recognizes the state and triggers exec_task or exec_client_task instruction
+ * 3. The executor creates task message and handles execution
+ *
+ * @param params.runInClient - If true, returns 'execClientTask' state for client-side execution
*/
execTask = async (
params: ExecTaskParams,
ctx: BuiltinToolContext,
): Promise<BuiltinToolResult> => {
- const { description, instruction, inheritMessages, timeout } = params;
+ const { description, instruction, inheritMessages, timeout, runInClient } = params;
if (!description || !instruction) {
return {
@@ -427,19 +429,25 @@ class GTDExecutor extends BaseExecutor<typeof GTDApiNameEnum> {
};
}
+ const task = {
+ description,
+ inheritMessages,
+ instruction,
+ runInClient,
+ timeout,
+ };
+
+ // Determine state type based on runInClient
+ // If runInClient is true, return 'execClientTask' to trigger client-side executor
+ const stateType = runInClient ? 'execClientTask' : 'execTask';
+
// Return stop: true with special state that AgentRuntime will recognize
- // The exec_task executor will be triggered by the runtime when it sees this state
return {
- content: `🚀 Triggered async task for execution:\n- ${description}`,
+ content: `🚀 Triggered async task for ${runInClient ? 'client-side' : ''} execution:\n- ${description}`,
state: {
parentMessageId: ctx.messageId,
- task: {
- description,
- inheritMessages,
- instruction,
- timeout,
- },
- type: 'execTask',
+ task,
+ type: stateType,
},
stop: true,
success: true,
@@ -450,12 +458,15 @@ class GTDExecutor extends BaseExecutor<typeof GTDApiNameEnum> {
* Execute one or more async tasks
*
* This method triggers async task execution by returning a special state.
- * The AgentRuntime's executor will recognize this state and trigger the exec_tasks instruction.
+ * The AgentRuntime's executor will recognize this state and trigger the appropriate instruction.
*
* Flow:
- * 1. GTD tool returns stop: true with state.type = 'execTasks'
- * 2. AgentRuntime executor recognizes the state and triggers exec_tasks instruction
- * 3. exec_tasks executor creates task messages and polls for completion
+ * 1. GTD tool returns stop: true with state.type = 'execTasks' or 'execClientTasks'
+ * 2. AgentRuntime executor recognizes the state and triggers exec_tasks or exec_client_tasks instruction
+ * 3. The executor creates task messages and handles execution
+ *
+ * Note: If any task has runInClient=true, all tasks will be routed to 'execClientTasks'.
+ * This is because client-side execution is the "special" case requiring local tool access.
*/
execTasks = async (
params: ExecTasksParams,
@@ -473,14 +484,20 @@ class GTDExecutor extends BaseExecutor<typeof GTDApiNameEnum> {
const taskCount = tasks.length;
const taskList = tasks.map((t, i) => `${i + 1}. ${t.description}`).join('\n');
+ // Check if any task requires client-side execution
+ const hasClientTasks = tasks.some((t) => t.runInClient);
+
+ // Determine state type: if any task needs client-side, route all to client executor
+ const stateType = hasClientTasks ? 'execClientTasks' : 'execTasks';
+ const executionMode = hasClientTasks ? 'client-side' : '';
+
// Return stop: true with special state that AgentRuntime will recognize
- // The exec_tasks executor will be triggered by the runtime when it sees this state
return {
- content: `🚀 Triggered ${taskCount} async task${taskCount > 1 ? 's' : ''} for execution:\n${taskList}`,
+ content: `🚀 Triggered ${taskCount} async task${taskCount > 1 ? 's' : ''} for ${executionMode} execution:\n${taskList}`,
state: {
parentMessageId: ctx.messageId,
tasks,
- type: 'execTasks',
+ type: stateType,
},
stop: true,
success: true,
diff --git a/packages/builtin-tool-gtd/src/manifest.ts b/packages/builtin-tool-gtd/src/manifest.ts
index e079c4a2540..51a66975248 100644
--- a/packages/builtin-tool-gtd/src/manifest.ts
+++ b/packages/builtin-tool-gtd/src/manifest.ts
@@ -1,5 +1,6 @@
import type { BuiltinToolManifest } from '@lobechat/types';
+import { isDesktop } from './const';
import { systemPrompt } from './systemRole';
import { GTDApiName } from './types';
@@ -171,6 +172,13 @@ export const GTDManifest: BuiltinToolManifest = {
'Whether to inherit context messages from the parent conversation. Default is false.',
type: 'boolean',
},
+ ...(isDesktop && {
+ runInClient: {
+ description:
+ 'Whether to run on the desktop client (for local file/shell access). MUST be true when task requires local-system tools. Default is false (server execution).',
+ type: 'boolean',
+ },
+ }),
timeout: {
description: 'Optional timeout in milliseconds. Default is 30 minutes.',
type: 'number',
@@ -203,6 +211,13 @@ export const GTDManifest: BuiltinToolManifest = {
'Whether to inherit context messages from the parent conversation. Default is false.',
type: 'boolean',
},
+ ...(isDesktop && {
+ runInClient: {
+ description:
+ 'Whether to run on the desktop client (for local file/shell access). MUST be true when task requires local-system tools. Default is false (server execution).',
+ type: 'boolean',
+ },
+ }),
timeout: {
description: 'Optional timeout in milliseconds. Default is 30 minutes.',
type: 'number',
diff --git a/packages/builtin-tool-gtd/src/systemRole.ts b/packages/builtin-tool-gtd/src/systemRole.ts
index fc6b11683b3..9cdfb2ae14d 100644
--- a/packages/builtin-tool-gtd/src/systemRole.ts
+++ b/packages/builtin-tool-gtd/src/systemRole.ts
@@ -1,3 +1,35 @@
+import { isDesktop } from './const';
+
+const runInClientSection = `
+<run_in_client>
+**IMPORTANT: When to use \`runInClient: true\` for async tasks**
+
+The \`runInClient\` parameter controls WHERE the async task executes:
+- \`runInClient: false\` (default): Task runs on the **server** - suitable for web searches, API calls, general research
+- \`runInClient: true\`: Task runs on the **desktop client** - required for local system access
+
+**MUST set \`runInClient: true\` when the task involves:**
+- Reading or writing local files (via \`local-system\` tool)
+- Executing shell commands on the user's machine
+- Accessing local directories or file system
+- Any operation that requires desktop-only local tools
+
+**Keep \`runInClient: false\` (or omit) when:**
+- Task only needs web searches or API calls
+- Task processes data that doesn't require local file access
+- Task can be fully completed with server-side capabilities
+
+**Note:** \`runInClient\` only has effect on the **desktop app**. On web platform, tasks always run on the server regardless of this setting.
+
+**Examples:**
+- "Research Python best practices" → \`runInClient: false\` (web search only)
+- "Organize files in my Downloads folder" → \`runInClient: true\` (local file access required)
+- "Read the project README and summarize it" → \`runInClient: true\` (local file read required)
+- "Find trending tech news" → \`runInClient: false\` (web search only)
+- "Create a new directory structure for my project" → \`runInClient: true\` (local shell/file required)
+</run_in_client>
+`;
+
export const systemPrompt = `You have GTD (Getting Things Done) tools to help manage plans, todos and tasks effectively. These tools support three levels of task management:
- **Plan**: A high-level strategic document describing goals, context, and overall direction. Plans do NOT contain actionable steps - they define the "what" and "why". **Plans should be stable once created** - they represent the overarching objective that rarely changes.
@@ -85,7 +117,7 @@ Use \`execTask\` for a single task, \`execTasks\` for multiple parallel tasks.
- User asks a factual question you know → Just answer directly
- User wants multiple independent analyses → execTasks (parallel execution)
</when_to_use>
-
+${isDesktop ? runInClientSection : ''}
<best_practices>
- **Plan first, then todos**: Always start with a plan unless explicitly told otherwise
- **Separate concerns**: Plans describe goals; Todos list actions
diff --git a/packages/builtin-tool-gtd/src/types.ts b/packages/builtin-tool-gtd/src/types.ts
index b5cb23b4fe0..34a14c06dd7 100644
--- a/packages/builtin-tool-gtd/src/types.ts
+++ b/packages/builtin-tool-gtd/src/types.ts
@@ -14,43 +14,25 @@ export const GTDApiName = {
/** Clear completed or all todos */
clearTodos: 'clearTodos',
-
// ==================== Planning ====================
-/** Create a structured plan by breaking down a goal into actionable steps */
-createPlan: 'createPlan',
+ /** Create a structured plan by breaking down a goal into actionable steps */
+ createPlan: 'createPlan',
-
-
+ /** Create new todo items */
+ createTodos: 'createTodos',
-/** Create new todo items */
-createTodos: 'createTodos',
+ // ==================== Async Tasks ====================
+ /** Execute a single async task */
+ execTask: 'execTask',
-
-
-
-// ==================== Async Tasks ====================
-/** Execute a single async task */
-execTask: 'execTask',
+ /** Execute one or more async tasks */
+ execTasks: 'execTasks',
-
-
+ /** Update an existing plan */
+ updatePlan: 'updatePlan',
-
-/** Execute one or more async tasks */
-execTasks: 'execTasks',
-
-
-
-
-
-
-/** Update an existing plan */
-updatePlan: 'updatePlan',
-
-
-
-/** Update todo items with batch operations (add, update, remove, complete, processing) */
-updateTodos: 'updateTodos',
+ /** Update todo items with batch operations (add, update, remove, complete, processing) */
+ updateTodos: 'updateTodos',
} as const;
export type GTDApiNameType = (typeof GTDApiName)[keyof typeof GTDApiName];
@@ -258,6 +240,14 @@ export interface ExecTaskItem {
inheritMessages?: boolean;
/** Detailed instruction/prompt for the task execution */
instruction: string;
+ /**
+ * Whether to execute the task on the client side (desktop only).
+ * When true and running on desktop, the task will be executed locally
+ * with access to local tools (file system, shell commands, etc.).
+ *
+ * MUST be true when task requires local-system tools.
+ */
+ runInClient?: boolean;
/** Timeout in milliseconds (optional, default 30 minutes) */
timeout?: number;
}
@@ -273,6 +263,14 @@ export interface ExecTaskParams {
inheritMessages?: boolean;
/** Detailed instruction/prompt for the task execution */
instruction: string;
+ /**
+ * Whether to execute the task on the client side (desktop only).
+ * When true and running on desktop, the task will be executed locally
+ * with access to local tools (file system, shell commands, etc.).
+ *
+ * MUST be true when task requires local-system tools.
+ */
+ runInClient?: boolean;
/** Timeout in milliseconds (optional, default 30 minutes) */
timeout?: number;
}
@@ -287,7 +285,7 @@ export interface ExecTasksParams {
}
/**
- * State returned after triggering exec_task
+ * State returned after triggering exec_task (server-side)
*/
export interface ExecTaskState {
/** Parent message ID (tool message) */
@@ -299,7 +297,7 @@ export interface ExecTaskState {
}
/**
- * State returned after triggering exec_tasks
+ * State returned after triggering exec_tasks (server-side)
*/
export interface ExecTasksState {
/** Parent message ID (tool message) */
@@ -309,3 +307,27 @@ export interface ExecTasksState {
/** Type identifier for render component */
type: 'execTasks';
}
+
+/**
+ * State returned after triggering exec_client_task (client-side, desktop only)
+ */
+export interface ExecClientTaskState {
+ /** Parent message ID (tool message) */
+ parentMessageId: string;
+ /** The task definition that was triggered */
+ task: ExecTaskItem;
+ /** Type identifier for render component */
+ type: 'execClientTask';
+}
+
+/**
+ * State returned after triggering exec_client_tasks (client-side, desktop only)
+ */
+export interface ExecClientTasksState {
+ /** Parent message ID (tool message) */
+ parentMessageId: string;
+ /** Array of task definitions that were triggered */
+ tasks: ExecTaskItem[];
+ /** Type identifier for render component */
+ type: 'execClientTasks';
+}
diff --git a/packages/builtin-tool-local-system/src/client/Inspector/ReadLocalFile/index.tsx b/packages/builtin-tool-local-system/src/client/Inspector/ReadLocalFile/index.tsx
index 1e6b2972d65..a5d617e6564 100644
--- a/packages/builtin-tool-local-system/src/client/Inspector/ReadLocalFile/index.tsx
+++ b/packages/builtin-tool-local-system/src/client/Inspector/ReadLocalFile/index.tsx
@@ -15,6 +15,7 @@ const styles = createStaticStyles(({ css }) => ({
lineRange: css`
flex-shrink: 0;
margin-inline-start: 4px;
+ font-size: 12px;
opacity: 0.7;
`,
}));
diff --git a/packages/builtin-tool-local-system/src/client/Inspector/RunCommand/index.tsx b/packages/builtin-tool-local-system/src/client/Inspector/RunCommand/index.tsx
index a2104059a1b..2b2307c460e 100644
--- a/packages/builtin-tool-local-system/src/client/Inspector/RunCommand/index.tsx
+++ b/packages/builtin-tool-local-system/src/client/Inspector/RunCommand/index.tsx
@@ -47,7 +47,7 @@ export const RunCommandInspector = memo<BuiltinInspectorProps<RunCommandParams,
// Get execution result from pluginState
const result = pluginState?.result;
- const isSuccess = result?.success && result?.exit_code === 0;
+ const isSuccess = result?.success || result?.exit_code === 0;
return (
<div className={cx(inspectorTextStyles.root, isLoading && shinyTextStyles.shinyText)}>
diff --git a/packages/builtin-tool-local-system/src/client/Render/WriteFile/index.tsx b/packages/builtin-tool-local-system/src/client/Render/WriteFile/index.tsx
index 55e5124822f..14239dcb9a6 100644
--- a/packages/builtin-tool-local-system/src/client/Render/WriteFile/index.tsx
+++ b/packages/builtin-tool-local-system/src/client/Render/WriteFile/index.tsx
@@ -32,7 +32,7 @@ const WriteFile = memo<BuiltinRenderProps<WriteLocalFileParams>>(({ args }) => {
if (ext === 'md' || ext === 'mdx') {
return (
- <Markdown style={{ maxHeight: 240, overflow: 'auto', padding: '0 8px' }}>
+ <Markdown style={{ maxHeight: 240, overflow: 'auto', padding: '0 8px' }} variant={'chat'}>
{args.content}
</Markdown>
);
diff --git a/packages/builtin-tool-local-system/src/client/Streaming/WriteFile/index.tsx b/packages/builtin-tool-local-system/src/client/Streaming/WriteFile/index.tsx
index c3dcf7c5fea..8424c504110 100644
--- a/packages/builtin-tool-local-system/src/client/Streaming/WriteFile/index.tsx
+++ b/packages/builtin-tool-local-system/src/client/Streaming/WriteFile/index.tsx
@@ -19,7 +19,11 @@ export const WriteFileStreaming = memo<BuiltinStreamingProps<WriteLocalFileParam
// Use Markdown for .md files, Highlighter for others
if (ext === 'md' || ext === 'mdx') {
- return <Markdown style={{ overflow: 'auto' }}>{content}</Markdown>;
+ return (
+ <Markdown animated style={{ overflow: 'auto' }} variant={'chat'}>
+ {content}
+ </Markdown>
+ );
}
return (
diff --git a/packages/builtin-tool-notebook/src/systemRole.ts b/packages/builtin-tool-notebook/src/systemRole.ts
index 23d4fcbd252..f0575d7f2ed 100644
--- a/packages/builtin-tool-notebook/src/systemRole.ts
+++ b/packages/builtin-tool-notebook/src/systemRole.ts
@@ -12,11 +12,17 @@ Note: The list of existing documents is automatically provided in the context, s
<when_to_use>
**Save to Notebook when**:
-- Creating reports, analyses, or summaries that should persist
- User explicitly asks to "save", "write down", or "document" something
-- Generating structured content like articles, notes, or reports
-- Web browsing results worth keeping for later reference
-- Any content the user might want to review or edit later
+- Creating substantial content meant to persist (reports, articles, analyses)
+- Generating structured deliverables the user will likely reference later
+- Web browsing results worth keeping for future reference
+
+**Do NOT save to Notebook when**:
+- User asks a simple question (just answer directly)
+- Providing explanations, tutorials, or how-to responses
+- Having casual conversations or discussions
+- Content is short, temporary, or doesn't need persistence
+- User didn't request saving and the content isn't a clear deliverable
**Document Types**:
- markdown: General formatted text (default)
@@ -44,8 +50,22 @@ Note: The list of existing documents is automatically provided in the context, s
<response_format>
After creating/updating documents:
-- Briefly confirm the action: "Saved to Notebook: [title]"
-- Don't repeat the full content in your response
-- Mention that user can view/edit in the Portal sidebar
+- Confirm the action briefly: "Saved to Notebook: [title]"
+- Provide a short summary (2-4 bullet points max) highlighting only the key takeaways
+- NEVER repeat or rephrase the full document content - the user just saw it being created
+- Optionally mention they can view/edit in the sidebar
+
+❌ Bad (repeating content):
+"I've saved 'Project Plan' which covers the three-phase implementation approach. Phase 1 focuses on user research and requirements gathering from March to April. Phase 2 involves design and prototyping from May to June. Phase 3 covers development and testing from July to September..."
+
+✅ Good (brief summary):
+"Saved to Notebook: Project Plan
+
+Key points:
+- 3-phase approach: Research → Design → Development
+- Timeline: March - September
+- 5 team members involved
+
+You can edit it in the sidebar."
</response_format>
`;
diff --git a/packages/conversation-flow/src/transformation/FlatListBuilder.ts b/packages/conversation-flow/src/transformation/FlatListBuilder.ts
index 27e805884df..a4fccd9cafb 100644
--- a/packages/conversation-flow/src/transformation/FlatListBuilder.ts
+++ b/packages/conversation-flow/src/transformation/FlatListBuilder.ts
@@ -31,8 +31,20 @@ export class FlatListBuilder {
const flatList: Message[] = [];
const processedIds = new Set<string>();
+ // Determine the root parentId
+ // Normal case: start from null (messages with no parentId)
+ // Orphan case: if all messages have parentId (thread mode), use first message as root
+ let rootParentId: string | null = null;
+
+ const hasRootMessages = this.childrenMap.has(null) && this.childrenMap.get(null)!.length > 0;
+ if (!hasRootMessages && messages.length > 0) {
+ // All messages have parentId - this is orphan/thread mode
+ // Use the first message's parentId as the virtual root
+ rootParentId = messages[0].parentId ?? null;
+ }
+
// Build the active path by traversing from root
- this.buildFlatListRecursive(null, flatList, processedIds, messages);
+ this.buildFlatListRecursive(rootParentId, flatList, processedIds, messages);
return flatList;
}
diff --git a/packages/conversation-flow/src/transformation/__tests__/FlatListBuilder.test.ts b/packages/conversation-flow/src/transformation/__tests__/FlatListBuilder.test.ts
index 0ec476eca76..97906045ad3 100644
--- a/packages/conversation-flow/src/transformation/__tests__/FlatListBuilder.test.ts
+++ b/packages/conversation-flow/src/transformation/__tests__/FlatListBuilder.test.ts
@@ -517,5 +517,45 @@ describe('FlatListBuilder', () => {
// User message should not have branch info since we're in optimistic update mode
expect((result[0] as any).siblingCount).toBeUndefined();
});
+
+ it('should handle orphan messages where all have parentId (thread mode)', () => {
+ // Scenario: Thread messages where the parent (source message) is not in the query result
+ // All messages have parentId pointing to a message not in the array
+ const messages: Message[] = [
+ {
+ content: 'Thread user message',
+ createdAt: 0,
+ id: 'msg-1',
+ parentId: 'source-msg-not-in-array',
+ role: 'user',
+ updatedAt: 0,
+ },
+ {
+ content: 'Thread assistant reply',
+ createdAt: 0,
+ id: 'msg-2',
+ parentId: 'msg-1',
+ role: 'assistant',
+ updatedAt: 0,
+ },
+ {
+ content: 'Thread user follow-up',
+ createdAt: 0,
+ id: 'msg-3',
+ parentId: 'msg-2',
+ role: 'user',
+ updatedAt: 0,
+ },
+ ];
+
+ const builder = createBuilder(messages);
+ const result = builder.flatten(messages);
+
+ // Should flatten all messages correctly using first message's parentId as virtual root
+ expect(result).toHaveLength(3);
+ expect(result[0].id).toBe('msg-1');
+ expect(result[1].id).toBe('msg-2');
+ expect(result[2].id).toBe('msg-3');
+ });
});
});
diff --git a/packages/database/src/models/__tests__/messages/message.thread-query.test.ts b/packages/database/src/models/__tests__/messages/message.thread-query.test.ts
index 71de83421fd..934b9a1c334 100644
--- a/packages/database/src/models/__tests__/messages/message.thread-query.test.ts
+++ b/packages/database/src/models/__tests__/messages/message.thread-query.test.ts
@@ -1,10 +1,10 @@
import { eq, sql } from 'drizzle-orm';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { getTestDB } from '../../../core/getTestDB';
import { agents, messages, sessions, threads, topics, users } from '../../../schemas';
import { LobeChatDatabase } from '../../../type';
import { MessageModel } from '../../message';
-import { getTestDB } from '../../../core/getTestDB';
const serverDB: LobeChatDatabase = await getTestDB();
@@ -337,6 +337,90 @@ describe('MessageModel thread query', () => {
expect(result.map((m) => m.id)).toEqual(['msg2', 'thread-msg1', 'thread-msg2']);
});
+ it('should return only thread messages for Isolation type (no parent messages)', async () => {
+ await serverDB.transaction(async (trx) => {
+ await trx.insert(agents).values([{ id: 'agent1', userId }]);
+ await trx.insert(topics).values([{ id: 'topic1', userId }]);
+
+ // Create thread with Isolation type
+ await trx.insert(threads).values([
+ {
+ id: 'thread1',
+ userId,
+ topicId: 'topic1',
+ sourceMessageId: 'msg2',
+ type: 'isolation',
+ },
+ ]);
+
+ // Create main conversation messages
+ await trx.insert(messages).values([
+ {
+ id: 'msg1',
+ userId,
+ agentId: 'agent1',
+ topicId: 'topic1',
+ threadId: null,
+ role: 'user',
+ content: 'first message',
+ createdAt: new Date('2023-01-01'),
+ },
+ {
+ id: 'msg2',
+ userId,
+ agentId: 'agent1',
+ topicId: 'topic1',
+ threadId: null,
+ role: 'assistant',
+ content: 'second message - source',
+ createdAt: new Date('2023-01-02'),
+ },
+ {
+ id: 'msg3',
+ userId,
+ agentId: 'agent1',
+ topicId: 'topic1',
+ threadId: null,
+ role: 'user',
+ content: 'third message',
+ createdAt: new Date('2023-01-03'),
+ },
+ // Thread messages
+ {
+ id: 'thread-msg1',
+ userId,
+ agentId: 'agent1',
+ topicId: 'topic1',
+ threadId: 'thread1',
+ role: 'user',
+ content: 'thread message 1',
+ createdAt: new Date('2023-01-02T10:00:00'),
+ },
+ {
+ id: 'thread-msg2',
+ userId,
+ agentId: 'agent1',
+ topicId: 'topic1',
+ threadId: 'thread1',
+ role: 'assistant',
+ content: 'thread message 2',
+ createdAt: new Date('2023-01-02T11:00:00'),
+ },
+ ]);
+ });
+
+ const result = await messageModel.query({
+ agentId: 'agent1',
+ topicId: 'topic1',
+ threadId: 'thread1',
+ });
+
+ // For Isolation: should include ONLY thread messages, NO parent messages at all
+ // Should NOT include msg1, msg2 (source), or msg3
+ expect(result).toHaveLength(2);
+ expect(result.map((m) => m.id)).toEqual(['thread-msg1', 'thread-msg2']);
+ });
+
it('should return only thread messages when thread has no sourceMessageId', async () => {
await serverDB.transaction(async (trx) => {
await trx.insert(sessions).values([{ id: 'session1', userId }]);
@@ -572,6 +656,55 @@ describe('MessageModel thread query', () => {
expect(result[0].id).toBe('msg2');
});
+ it('should return empty array for Isolation thread type', async () => {
+ await serverDB.transaction(async (trx) => {
+ await trx.insert(agents).values([{ id: 'agent1', userId }]);
+ await trx.insert(topics).values([{ id: 'topic1', userId }]);
+
+ await trx.insert(messages).values([
+ {
+ id: 'msg1',
+ userId,
+ agentId: 'agent1',
+ topicId: 'topic1',
+ threadId: null,
+ role: 'user',
+ content: 'first',
+ createdAt: new Date('2023-01-01'),
+ },
+ {
+ id: 'msg2',
+ userId,
+ agentId: 'agent1',
+ topicId: 'topic1',
+ threadId: null,
+ role: 'assistant',
+ content: 'second - source',
+ createdAt: new Date('2023-01-02'),
+ },
+ {
+ id: 'msg3',
+ userId,
+ agentId: 'agent1',
+ topicId: 'topic1',
+ threadId: null,
+ role: 'user',
+ content: 'third',
+ createdAt: new Date('2023-01-03'),
+ },
+ ]);
+ });
+
+ const result = await messageModel.getThreadParentMessages({
+ sourceMessageId: 'msg2',
+ topicId: 'topic1',
+ threadType: 'isolation' as any,
+ });
+
+ // Isolation should return empty array (no parent messages)
+ expect(result).toHaveLength(0);
+ });
+
it('should return all messages up to source message for Continuation thread type', async () => {
await serverDB.transaction(async (trx) => {
await trx.insert(sessions).values([{ id: 'session1', userId }]);
diff --git a/packages/database/src/models/message.ts b/packages/database/src/models/message.ts
index cfff57ebeb5..ef14a63ba6c 100644
--- a/packages/database/src/models/message.ts
+++ b/packages/database/src/models/message.ts
@@ -431,6 +431,7 @@ export class MessageModel {
return [
t.sourceMessageId!,
{
+ clientMode: metadata?.clientMode as boolean | undefined,
duration: metadata?.duration as number | undefined,
status: t.status as ThreadStatus,
threadId: t.threadId,
@@ -678,10 +679,11 @@ export class MessageModel {
* @param params - Parameters for getting parent messages
* @param params.sourceMessageId - The ID of the source message that started the thread
* @param params.topicId - The topic ID the thread belongs to
- * @param params.threadType - The type of thread (Continuation or Standalone)
+ * @param params.threadType - The type of thread (Continuation, Standalone, or Isolation)
* @returns Parent messages based on thread type:
* - Continuation: All messages from the topic up to and including the source message
* - Standalone: Only the source message itself
+ * - Isolation: No parent messages (completely isolated thread)
*/
getThreadParentMessages = async (params: {
sourceMessageId: string;
@@ -690,6 +692,11 @@ export class MessageModel {
}): Promise<DBMessageItem[]> => {
const { sourceMessageId, topicId, threadType } = params;
+ // For Isolation type, return empty array (no parent messages)
+ if (threadType === ThreadType.Isolation) {
+ return [];
+ }
+
// For Standalone type, only return the source message
if (threadType === ThreadType.Standalone) {
const sourceMessage = await this.db.query.messages.findFirst({
diff --git a/packages/database/src/models/thread.ts b/packages/database/src/models/thread.ts
index bc5f09be4b8..89705df380e 100644
--- a/packages/database/src/models/thread.ts
+++ b/packages/database/src/models/thread.ts
@@ -32,7 +32,7 @@ export class ThreadModel {
// @ts-ignore
const [result] = await this.db
.insert(threads)
- .values({ ...params, status: ThreadStatus.Active, userId: this.userId })
+ .values({ status: ThreadStatus.Active, ...params, userId: this.userId })
.onConflictDoNothing()
.returning();
diff --git a/packages/types/src/message/ui/chat.ts b/packages/types/src/message/ui/chat.ts
index 59e2c580bb9..c06ffd0e7d6 100644
--- a/packages/types/src/message/ui/chat.ts
+++ b/packages/types/src/message/ui/chat.ts
@@ -64,6 +64,8 @@ interface UIMessageBranch {
* Retrieved from the associated Thread via sourceMessageId
*/
export interface TaskDetail {
+ /** Whether this task runs in client mode (local execution) */
+ clientMode?: boolean;
/** Task completion time (ISO string) */
completedAt?: string;
/** Execution duration in milliseconds */
diff --git a/packages/types/src/topic/thread.ts b/packages/types/src/topic/thread.ts
index a2831d00dc7..8591030ea10 100644
--- a/packages/types/src/topic/thread.ts
+++ b/packages/types/src/topic/thread.ts
@@ -23,6 +23,8 @@ export enum ThreadStatus {
* Metadata for Thread, used for agent task execution
*/
export interface ThreadMetadata {
+ /** Whether this thread runs in client mode (local execution) */
+ clientMode?: boolean;
/** Task completion time */
completedAt?: string;
/** Execution duration in milliseconds */
@@ -68,16 +70,34 @@ export interface CreateThreadParams {
agentId?: string;
/** Group ID for group chat context */
groupId?: string;
+ /** Initial metadata for the thread */
+ metadata?: ThreadMetadata;
parentThreadId?: string;
sourceMessageId?: string;
+ /** Initial status (defaults to Active) */
+ status?: ThreadStatus;
title?: string;
topicId: string;
type: IThreadType;
}
+export const threadMetadataSchema = z.object({
+ clientMode: z.boolean().optional(),
+ completedAt: z.string().optional(),
+ duration: z.number().optional(),
+ error: z.any().optional(),
+ operationId: z.string().optional(),
+ startedAt: z.string().optional(),
+ totalCost: z.number().optional(),
+ totalMessages: z.number().optional(),
+ totalTokens: z.number().optional(),
+ totalToolCalls: z.number().optional(),
+});
+
export const createThreadSchema = z.object({
agentId: z.string().optional(),
groupId: z.string().optional(),
+ metadata: threadMetadataSchema.optional(),
parentThreadId: z.string().optional(),
sourceMessageId: z.string().optional(),
title: z.string().optional(),
diff --git a/src/components/StreamingMarkdown/index.tsx b/src/components/StreamingMarkdown/index.tsx
index b555c1c78c0..4873bfc2a8f 100644
--- a/src/components/StreamingMarkdown/index.tsx
+++ b/src/components/StreamingMarkdown/index.tsx
@@ -2,7 +2,9 @@
import { Markdown, ScrollShadow } from '@lobehub/ui';
import { createStaticStyles } from 'antd-style';
-import { memo, useCallback, useEffect, useRef, useState } from 'react';
+import { type RefObject, memo, useEffect } from 'react';
+
+import { useAutoScroll } from '@/hooks/useAutoScroll';
const styles = createStaticStyles(({ css }) => ({
container: css`
@@ -19,51 +21,16 @@ interface StreamingMarkdownProps {
}
const StreamingMarkdown = memo<StreamingMarkdownProps>(({ children, maxHeight = 400 }) => {
- const containerRef = useRef<HTMLDivElement>(null);
- const [userHasScrolled, setUserHasScrolled] = useState(false);
- const isAutoScrollingRef = useRef(false);
-
- // Handle user scroll detection
- const handleScroll = useCallback(() => {
- // Ignore scroll events triggered by auto-scroll
- if (isAutoScrollingRef.current) return;
-
- const container = containerRef.current;
- if (!container) return;
-
- // Check if user scrolled away from bottom
- const distanceToBottom = container.scrollHeight - container.scrollTop - container.clientHeight;
- const isAtBottom = distanceToBottom < 20;
-
- // If user scrolled up, stop auto-scrolling
- if (!isAtBottom) {
- setUserHasScrolled(true);
- }
- }, []);
-
- // Auto scroll to bottom when content changes (unless user has scrolled)
- useEffect(() => {
- if (userHasScrolled) return;
-
- const container = containerRef.current;
- if (!container) return;
-
- isAutoScrollingRef.current = true;
- requestAnimationFrame(() => {
- container.scrollTop = container.scrollHeight;
- // Reset the flag after scroll completes
- requestAnimationFrame(() => {
- isAutoScrollingRef.current = false;
- });
- });
- }, [children, userHasScrolled]);
+ const { ref, handleScroll, resetScrollLock } = useAutoScroll<HTMLDivElement>({
+ deps: [children],
+ });
- // Reset userHasScrolled when content is cleared (new stream starts)
+ // Reset scroll lock when content is cleared (new stream starts)
useEffect(() => {
if (!children) {
- setUserHasScrolled(false);
+ resetScrollLock();
}
- }, [children]);
+ }, [children, resetScrollLock]);
if (!children) return null;
@@ -72,7 +39,7 @@ const StreamingMarkdown = memo<StreamingMarkdownProps>(({ children, maxHeight =
className={styles.container}
offset={12}
onScroll={handleScroll}
- ref={containerRef}
+ ref={ref as RefObject<HTMLDivElement>}
size={12}
style={{ maxHeight }}
>
diff --git a/src/features/Conversation/Messages/AssistantGroup/components/MessageContent.tsx b/src/features/Conversation/Messages/AssistantGroup/components/MessageContent.tsx
index b83d30588fe..d2092fe1198 100644
--- a/src/features/Conversation/Messages/AssistantGroup/components/MessageContent.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/components/MessageContent.tsx
@@ -28,8 +28,6 @@ const MessageContent = memo<ContentBlockProps>(({ content, hasTools, id }) => {
if (!content && !hasTools) return <ContentLoading id={id} />;
if (content === LOADING_FLAT) {
- if (hasTools) return null;
-
return <ContentLoading id={id} />;
}
diff --git a/src/features/Conversation/Messages/Task/ClientTaskDetail/CompletedState.tsx b/src/features/Conversation/Messages/Task/ClientTaskDetail/CompletedState.tsx
new file mode 100644
index 00000000000..2393894d374
--- /dev/null
+++ b/src/features/Conversation/Messages/Task/ClientTaskDetail/CompletedState.tsx
@@ -0,0 +1,108 @@
+'use client';
+
+import { type AssistantContentBlock } from '@lobechat/types';
+import { Accordion, AccordionItem, Block, Flexbox, Icon, Text } from '@lobehub/ui';
+import { cssVar } from 'antd-style';
+import { Workflow } from 'lucide-react';
+import { memo, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import ContentBlock from '../../AssistantGroup/components/ContentBlock';
+import { formatDuration } from '../../Tasks/shared/utils';
+import Usage from '../../components/Extras/Usage';
+
+interface CompletedStateProps {
+ assistantId: string;
+ blocks: AssistantContentBlock[];
+ duration?: number;
+ model?: string;
+ provider?: string;
+ totalCost?: number;
+ totalTokens?: number;
+ totalToolCalls?: number;
+}
+
+const CompletedState = memo<CompletedStateProps>(
+ ({ blocks, assistantId, duration, totalToolCalls, model, provider, totalTokens, totalCost }) => {
+ const { t } = useTranslation('chat');
+
+ // Split blocks: intermediate steps (all but last) and final result (last)
+ const { intermediateBlocks, finalBlock } = useMemo(() => {
+ if (blocks.length === 0) return { finalBlock: null, intermediateBlocks: [] };
+ if (blocks.length === 1) return { finalBlock: blocks[0], intermediateBlocks: [] };
+
+ return {
+ finalBlock: blocks.at(-1)!,
+ intermediateBlocks: blocks.slice(0, -1),
+ };
+ }, [blocks]);
+
+ if (!finalBlock) return null;
+
+ const title = (
+ <Flexbox align="center" gap={8} horizontal>
+ <Block
+ align="center"
+ flex="none"
+ gap={4}
+ height={24}
+ horizontal
+ justify="center"
+ style={{ fontSize: 12 }}
+ variant="outlined"
+ width={24}
+ >
+ <Icon color={cssVar.colorTextSecondary} icon={Workflow} />
+ </Block>
+ <Flexbox align="center" gap={4} horizontal>
+ <Text as="span" type="secondary" weight={500}>
+ {totalToolCalls}
+ </Text>
+ <Text as="span" type="secondary">
+ {t('task.metrics.toolCallsShort')}
+ </Text>
+ {/* Duration display */}
+ {duration && (
+ <Text as="span" type="secondary">
+ {t('task.metrics.duration', { duration: formatDuration(duration) })}
+ </Text>
+ )}
+ </Flexbox>
+ </Flexbox>
+ );
+
+ return (
+ <Flexbox gap={8}>
+ {/* Intermediate steps - collapsed by default */}
+ {intermediateBlocks.length > 0 && (
+ <Accordion defaultExpandedKeys={[]} gap={8}>
+ <AccordionItem itemKey="intermediate" paddingBlock={4} paddingInline={4} title={title}>
+ <Flexbox gap={8} paddingInline={4} style={{ marginTop: 8 }}>
+ {intermediateBlocks.map((block) => (
+ <ContentBlock
+ {...block}
+ assistantId={assistantId}
+ disableEditing
+ key={block.id}
+ />
+ ))}
+ </Flexbox>
+ </AccordionItem>
+ </Accordion>
+ )}
+
+ {/* Final result - always visible */}
+ <ContentBlock {...finalBlock} assistantId={assistantId} disableEditing />
+
+ {/* Usage display */}
+ {model && provider && (
+ <Usage model={model} provider={provider} usage={{ cost: totalCost, totalTokens }} />
+ )}
+ </Flexbox>
+ );
+ },
+);
+
+CompletedState.displayName = 'ClientCompletedState';
+
+export default CompletedState;
diff --git a/src/features/Conversation/Messages/Task/ClientTaskDetail/InitializingState.tsx b/src/features/Conversation/Messages/Task/ClientTaskDetail/InitializingState.tsx
new file mode 100644
index 00000000000..5dcba8626f3
--- /dev/null
+++ b/src/features/Conversation/Messages/Task/ClientTaskDetail/InitializingState.tsx
@@ -0,0 +1,66 @@
+'use client';
+
+import { Flexbox, Text } from '@lobehub/ui';
+import { createStaticStyles, keyframes } from 'antd-style';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import NeuralNetworkLoading from '@/components/NeuralNetworkLoading';
+import { shinyTextStyles } from '@/styles';
+
+const shimmer = keyframes`
+ 0% {
+ transform: translateX(-100%);
+ }
+
+ 100% {
+ transform: translateX(100%);
+ }
+`;
+
+const styles = createStaticStyles(({ css, cssVar }) => ({
+ container: css`
+ padding-block: 12px;
+ `,
+ progress: css`
+ position: relative;
+
+ overflow: hidden;
+
+ height: 3px;
+ border-radius: 2px;
+
+ background: ${cssVar.colorFillSecondary};
+ `,
+ progressShimmer: css`
+ position: absolute;
+ inset-block-start: 0;
+ inset-inline-start: 0;
+
+ width: 100%;
+ height: 100%;
+
+ background: linear-gradient(90deg, transparent, ${cssVar.colorPrimaryBgHover}, transparent);
+
+ animation: ${shimmer} 2s infinite;
+ `,
+}));
+
+const InitializingState = memo(() => {
+ const { t } = useTranslation('chat');
+
+ return (
+ <Flexbox className={styles.container} gap={12}>
+ <Flexbox align="center" gap={8} horizontal>
+ <NeuralNetworkLoading size={14} />
+ <Text className={shinyTextStyles.shinyText} weight={500}>
+ {t('task.status.initializing')}
+ </Text>
+ </Flexbox>
+ </Flexbox>
+ );
+});
+
+InitializingState.displayName = 'InitializingState';
+
+export default InitializingState;
diff --git a/src/features/Conversation/Messages/Task/ClientTaskDetail/InstructionAccordion.tsx b/src/features/Conversation/Messages/Task/ClientTaskDetail/InstructionAccordion.tsx
new file mode 100644
index 00000000000..87269f673ad
--- /dev/null
+++ b/src/features/Conversation/Messages/Task/ClientTaskDetail/InstructionAccordion.tsx
@@ -0,0 +1,63 @@
+import { Accordion, AccordionItem, Block, Flexbox, Icon, Markdown, Text } from '@lobehub/ui';
+import { cssVar } from 'antd-style';
+import { ScrollText } from 'lucide-react';
+import { memo, useEffect, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+interface InstructionAccordionProps {
+ childrenCount: number;
+ instruction: string;
+}
+
+const InstructionAccordion = memo<InstructionAccordionProps>(({ instruction, childrenCount }) => {
+ const { t } = useTranslation('chat');
+
+ // Auto-collapse instruction when children count exceeds threshold
+ const [expandedKeys, setExpandedKeys] = useState<string[]>(['instruction']);
+
+ useEffect(() => {
+ if (childrenCount > 1) {
+ setExpandedKeys([]);
+ }
+ }, [childrenCount > 1]);
+
+ return (
+ <Accordion
+ expandedKeys={expandedKeys}
+ gap={8}
+ onExpandedChange={(keys) => setExpandedKeys(keys as string[])}
+ >
+ <AccordionItem
+ itemKey="instruction"
+ paddingBlock={4}
+ paddingInline={4}
+ title={
+ <Flexbox align="center" gap={8} horizontal>
+ <Block
+ align="center"
+ flex="none"
+ gap={4}
+ height={24}
+ horizontal
+ justify="center"
+ style={{ fontSize: 12 }}
+ variant="outlined"
+ width={24}
+ >
+ <Icon color={cssVar.colorTextSecondary} icon={ScrollText} />
+ </Block>
+ <Text as="span" type="secondary">
+ {t('task.instruction')}
+ </Text>
+ </Flexbox>
+ }
+ >
+ <Block padding={12} style={{ marginBlock: 8, maxHeight: 300, overflow: 'auto' }} variant={'outlined'}>
+ <Markdown variant={'chat'}>{instruction}</Markdown>
+ </Block>
+ </AccordionItem>
+ </Accordion>
+ );
+});
+
+export default InstructionAccordion;
diff --git a/src/features/Conversation/Messages/Task/ClientTaskDetail/ProcessingState.tsx b/src/features/Conversation/Messages/Task/ClientTaskDetail/ProcessingState.tsx
new file mode 100644
index 00000000000..87e12d149d9
--- /dev/null
+++ b/src/features/Conversation/Messages/Task/ClientTaskDetail/ProcessingState.tsx
@@ -0,0 +1,123 @@
+'use client';
+
+import { type AssistantContentBlock } from '@lobechat/types';
+import { Block, Flexbox, ScrollShadow, Text } from '@lobehub/ui';
+import { createStaticStyles } from 'antd-style';
+import { type RefObject, memo, useEffect, useMemo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import NeuralNetworkLoading from '@/components/NeuralNetworkLoading';
+import AnimatedNumber from '@/features/Conversation/Messages/components/Extras/Usage/UsageDetail/AnimatedNumber';
+import { useAutoScroll } from '@/hooks/useAutoScroll';
+
+import ContentBlock from '../../AssistantGroup/components/ContentBlock';
+import { accumulateUsage, formatElapsedTime } from '../../Tasks/shared/utils';
+import Usage from '../../components/Extras/Usage';
+
+const styles = createStaticStyles(({ css }) => ({
+ contentScroll: css`
+ max-height: min(50vh, 300px);
+ `,
+}));
+
+interface ProcessingStateProps {
+ assistantId: string;
+ blocks: AssistantContentBlock[];
+ model?: string;
+ provider?: string;
+ startTime?: number;
+}
+
+const ProcessingState = memo<ProcessingStateProps>(
+ ({ blocks, assistantId, startTime, model, provider }) => {
+ const { t } = useTranslation('chat');
+ const [elapsedTime, setElapsedTime] = useState(0);
+ const { ref, handleScroll } = useAutoScroll<HTMLDivElement>({
+ deps: [blocks],
+ enabled: true,
+ });
+
+ const totalToolCalls = useMemo(
+ () => blocks.reduce((sum, block) => sum + (block.tools?.length || 0), 0),
+ [blocks],
+ );
+
+ // Accumulate usage from all blocks
+ const accumulatedUsage = useMemo(() => accumulateUsage(blocks), [blocks]);
+
+ // Calculate initial elapsed time
+ useEffect(() => {
+ if (startTime) {
+ setElapsedTime(Math.max(0, Date.now() - startTime));
+ }
+ }, [startTime]);
+
+ // Timer for updating elapsed time every second
+ useEffect(() => {
+ if (!startTime) return;
+
+ const timer = setInterval(() => {
+ setElapsedTime(Math.max(0, Date.now() - startTime));
+ }, 1000);
+
+ return () => clearInterval(timer);
+ }, [startTime]);
+
+ return (
+ <Flexbox gap={8}>
+ <Flexbox align="center" gap={8} horizontal paddingInline={4}>
+ <Block
+ align="center"
+ flex="none"
+ gap={4}
+ height={24}
+ horizontal
+ justify="center"
+ style={{ fontSize: 12 }}
+ variant="outlined"
+ width={24}
+ >
+ <NeuralNetworkLoading size={16} />
+ </Block>
+ <Flexbox align="center" gap={4} horizontal>
+ <Text as="span" type="secondary" weight={500}>
+ <AnimatedNumber
+ duration={500}
+ formatter={(v) => Math.round(v).toString()}
+ value={totalToolCalls}
+ />
+ </Text>
+ <Text as="span" type="secondary">
+ {t('task.metrics.toolCallsShort')}
+ </Text>
+ {startTime && (
+ <Text as="span" type="secondary">
+ ({formatElapsedTime(elapsedTime)})
+ </Text>
+ )}
+ </Flexbox>
+ </Flexbox>
+ <ScrollShadow
+ className={styles.contentScroll}
+ offset={12}
+ onScroll={handleScroll}
+ ref={ref as RefObject<HTMLDivElement>}
+ size={8}
+ >
+ <Flexbox gap={8}>
+ {blocks.map((block) => (
+ <ContentBlock {...block} assistantId={assistantId} disableEditing key={block.id} />
+ ))}
+ </Flexbox>
+ </ScrollShadow>
+
+ {/* Usage display */}
+ {model && provider && <Usage model={model} provider={provider} usage={accumulatedUsage} />}
+ </Flexbox>
+ );
+ },
+);
+
+ProcessingState.displayName = 'ClientProcessingState';
+
+export default ProcessingState;
diff --git a/src/features/Conversation/Messages/Task/ClientTaskDetail/index.tsx b/src/features/Conversation/Messages/Task/ClientTaskDetail/index.tsx
new file mode 100644
index 00000000000..15f99c32cd0
--- /dev/null
+++ b/src/features/Conversation/Messages/Task/ClientTaskDetail/index.tsx
@@ -0,0 +1,106 @@
+'use client';
+
+import { type TaskDetail, ThreadStatus } from '@lobechat/types';
+import { Flexbox } from '@lobehub/ui';
+import { memo, useMemo } from 'react';
+
+import BubblesLoading from '@/components/BubblesLoading';
+import { useChatStore } from '@/store/chat';
+import { displayMessageSelectors } from '@/store/chat/selectors';
+import { messageMapKey } from '@/store/chat/utils/messageMapKey';
+
+import CompletedState from './CompletedState';
+import InitializingState from './InitializingState';
+import InstructionAccordion from './InstructionAccordion';
+import ProcessingState from './ProcessingState';
+
+interface ClientTaskDetailProps {
+ content?: string;
+ messageId: string;
+ taskDetail?: TaskDetail;
+}
+
+const ClientTaskDetail = memo<ClientTaskDetailProps>(({ taskDetail }) => {
+ const threadId = taskDetail?.threadId;
+ const isExecuting = taskDetail?.status === ThreadStatus.Processing;
+
+ const [activeAgentId, activeTopicId, useFetchMessages] = useChatStore((s) => [
+ s.activeAgentId,
+ s.activeTopicId,
+ s.useFetchMessages,
+ ]);
+
+ const threadContext = useMemo(
+ () => ({
+ agentId: activeAgentId,
+ scope: 'thread' as const,
+ threadId,
+ topicId: activeTopicId,
+ }),
+ [activeAgentId, activeTopicId, threadId],
+ );
+
+ const threadMessageKey = useMemo(
+ () => (threadId ? messageMapKey(threadContext) : null),
+ [threadId],
+ );
+
+ // Fetch thread messages (skip when executing - messages come from real-time updates)
+ useFetchMessages(threadContext, isExecuting);
+
+ // Get thread messages from store using selector
+ const threadMessages = useChatStore((s) =>
+ threadMessageKey
+ ? displayMessageSelectors.getDisplayMessagesByKey(threadMessageKey)(s)
+ : undefined,
+ );
+
+ if (!threadMessages) return <BubblesLoading />;
+
+ // Find the assistantGroup message which contains the children blocks
+ const assistantGroupMessage = threadMessages.find((item) => item.role === 'assistantGroup');
+ const instruction = threadMessages.find((item) => item.role === 'user')?.content;
+ const childrenCount = assistantGroupMessage?.children?.length ?? 0;
+
+ // Get model/provider from assistantGroup message
+ const model = assistantGroupMessage?.model;
+ const provider = assistantGroupMessage?.provider;
+
+ // Initializing state: no status yet (task just created, waiting for client execution)
+ if (threadMessages.length === 0 || !assistantGroupMessage?.children || childrenCount === 0) {
+ return <InitializingState />;
+ }
+
+ return (
+ <Flexbox gap={4}>
+ {instruction && (
+ <InstructionAccordion childrenCount={childrenCount} instruction={instruction} />
+ )}
+
+ {isExecuting ? (
+ <ProcessingState
+ assistantId={assistantGroupMessage.id}
+ blocks={assistantGroupMessage.children}
+ model={model ?? undefined}
+ provider={provider ?? undefined}
+ startTime={assistantGroupMessage.createdAt}
+ />
+ ) : (
+ <CompletedState
+ assistantId={assistantGroupMessage.id}
+ blocks={assistantGroupMessage.children}
+ duration={taskDetail?.duration}
+ model={model ?? undefined}
+ provider={provider ?? undefined}
+ totalCost={taskDetail?.totalCost}
+ totalTokens={taskDetail?.totalTokens}
+ totalToolCalls={taskDetail?.totalToolCalls}
+ />
+ )}
+ </Flexbox>
+ );
+});
+
+ClientTaskDetail.displayName = 'ClientClientTaskDetail';
+
+export default ClientTaskDetail;
diff --git a/src/features/Conversation/Messages/Task/TaskDetailPanel/index.tsx b/src/features/Conversation/Messages/Task/TaskDetailPanel/index.tsx
index cc16277e1c7..de98e934542 100644
--- a/src/features/Conversation/Messages/Task/TaskDetailPanel/index.tsx
+++ b/src/features/Conversation/Messages/Task/TaskDetailPanel/index.tsx
@@ -17,6 +17,7 @@ interface TaskDetailPanelProps {
}
const TaskDetailPanel = memo<TaskDetailPanelProps>(({ taskDetail, content, messageId }) => {
+ // Default: server-side task execution
return <StatusContent content={content} messageId={messageId} taskDetail={taskDetail} />;
});
diff --git a/src/features/Conversation/Messages/Task/index.tsx b/src/features/Conversation/Messages/Task/index.tsx
index 52ad3224c48..bc6291594e6 100644
--- a/src/features/Conversation/Messages/Task/index.tsx
+++ b/src/features/Conversation/Messages/Task/index.tsx
@@ -19,6 +19,7 @@ import { useAgentMeta, useDoubleClickEdit } from '../../hooks';
import { dataSelectors, messageStateSelectors, useConversationStore } from '../../store';
import { normalizeThinkTags, processWithArtifact } from '../../utils/markdown';
import { AssistantActionsBar } from './Actions';
+import ClientTaskDetail from './ClientTaskDetail';
import TaskDetailPanel from './TaskDetailPanel';
interface TaskMessageProps {
@@ -91,12 +92,16 @@ const TaskMessage = memo<TaskMessageProps>(({ id, index, disableEditing, isLates
time={createdAt}
titleAddon={<Tag>{t('task.subtask')}</Tag>}
>
- <TaskDetailPanel
- content={content}
- instruction={metadata?.instruction}
- messageId={id}
- taskDetail={taskDetail}
- />
+ {taskDetail?.clientMode ? (
+ <ClientTaskDetail messageId={id} taskDetail={taskDetail} />
+ ) : (
+ <TaskDetailPanel
+ content={content}
+ instruction={metadata?.instruction}
+ messageId={id}
+ taskDetail={taskDetail}
+ />
+ )}
</ChatItem>
);
}, isEqual);
diff --git a/src/features/Conversation/Messages/Tasks/TaskItem/TaskTitle.tsx b/src/features/Conversation/Messages/Tasks/TaskItem/TaskTitle.tsx
index 406c5225bd6..4f6684b635e 100644
--- a/src/features/Conversation/Messages/Tasks/TaskItem/TaskTitle.tsx
+++ b/src/features/Conversation/Messages/Tasks/TaskItem/TaskTitle.tsx
@@ -2,9 +2,10 @@
import { Block, Flexbox, Icon, Text } from '@lobehub/ui';
import { cssVar } from 'antd-style';
-import { ListChecksIcon, Loader2, XIcon } from 'lucide-react';
+import { ListChecksIcon, XIcon } from 'lucide-react';
import { memo } from 'react';
+import NeuralNetworkLoading from '@/components/NeuralNetworkLoading';
import { ThreadStatus } from '@/types/index';
import { isProcessingStatus } from '../shared';
@@ -27,7 +28,7 @@ const TaskStatusIndicator = memo<{ status?: ThreadStatus }>(({ status }) => {
} else if (isError) {
icon = <Icon color={cssVar.colorError} icon={XIcon} />;
} else if (isProcessing || isInitializing) {
- icon = <Icon color={cssVar.colorTextDescription} icon={Loader2} spin />;
+ icon = <NeuralNetworkLoading size={16} />;
} else {
return null;
}
diff --git a/src/features/Conversation/Messages/Tasks/shared/InitializingState.tsx b/src/features/Conversation/Messages/Tasks/shared/InitializingState.tsx
index 17941b46ead..5dcba8626f3 100644
--- a/src/features/Conversation/Messages/Tasks/shared/InitializingState.tsx
+++ b/src/features/Conversation/Messages/Tasks/shared/InitializingState.tsx
@@ -57,10 +57,6 @@ const InitializingState = memo(() => {
{t('task.status.initializing')}
</Text>
</Flexbox>
-
- <div className={styles.progress}>
- <div className={styles.progressShimmer} />
- </div>
</Flexbox>
);
});
diff --git a/src/features/Conversation/Messages/Tasks/shared/utils.ts b/src/features/Conversation/Messages/Tasks/shared/utils.ts
index 361077feb53..58c7b8f3d01 100644
--- a/src/features/Conversation/Messages/Tasks/shared/utils.ts
+++ b/src/features/Conversation/Messages/Tasks/shared/utils.ts
@@ -1,4 +1,9 @@
-import { type TaskCurrentActivity, ThreadStatus } from '@/types/index';
+import {
+ type AssistantContentBlock,
+ type ModelUsage,
+ type TaskCurrentActivity,
+ ThreadStatus,
+} from '@lobechat/types';
/**
* Format duration in milliseconds to human-readable string
@@ -68,3 +73,19 @@ export const isProcessingStatus = (status?: ThreadStatus): boolean => {
status === ThreadStatus.Todo
);
};
+
+/**
+ * Accumulate usage from all blocks
+ */
+export const accumulateUsage = (blocks: AssistantContentBlock[]): ModelUsage => {
+ return blocks.reduce((acc, block) => {
+ const usage = block.usage;
+ if (!usage) return acc;
+ return {
+ cost: (acc.cost || 0) + (usage.cost || 0),
+ totalInputTokens: (acc.totalInputTokens || 0) + (usage.totalInputTokens || 0),
+ totalOutputTokens: (acc.totalOutputTokens || 0) + (usage.totalOutputTokens || 0),
+ totalTokens: (acc.totalTokens || 0) + (usage.totalTokens || 0),
+ };
+ }, {} as ModelUsage);
+};
diff --git a/src/features/Conversation/Messages/components/ContentLoading.tsx b/src/features/Conversation/Messages/components/ContentLoading.tsx
index 41ad882e441..765939a25d8 100644
--- a/src/features/Conversation/Messages/components/ContentLoading.tsx
+++ b/src/features/Conversation/Messages/components/ContentLoading.tsx
@@ -18,7 +18,7 @@ interface ContentLoadingProps {
const ContentLoading = memo<ContentLoadingProps>(({ id }) => {
const { t } = useTranslation('chat');
const runningOp = useChatStore(operationSelectors.getDeepestRunningOperationByMessage(id));
- console.log('runningOp', runningOp);
+
const [elapsedSeconds, setElapsedSeconds] = useState(0);
const [startTime, setStartTime] = useState(runningOp?.metadata?.startTime);
diff --git a/src/features/Conversation/components/Thinking/index.tsx b/src/features/Conversation/components/Thinking/index.tsx
index 927db3d8b24..5045275b36c 100644
--- a/src/features/Conversation/components/Thinking/index.tsx
+++ b/src/features/Conversation/components/Thinking/index.tsx
@@ -6,11 +6,11 @@ import {
type RefObject,
memo,
useEffect,
- useRef,
useState,
} from 'react';
import MarkdownMessage from '@/features/Conversation/Markdown';
+import { useAutoScroll } from '@/hooks/useAutoScroll';
import { type ChatCitationItem } from '@/types/index';
import Title from './Title';
@@ -40,39 +40,17 @@ interface ThinkingProps {
const Thinking = memo<ThinkingProps>((props) => {
const { content, duration, thinking, citations, thinkingAnimated } = props;
const [showDetail, setShowDetail] = useState(false);
- const contentRef = useRef<HTMLDivElement | null>(null);
+
+ const { ref, handleScroll } = useAutoScroll<HTMLDivElement>({
+ deps: [content, showDetail],
+ enabled: thinking && showDetail,
+ threshold: 120,
+ });
useEffect(() => {
setShowDetail(!!thinking);
}, [thinking]);
- // 当内容变更且正在思考时,如果用户接近底部则自动滚动到底部
- useEffect(() => {
- if (!thinking || !showDetail) return;
- const container = contentRef.current;
- if (!container) return;
-
- // 仅当用户接近底部时才自动滚动,避免打断用户查看上方内容
- const distanceToBottom = container.scrollHeight - container.scrollTop - container.clientHeight;
- const isNearBottom = distanceToBottom < 120;
-
- if (isNearBottom) {
- requestAnimationFrame(() => {
- container.scrollTop = container.scrollHeight;
- });
- }
- }, [content, thinking, showDetail]);
-
- // 展开时滚动到底部,便于查看最新内容
- useEffect(() => {
- if (!showDetail) return;
- const container = contentRef.current;
- if (!container) return;
- requestAnimationFrame(() => {
- container.scrollTop = container.scrollHeight;
- });
- }, [showDetail]);
-
return (
<Accordion
expandedKeys={showDetail ? ['thinking'] : []}
@@ -88,7 +66,8 @@ const Thinking = memo<ThinkingProps>((props) => {
<ScrollShadow
className={styles.contentScroll}
offset={12}
- ref={contentRef as unknown as RefObject<HTMLDivElement>}
+ onScroll={handleScroll}
+ ref={ref as RefObject<HTMLDivElement>}
size={12}
>
{typeof content === 'string' ? (
diff --git a/src/features/Conversation/store/slices/data/action.ts b/src/features/Conversation/store/slices/data/action.ts
index 8fc1eea78cc..3c7adc0d178 100644
--- a/src/features/Conversation/store/slices/data/action.ts
+++ b/src/features/Conversation/store/slices/data/action.ts
@@ -106,12 +106,11 @@ export const dataSlice: StateCreator<
// Also skip fetch when topicId is null (new conversation state) - there's no server data,
// only local optimistic updates. Fetching would return empty array and overwrite local data.
const shouldFetch = !skipFetch && !!context.agentId && !!context.topicId;
+
return useClientDataSWRWithSync<UIChatMessage[]>(
shouldFetch ? ['CONVERSATION_FETCH_MESSAGES', context] : null,
- async () => {
- return messageService.getMessages(context);
- },
+ () => messageService.getMessages(context),
{
onData: (data) => {
if (!data) return;
diff --git a/src/features/NavPanel/components/BackButton.tsx b/src/features/NavPanel/components/BackButton.tsx
index 27701845432..e7d8b365e09 100644
--- a/src/features/NavPanel/components/BackButton.tsx
+++ b/src/features/NavPanel/components/BackButton.tsx
@@ -1,26 +1,23 @@
import { ActionIcon, type ActionIconProps } from '@lobehub/ui';
import { ChevronLeftIcon } from 'lucide-react';
import { memo } from 'react';
-import { useNavigate } from 'react-router-dom';
+import { Link } from 'react-router-dom';
import { DESKTOP_HEADER_ICON_SIZE } from '@/const/layoutTokens';
export const BACK_BUTTON_ID = 'lobe-back-button';
const BackButton = memo<ActionIconProps & { to?: string }>(({ to = '/', onClick, ...rest }) => {
- const navigate = useNavigate();
-
return (
- <ActionIcon
- icon={ChevronLeftIcon}
- id={BACK_BUTTON_ID}
- onClick={(e) => {
- navigate(to);
- onClick?.(e);
- }}
- size={DESKTOP_HEADER_ICON_SIZE}
- {...rest}
- />
+ // @ts-expect-error
+ <Link onClick={onClick} to={to}>
+ <ActionIcon
+ icon={ChevronLeftIcon}
+ id={BACK_BUTTON_ID}
+ size={DESKTOP_HEADER_ICON_SIZE}
+ {...rest}
+ />
+ </Link>
);
});
diff --git a/src/features/NavPanel/components/NavPanelDraggable.tsx b/src/features/NavPanel/components/NavPanelDraggable.tsx
index af0fcbf5cd7..1f03c9a28a5 100644
--- a/src/features/NavPanel/components/NavPanelDraggable.tsx
+++ b/src/features/NavPanel/components/NavPanelDraggable.tsx
@@ -13,6 +13,7 @@ import { systemStatusSelectors } from '@/store/global/selectors';
import { isMacOS } from '@/utils/platform';
import { useNavPanelSizeChangeHandler } from '../hooks/useNavPanel';
+import { BACK_BUTTON_ID } from './BackButton';
const motionVariants = {
animate: { opacity: 1, x: 0 },
@@ -76,6 +77,9 @@ const draggableStyles = createStaticStyles(({ css, cssVar }) => ({
opacity,
width 0.2s ${cssVar.motionEaseOut};
}
+ #${BACK_BUTTON_ID} {
+ width: 24px !important;
+ }
&:hover {
#${TOGGLE_BUTTON_ID} {
diff --git a/src/hooks/useAutoScroll.ts b/src/hooks/useAutoScroll.ts
new file mode 100644
index 00000000000..51e865d7180
--- /dev/null
+++ b/src/hooks/useAutoScroll.ts
@@ -0,0 +1,117 @@
+import { type RefObject, useCallback, useEffect, useRef, useState } from 'react';
+
+interface UseAutoScrollOptions {
+ /**
+ * Dependencies that trigger auto-scroll when changed
+ */
+ deps?: unknown[];
+ /**
+ * Whether auto-scroll is enabled (e.g., only when streaming/executing)
+ * @default true
+ */
+ enabled?: boolean;
+ /**
+ * Distance threshold from bottom to consider "near bottom" (in pixels)
+ * @default 20
+ */
+ threshold?: number;
+}
+
+interface UseAutoScrollReturn<T extends HTMLElement> {
+ /**
+ * Callback to handle scroll events, attach to onScroll
+ */
+ handleScroll: () => void;
+ /**
+ * Ref to attach to the scrollable container
+ */
+ ref: RefObject<T | null>;
+ /**
+ * Reset the scroll lock state (e.g., when new content starts)
+ */
+ resetScrollLock: () => void;
+ /**
+ * Whether user has scrolled away from bottom (scroll lock active)
+ */
+ userHasScrolled: boolean;
+}
+
+/**
+ * Hook for auto-scrolling content with user scroll detection
+ *
+ * Features:
+ * - Auto-scrolls to bottom when dependencies change
+ * - Detects when user scrolls away from bottom and stops auto-scrolling
+ * - Provides reset function for when new content starts
+ * - Ignores scroll events triggered by auto-scroll itself
+ *
+ * @example
+ * ```tsx
+ * const { ref, handleScroll } = useAutoScroll<HTMLDivElement>({
+ * deps: [content],
+ * enabled: isStreaming,
+ * });
+ *
+ * return (
+ * <ScrollShadow ref={ref} onScroll={handleScroll}>
+ * {content}
+ * </ScrollShadow>
+ * );
+ * ```
+ */
+export function useAutoScroll<T extends HTMLElement = HTMLDivElement>(
+ options: UseAutoScrollOptions = {},
+): UseAutoScrollReturn<T> {
+ const { deps = [], enabled = true, threshold = 20 } = options;
+
+ const ref = useRef<T | null>(null);
+ const [userHasScrolled, setUserHasScrolled] = useState(false);
+ const isAutoScrollingRef = useRef(false);
+
+ // Handle user scroll detection
+ const handleScroll = useCallback(() => {
+ // Ignore scroll events triggered by auto-scroll
+ if (isAutoScrollingRef.current) return;
+
+ const container = ref.current;
+ if (!container) return;
+
+ // Check if user scrolled away from bottom
+ const distanceToBottom = container.scrollHeight - container.scrollTop - container.clientHeight;
+ const isAtBottom = distanceToBottom < threshold;
+
+ // If user scrolled up, stop auto-scrolling
+ if (!isAtBottom) {
+ setUserHasScrolled(true);
+ }
+ }, [threshold]);
+
+ // Reset scroll lock state
+ const resetScrollLock = useCallback(() => {
+ setUserHasScrolled(false);
+ }, []);
+
+ // Auto scroll to bottom when deps change (unless user has scrolled or disabled)
+ useEffect(() => {
+ if (!enabled || userHasScrolled) return;
+
+ const container = ref.current;
+ if (!container) return;
+
+ isAutoScrollingRef.current = true;
+ requestAnimationFrame(() => {
+ container.scrollTop = container.scrollHeight;
+ // Reset the flag after scroll completes
+ requestAnimationFrame(() => {
+ isAutoScrollingRef.current = false;
+ });
+ });
+ }, [enabled, userHasScrolled, ...deps]);
+
+ return {
+ handleScroll,
+ ref,
+ resetScrollLock,
+ userHasScrolled,
+ };
+}
diff --git a/src/locales/default/chat.ts b/src/locales/default/chat.ts
index bfdb5a54a99..6b3689e12b1 100644
--- a/src/locales/default/chat.ts
+++ b/src/locales/default/chat.ts
@@ -230,6 +230,7 @@ export default {
'noSelectedAgents': 'No members selected yet',
'openInNewWindow': 'Open in New Window',
'operation.execAgentRuntime': 'Preparing response',
+ 'operation.execClientTask': 'Executing task',
'operation.sendMessage': 'Sending message',
'owner': 'Group owner',
'pageCopilot.title': 'Page Agent',
@@ -354,13 +355,17 @@ export default {
'tab.profile': 'Agent Profile',
'tab.search': 'Search',
'task.activity.calling': 'Calling Skill...',
+ 'task.activity.clientExecuting': 'Executing locally...',
'task.activity.generating': 'Generating response...',
'task.activity.gotResult': 'Tool result received',
'task.activity.toolCalling': 'Calling {{toolName}}...',
'task.activity.toolResult': '{{toolName}} result received',
'task.batchTasks': '{{count}} Batch Subtasks',
+ 'task.instruction': 'Task Instruction',
+ 'task.intermediateSteps': '{{count}} intermediate steps',
+ 'task.metrics.duration': '(took {{duration}})',
'task.metrics.stepsShort': 'steps',
- 'task.metrics.toolCallsShort': 'tool uses',
+ 'task.metrics.toolCallsShort': 'skill uses',
'task.status.cancelled': 'Task Cancelled',
'task.status.failed': 'Task Failed',
'task.status.initializing': 'Initializing task...',
diff --git a/src/server/routers/lambda/aiAgent.ts b/src/server/routers/lambda/aiAgent.ts
index 00101bb73e3..a495df32699 100644
--- a/src/server/routers/lambda/aiAgent.ts
+++ b/src/server/routers/lambda/aiAgent.ts
@@ -1,5 +1,10 @@
import { type AgentRuntimeContext } from '@lobechat/agent-runtime';
-import { type TaskCurrentActivity, type TaskStatusResult, ThreadStatus } from '@lobechat/types';
+import {
+ type TaskCurrentActivity,
+ type TaskStatusResult,
+ ThreadStatus,
+ ThreadType,
+} from '@lobechat/types';
import { TRPCError } from '@trpc/server';
import debug from 'debug';
import pMap from 'p-map';
@@ -154,6 +159,49 @@ const ExecSubAgentTaskSchema = z.object({
topicId: z.string(),
});
+/**
+ * Schema for createClientTaskThread - create Thread for client-side task execution
+ * This is used when runInClient=true on desktop client
+ */
+const CreateClientTaskThreadSchema = z.object({
+ /** The Agent ID to execute the task */
+ agentId: z.string(),
+ /** The Group ID (optional, only for Group mode) */
+ groupId: z.string().optional(),
+ /** Initial user message content (task instruction) */
+ instruction: z.string(),
+ /** The parent message ID (task message) */
+ parentMessageId: z.string(),
+ /** Task title (shown in UI, used as thread title) */
+ title: z.string().optional(),
+ /** The Topic ID */
+ topicId: z.string(),
+});
+
+/**
+ * Schema for updateClientTaskThreadStatus - update Thread status after client-side execution
+ */
+const UpdateClientTaskThreadStatusSchema = z.object({
+ /** Completion reason */
+ completionReason: z.enum(['done', 'error', 'interrupted']),
+ /** Error message if failed */
+ error: z.string().optional(),
+ /** Thread metadata to update */
+ metadata: z
+ .object({
+ totalCost: z.number().optional(),
+ totalMessages: z.number().optional(),
+ totalSteps: z.number().optional(),
+ totalTokens: z.number().optional(),
+ totalToolCalls: z.number().optional(),
+ })
+ .optional(),
+ /** Result content (last assistant message) */
+ resultContent: z.string().optional(),
+ /** The Thread ID */
+ threadId: z.string(),
+});
+
/**
* Schema for interruptTask - interrupt a running task
*/
@@ -184,6 +232,100 @@ const aiAgentProcedure = authedProcedure.use(serverDatabase).use(async (opts) =>
});
export const aiAgentRouter = router({
+ /**
+ * Create Thread for client-side task execution
+ *
+ * This endpoint is called by desktop client when runInClient=true.
+ * It creates the Thread but does NOT execute the task - execution happens on client side.
+ */
+ createClientTaskThread: aiAgentProcedure
+ .input(CreateClientTaskThreadSchema)
+ .mutation(async ({ input, ctx }) => {
+ const { agentId, groupId, instruction, parentMessageId, title, topicId } = input;
+
+ log('createClientTaskThread: agentId=%s, groupId=%s', agentId, groupId);
+
+ try {
+ // 1. Create Thread for isolated task execution
+ const startedAt = new Date().toISOString();
+ const thread = await ctx.threadModel.create({
+ agentId,
+ groupId,
+ metadata: { clientMode: true, startedAt },
+ sourceMessageId: parentMessageId,
+ status: ThreadStatus.Processing,
+ title,
+ topicId,
+ type: ThreadType.Isolation,
+ });
+
+ if (!thread) {
+ throw new TRPCError({
+ code: 'INTERNAL_SERVER_ERROR',
+ message: 'Failed to create thread for task execution',
+ });
+ }
+
+ log('createClientTaskThread: created thread %s', thread.id);
+
+ // 2. Create initial user message (persisted to database)
+ const userMessage = await ctx.messageModel.create({
+ agentId,
+ content: instruction,
+ parentId: parentMessageId,
+ role: 'user',
+ threadId: thread.id,
+ topicId,
+ });
+
+ log('createClientTaskThread: created user message %s', userMessage.id);
+
+ // 3. Query thread messages and main chat messages in parallel
+ const [threadMessages, messages] = await Promise.all([
+ // Thread messages (messages within this thread)
+ ctx.messageModel.query({
+ agentId,
+ threadId: thread.id,
+ topicId,
+ }),
+ // Main chat messages (messages without threadId, includes updated taskDetail)
+ ctx.messageModel.query({
+ agentId,
+ topicId,
+ // No threadId - matchThread will filter for threadId IS NULL (main chat)
+ }),
+ ]);
+
+ log(
+ 'createClientTaskThread: queried %d thread messages, %d main messages',
+ threadMessages.length,
+ messages.length,
+ );
+
+ // 4. Return Thread, userMessageId, threadMessages and messages
+ return {
+ messages,
+ startedAt,
+ success: true,
+ threadId: thread.id,
+ threadMessages,
+ userMessageId: userMessage.id,
+ };
+ } catch (error: any) {
+ log('createClientTaskThread failed: %O', error);
+
+ if (error instanceof TRPCError) {
+ throw error;
+ }
+
+ throw new TRPCError({
+ cause: error,
+ code: 'INTERNAL_SERVER_ERROR',
+ message: `Failed to create client task thread: ${error.message}`,
+ });
+ }
+ }),
+
createOperation: aiAgentProcedure
.input(CreateAgentOperationSchema)
.mutation(async ({ input, ctx }) => {
@@ -846,4 +988,100 @@ export const aiAgentRouter = router({
timestamp: new Date().toISOString(),
};
}),
+
+ /**
+ * Update Thread status after client-side task execution completes
+ *
+ * This endpoint is called by desktop client after task execution finishes.
+ * It updates the Thread status and metadata similar to server-side completion.
+ */
+ updateClientTaskThreadStatus: aiAgentProcedure
+ .input(UpdateClientTaskThreadStatusSchema)
+ .mutation(async ({ input, ctx }) => {
+ const { threadId, completionReason, error, resultContent, metadata } = input;
+
+ log('updateClientTaskThreadStatus: threadId=%s, reason=%s', threadId, completionReason);
+
+ try {
+ // Find thread
+ const thread = await ctx.threadModel.findById(threadId);
+ if (!thread) {
+ throw new TRPCError({
+ code: 'NOT_FOUND',
+ message: 'Thread not found',
+ });
+ }
+
+ const completedAt = new Date().toISOString();
+ const startedAt = thread.metadata?.startedAt;
+ const duration = startedAt ? Date.now() - new Date(startedAt).getTime() : undefined;
+
+ // Determine thread status based on completion reason
+ let status: ThreadStatus;
+ switch (completionReason) {
+ case 'done': {
+ status = ThreadStatus.Completed;
+ break;
+ }
+ case 'error': {
+ status = ThreadStatus.Failed;
+ break;
+ }
+ case 'interrupted': {
+ status = ThreadStatus.Cancel;
+ break;
+ }
+ default: {
+ status = ThreadStatus.Completed;
+ }
+ }
+
+ // Update Thread metadata and status
+ await ctx.threadModel.update(threadId, {
+ metadata: {
+ ...thread.metadata,
+ completedAt,
+ duration,
+ error: error || undefined,
+ totalCost: metadata?.totalCost,
+ totalMessages: metadata?.totalMessages,
+ totalSteps: metadata?.totalSteps,
+ totalTokens: metadata?.totalTokens,
+ totalToolCalls: metadata?.totalToolCalls,
+ },
+ status,
+ });
+
+ // Update task message (sourceMessageId) with result content if provided
+ if (resultContent && thread.sourceMessageId) {
+ await ctx.messageModel.update(thread.sourceMessageId, {
+ content: resultContent,
+ });
+ log(
+ 'updateClientTaskThreadStatus: updated task message %s with result',
+ thread.sourceMessageId,
+ );
+ }
+
+ log('updateClientTaskThreadStatus: thread %s completed with status %s', threadId, status);
+
+ return {
+ status,
+ success: true,
+ threadId,
+ };
+ } catch (error: any) {
+ log('updateClientTaskThreadStatus failed: %O', error);
+
+ if (error instanceof TRPCError) {
+ throw error;
+ }
+
+ throw new TRPCError({
+ cause: error,
+ code: 'INTERNAL_SERVER_ERROR',
+ message: `Failed to update client task thread status: ${error.message}`,
+ });
+ }
+ }),
});
diff --git a/src/server/routers/lambda/thread.ts b/src/server/routers/lambda/thread.ts
index c40c281b570..9353faf0764 100644
--- a/src/server/routers/lambda/thread.ts
+++ b/src/server/routers/lambda/thread.ts
@@ -21,6 +21,7 @@ const threadProcedure = authedProcedure.use(serverDatabase).use(async (opts) =>
export const threadRouter = router({
createThread: threadProcedure.input(createThreadSchema).mutation(async ({ input, ctx }) => {
const thread = await ctx.threadModel.create({
+ metadata: input.metadata,
parentThreadId: input.parentThreadId,
sourceMessageId: input.sourceMessageId,
title: input.title,
@@ -38,6 +39,7 @@ export const threadRouter = router({
)
.mutation(async ({ input, ctx }) => {
const thread = await ctx.threadModel.create({
+ metadata: input.metadata,
parentThreadId: input.parentThreadId,
sourceMessageId: input.sourceMessageId,
title: input.message.content.slice(0, 20),
diff --git a/src/server/services/message/__tests__/index.test.ts b/src/server/services/message/__tests__/index.test.ts
index 35e09af6354..e2eb0ede322 100644
--- a/src/server/services/message/__tests__/index.test.ts
+++ b/src/server/services/message/__tests__/index.test.ts
@@ -293,6 +293,7 @@ describe('MessageService', () => {
current: 0,
groupId: undefined,
pageSize: 9999,
+ threadId: undefined,
topicId: undefined,
},
expect.objectContaining({
@@ -327,6 +328,42 @@ describe('MessageService', () => {
current: 0,
groupId: 'group-1',
pageSize: 9999,
+ threadId: undefined,
+ topicId: 'topic-1',
+ },
+ expect.objectContaining({
+ postProcessUrl: expect.any(Function),
+ }),
+ );
+ expect(result.id).toBe('msg-1');
+ expect(result.messages).toEqual(mockMessages);
+ });
+
+ it('should create message with threadId and query thread messages', async () => {
+ const params = {
+ agentId: 'agent-1',
+ content: 'Hello in thread',
+ groupId: 'group-1',
+ role: 'user' as const,
+ threadId: 'thread-1',
+ topicId: 'topic-1',
+ };
+ const createdMessage = { id: 'msg-1', ...params };
+ const mockMessages = [createdMessage];
+
+ vi.mocked(mockMessageModel.create).mockResolvedValue(createdMessage as any);
+ vi.mocked(mockMessageModel.query).mockResolvedValue(mockMessages as any);
+
+ const result = await messageService.createMessage(params as any);
+
+ expect(mockMessageModel.create).toHaveBeenCalledWith(params);
+ expect(mockMessageModel.query).toHaveBeenCalledWith(
+ {
+ agentId: 'agent-1',
+ current: 0,
+ groupId: 'group-1',
+ pageSize: 9999,
+ threadId: 'thread-1',
topicId: 'topic-1',
},
expect.objectContaining({
diff --git a/src/server/services/message/index.ts b/src/server/services/message/index.ts
index 2ee67fbdc12..2a5159641ab 100644
--- a/src/server/services/message/index.ts
+++ b/src/server/services/message/index.ts
@@ -1,5 +1,9 @@
import { type LobeChatDatabase } from '@lobechat/database';
-import { type CreateMessageParams, type UIChatMessage, type UpdateMessageParams } from '@lobechat/types';
+import {
+ type CreateMessageParams,
+ type UIChatMessage,
+ type UpdateMessageParams,
+} from '@lobechat/types';
import { MessageModel } from '@/database/models/message';
@@ -95,6 +99,7 @@ export class MessageService {
current: 0,
groupId: params.groupId,
pageSize: 9999,
+ threadId: params.threadId,
topicId: params.topicId,
},
{
diff --git a/src/services/aiAgent.ts b/src/services/aiAgent.ts
index 9a8bb72a532..f295588b774 100644
--- a/src/services/aiAgent.ts
+++ b/src/services/aiAgent.ts
@@ -40,6 +40,38 @@ export interface InterruptTaskParams {
threadId?: string;
}
+/**
+ * Parameters for createClientTaskThread
+ * Creates a Thread for client-side task execution (desktop only)
+ */
+export interface CreateClientTaskThreadParams {
+ agentId: string;
+ groupId?: string;
+ /** Initial user message content (task instruction) */
+ instruction: string;
+ parentMessageId: string;
+ title?: string;
+ topicId: string;
+}
+
+/**
+ * Parameters for updateClientTaskThreadStatus
+ * Updates Thread status after client-side execution completes
+ */
+export interface UpdateClientTaskThreadStatusParams {
+ completionReason: 'done' | 'error' | 'interrupted';
+ error?: string;
+ metadata?: {
+ totalCost?: number;
+ totalMessages?: number;
+ totalSteps?: number;
+ totalTokens?: number;
+ totalToolCalls?: number;
+ };
+ resultContent?: string;
+ threadId: string;
+}
+
class AiAgentService {
/**
* Execute a single Agent task
@@ -72,6 +104,25 @@ class AiAgentService {
async interruptTask(params: InterruptTaskParams) {
return await lambdaClient.aiAgent.interruptTask.mutate(params);
}
+
+ /**
+ * Create Thread for client-side task execution (desktop only)
+ *
+ * This method is called when runInClient=true on desktop client.
+ * It creates the Thread but does NOT execute the task - execution happens locally.
+ */
+ async createClientTaskThread(params: CreateClientTaskThreadParams) {
+ return await lambdaClient.aiAgent.createClientTaskThread.mutate(params);
+ }
+
+ /**
+ * Update Thread status after client-side task execution completes
+ *
+ * This method is called by desktop client after task execution finishes.
+ */
+ async updateClientTaskThreadStatus(params: UpdateClientTaskThreadStatusParams) {
+ return await lambdaClient.aiAgent.updateClientTaskThreadStatus.mutate(params);
+ }
}
export const aiAgentService = new AiAgentService();
diff --git a/src/store/chat/agents/createAgentExecutors.ts b/src/store/chat/agents/createAgentExecutors.ts
index 519fb1bb0bb..0bebdfd8491 100644
--- a/src/store/chat/agents/createAgentExecutors.ts
+++ b/src/store/chat/agents/createAgentExecutors.ts
@@ -3,6 +3,8 @@ import {
type AgentInstruction,
type AgentInstructionCallLlm,
type AgentInstructionCallTool,
+ type AgentInstructionExecClientTask,
+ type AgentInstructionExecClientTasks,
type AgentInstructionExecTask,
type AgentInstructionExecTasks,
type AgentRuntimeContext,
@@ -15,13 +17,17 @@ import {
type TasksBatchResultPayload,
UsageCounter,
} from '@lobechat/agent-runtime';
-import type { ChatToolPayload, CreateMessageParams } from '@lobechat/types';
+import { isDesktop } from '@lobechat/const';
+import type { ChatToolPayload, ConversationContext, CreateMessageParams } from '@lobechat/types';
import debug from 'debug';
import pMap from 'p-map';
import { LOADING_FLAT } from '@/const/message';
import { aiAgentService } from '@/services/aiAgent';
+import { agentByIdSelectors } from '@/store/agent/selectors';
+import { getAgentStoreState } from '@/store/agent/store';
import type { ChatStore } from '@/store/chat/store';
+import { messageMapKey } from '@/store/chat/utils/messageMapKey';
import { sleep } from '@/utils/sleep';
const log = debug('lobe-store:agent-executors');
@@ -571,7 +577,9 @@ export const createAgentExecutors = (context: {
const stateType = result.state?.type;
// GTD async tasks need to be passed to Agent for exec_task/exec_tasks instruction
- if (stateType === 'execTask' || stateType === 'execTasks') {
+ // Includes both server-side (execTask/execTasks) and client-side (execClientTask/execClientTasks)
+ const execTaskStateTypes = ['execTask', 'execTasks', 'execClientTask', 'execClientTasks'];
+ if (execTaskStateTypes.includes(stateType)) {
log(
'[%s][call_tool] Detected %s state, passing to Agent for decision',
sessionLogId,
@@ -955,7 +963,8 @@ export const createAgentExecutors = (context: {
const taskMessageId = taskMessageResult.id;
log('[%s] Created task message: %s', taskLogId, taskMessageId);
- // 2. Create task via backend API
+ // 2. Create and execute task on server
+ log('[%s] Using server-side execution', taskLogId);
const createResult = await aiAgentService.execSubAgentTask({
agentId,
instruction: task.instruction,
@@ -1006,10 +1015,29 @@ export const createAgentExecutors = (context: {
const startTime = Date.now();
while (Date.now() - startTime < maxWait) {
- // Check if operation has been cancelled
+ // Check if parent operation has been cancelled
const currentOperation = context.get().operations[state.operationId];
if (currentOperation?.status === 'cancelled') {
log('[%s] Operation cancelled, stopping polling', taskLogId);
+
+ // Send interrupt request to stop the server-side task
+ try {
+ await aiAgentService.interruptTask({ threadId: createResult.threadId });
+ log('[%s] Sent interrupt request for cancelled task', taskLogId);
+ } catch (err) {
+ log('[%s] Failed to interrupt cancelled task: %O', taskLogId, err);
+ }
+
+ // Update task message to cancelled state
+ await context
+ .get()
+ .optimisticUpdateMessageContent(
+ taskMessageId,
+ 'Task was cancelled by user.',
+ undefined,
+ { operationId: state.operationId },
+ );
+
const updatedMessages = context.get().dbMessagesMap[context.messageKey] || [];
return {
events,
@@ -1125,6 +1153,8 @@ export const createAgentExecutors = (context: {
if (status.status === 'cancel') {
log('[%s] Task was cancelled', taskLogId);
+ // Note: Don't fail the operation here - it was cancelled intentionally
+ // The cancel handler already updated the message
await context
.get()
.optimisticUpdateMessageContent(taskMessageId, 'Task was cancelled', undefined, {
@@ -1161,6 +1191,15 @@ export const createAgentExecutors = (context: {
// Timeout reached
log('[%s] Task timeout after %dms', taskLogId, maxWait);
+
+ // Try to interrupt the task that timed out
+ try {
+ await aiAgentService.interruptTask({ threadId: createResult.threadId });
+ log('[%s] Sent interrupt request for timed out task', taskLogId);
+ } catch (err) {
+ log('[%s] Failed to interrupt timed out task: %O', taskLogId, err);
+ }
+
await context
.get()
.optimisticUpdateMessageContent(
@@ -1303,7 +1342,8 @@ export const createAgentExecutors = (context: {
const taskMessageId = taskMessageResult.id;
log('[%s] Created task message: %s', taskLogId, taskMessageId);
- // 2. Create task via backend API (no groupId for single agent mode)
+ // 2. Create and execute task on server
+ log('[%s] Using server-side execution', taskLogId);
const createResult = await aiAgentService.execSubAgentTask({
agentId,
instruction: task.instruction,
@@ -1333,16 +1373,35 @@ export const createAgentExecutors = (context: {
log('[%s] Task created with threadId: %s', taskLogId, createResult.threadId);
- // 3. Poll for task completion
+ // 4. Poll for task completion
const pollInterval = 3000; // 3 seconds
const maxWait = task.timeout || 1_800_000; // Default 30 minutes
const startTime = Date.now();
while (Date.now() - startTime < maxWait) {
- // Check if operation has been cancelled
+ // Check if parent operation has been cancelled
const currentOperation = context.get().operations[state.operationId];
if (currentOperation?.status === 'cancelled') {
log('[%s] Operation cancelled, stopping polling', taskLogId);
+
+ // Send interrupt request to stop the server-side task
+ try {
+ await aiAgentService.interruptTask({ threadId: createResult.threadId });
+ log('[%s] Sent interrupt request for cancelled task', taskLogId);
+ } catch (err) {
+ log('[%s] Failed to interrupt cancelled task: %O', taskLogId, err);
+ }
+
+ // Update task message to cancelled state
+ await context
+ .get()
+ .optimisticUpdateMessageContent(
+ taskMessageId,
+ 'Task was cancelled by user.',
+ undefined,
+ { operationId: state.operationId },
+ );
+
return {
error: 'Operation cancelled',
success: false,
@@ -1370,7 +1429,7 @@ export const createAgentExecutors = (context: {
if (status.status === 'completed') {
log('[%s] Task completed successfully', taskLogId);
- // 4. Update task message with result
+ // 5. Update task message with result
if (status.result) {
await context
.get()
@@ -1387,13 +1446,14 @@ export const createAgentExecutors = (context: {
}
if (status.status === 'failed') {
- log('[%s] Task failed: %s', taskLogId, status.error);
+ const errorMessage = status.error || 'Unknown error';
+ log('[%s] Task failed: %s', taskLogId, errorMessage);
// Update task message with error
await context
.get()
.optimisticUpdateMessageContent(
taskMessageId,
- `Task failed: ${status.error}`,
+ `Task failed: ${errorMessage}`,
undefined,
{ operationId: state.operationId },
);
@@ -1407,7 +1467,8 @@ export const createAgentExecutors = (context: {
if (status.status === 'cancel') {
log('[%s] Task was cancelled', taskLogId);
- // Update task message with cancelled status
+ // Note: Don't fail the operation here - it was cancelled intentionally
+ // The cancel handler already updated the message
await context
.get()
.optimisticUpdateMessageContent(taskMessageId, 'Task was cancelled', undefined, {
@@ -1427,6 +1488,15 @@ export const createAgentExecutors = (context: {
// Timeout reached
log('[%s] Task timeout after %dms', taskLogId, maxWait);
+
+ // Try to interrupt the task that timed out
+ try {
+ await aiAgentService.interruptTask({ threadId: createResult.threadId });
+ log('[%s] Sent interrupt request for timed out task', taskLogId);
+ } catch (err) {
+ log('[%s] Failed to interrupt timed out task: %O', taskLogId, err);
+ }
+
// Update task message with timeout error
await context
.get()
@@ -1453,7 +1523,7 @@ export const createAgentExecutors = (context: {
};
}
},
- { concurrency: 5 }, // Limit concurrent tasks
+ { concurrency: 15 }, // Limit concurrent tasks
);
log('[%s][exec_tasks] All tasks completed, results: %O', sessionLogId, results);
@@ -1481,6 +1551,638 @@ export const createAgentExecutors = (context: {
} as AgentRuntimeContext,
};
},
+
+ /**
+ * exec_client_task executor
+ * Executes a single async task on the client side (desktop only)
+ * Used when task requires local tools like file system or shell commands
+ *
+ * Flow:
+ * 1. Create a task message (role: 'task') as placeholder
+ * 2. Create Thread via API (for isolation)
+ * 3. Execute using internal_execAgentRuntime (client-side)
+ * 4. Update Thread status via API on completion
+ * 5. Update task message content with result
+ * 6. Return task_result phase with result
+ */
+ exec_client_task: async (instruction, state) => {
+ const { parentMessageId, task } = (instruction as AgentInstructionExecClientTask).payload;
+
+ const events: AgentEvent[] = [];
+ const sessionLogId = `${state.operationId}:${state.stepCount}`;
+
+ log(
+ '[%s][exec_client_task] Starting client-side execution of task: %s',
+ sessionLogId,
+ task.description,
+ );
+
+ // Check if we're on desktop - if not, this executor shouldn't have been called
+ if (!isDesktop) {
+ log(
+ '[%s][exec_client_task] ERROR: Not on desktop, cannot execute client-side task',
+ sessionLogId,
+ );
+ return {
+ events,
+ newState: state,
+ nextContext: {
+ payload: {
+ parentMessageId,
+ result: {
+ error: 'Client-side task execution is only available on desktop',
+ success: false,
+ taskMessageId: '',
+ threadId: '',
+ },
+ } as TaskResultPayload,
+ phase: 'task_result',
+ session: {
+ messageCount: state.messages.length,
+ sessionId: state.operationId,
+ status: 'running',
+ stepCount: state.stepCount + 1,
+ },
+ } as AgentRuntimeContext,
+ };
+ }
+
+ // Get context from operation
+ const opContext = getOperationContext();
+ const { agentId, topicId } = opContext;
+
+ if (!agentId || !topicId) {
+ log('[%s][exec_client_task] No valid context, cannot execute task', sessionLogId);
+ return {
+ events,
+ newState: state,
+ nextContext: {
+ payload: {
+ parentMessageId,
+ result: {
+ error: 'No valid context available',
+ success: false,
+ taskMessageId: '',
+ threadId: '',
+ },
+ } as TaskResultPayload,
+ phase: 'task_result',
+ session: {
+ messageCount: state.messages.length,
+ sessionId: state.operationId,
+ status: 'running',
+ stepCount: state.stepCount + 1,
+ },
+ } as AgentRuntimeContext,
+ };
+ }
+
+ const taskLogId = `${sessionLogId}:client-task`;
+
+ // Get agent's model and provider configuration
+ const agentState = getAgentStoreState();
+ const taskModel = agentByIdSelectors.getAgentModelById(agentId)(agentState);
+ const taskProvider = agentByIdSelectors.getAgentModelProviderById(agentId)(agentState);
+
+ try {
+ // 1. Create task message as placeholder with model/provider
+ const taskMessageResult = await context.get().optimisticCreateMessage(
+ {
+ agentId,
+ content: '',
+ metadata: { instruction: task.instruction, taskTitle: task.description },
+ model: taskModel,
+ parentId: parentMessageId,
+ provider: taskProvider,
+ role: 'task',
+ topicId,
+ },
+ { operationId: state.operationId },
+ );
+
+ if (!taskMessageResult) {
+ log('[%s] Failed to create task message', taskLogId);
+ return {
+ events,
+ newState: state,
+ nextContext: {
+ payload: {
+ parentMessageId,
+ result: {
+ error: 'Failed to create task message',
+ success: false,
+ taskMessageId: '',
+ threadId: '',
+ },
+ } as TaskResultPayload,
+ phase: 'task_result',
+ session: {
+ messageCount: state.messages.length,
+ sessionId: state.operationId,
+ status: 'running',
+ stepCount: state.stepCount + 1,
+ },
+ } as AgentRuntimeContext,
+ };
+ }
+
+ const taskMessageId = taskMessageResult.id;
+ log('[%s][exec_client_task] Created task message: %s', taskLogId, taskMessageId);
+
+ // 2. Create Thread via API first (to get threadId for operation context)
+ const threadResult = await aiAgentService.createClientTaskThread({
+ agentId,
+ instruction: task.instruction,
+ parentMessageId: taskMessageId,
+ title: task.description,
+ topicId,
+ });
+
+ if (!threadResult.success) {
+ log('[%s][exec_client_task] Failed to create client task thread', taskLogId);
+ await context
+ .get()
+ .optimisticUpdateMessageContent(
+ taskMessageId,
+ 'Failed to create task thread',
+ undefined,
+ { operationId: state.operationId },
+ );
+ return {
+ events,
+ newState: state,
+ nextContext: {
+ payload: {
+ parentMessageId,
+ result: {
+ error: 'Failed to create client task thread',
+ success: false,
+ taskMessageId,
+ threadId: '',
+ },
+ } as TaskResultPayload,
+ phase: 'task_result',
+ session: {
+ messageCount: state.messages.length,
+ sessionId: state.operationId,
+ status: 'running',
+ stepCount: state.stepCount + 1,
+ },
+ } as AgentRuntimeContext,
+ };
+ }
+
+ const { threadId, userMessageId, threadMessages, messages } = threadResult;
+
+ // 3. Build sub-task ConversationContext (uses threadId for isolation)
+ const subContext: ConversationContext = { agentId, topicId, threadId, scope: 'thread' };
+
+ // 4. Create a child operation for task execution (now with threadId)
+ const { operationId: taskOperationId } = context.get().startOperation({
+ type: 'execClientTask',
+ context: subContext,
+ parentOperationId: state.operationId,
+ metadata: {
+ startTime: Date.now(),
+ taskDescription: task.description,
+ taskMessageId,
+ executionMode: 'client',
+ },
+ });
+ log(
+ '[%s][exec_client_task] Created thread: %s, userMessageId: %s, threadMessages: %d',
+ taskLogId,
+ threadId,
+ userMessageId,
+ threadMessages.length,
+ );
+
+ // 5. Sync messages to store
+ // Update main chat messages with latest taskDetail status
+ context.get().replaceMessages(messages, { operationId: state.operationId });
+ // Update thread messages
+ context.get().replaceMessages(threadMessages, { context: subContext });
+
+ // 6. Use server-returned thread messages (already persisted)
+ let subMessages = [...threadMessages];
+
+ // Optionally inherit messages from parent conversation
+ if (task.inheritMessages) {
+ const parentMessages = state.messages.filter((m) => m.role !== 'task');
+ subMessages = [...parentMessages, ...subMessages];
+ // Re-sync with inherited messages
+ context.get().replaceMessages(subMessages, { context: subContext });
+ }
+
+ // 7. Execute using internal_execAgentRuntime (client-side with local tools access)
+ log('[%s][exec_client_task] Starting client-side AgentRuntime execution', taskLogId);
+
+ const runtimeResult = await context.get().internal_execAgentRuntime({
+ context: subContext,
+ messages: subMessages,
+ parentMessageId: userMessageId, // Use server-returned userMessageId
+ parentMessageType: 'user',
+ operationId: taskOperationId,
+ parentOperationId: state.operationId,
+ });
+
+ log('[%s][exec_client_task] Client-side AgentRuntime execution completed', taskLogId);
+
+ // 8. Get execution result from sub-task messages
+ const subMessageKey = messageMapKey(subContext);
+ const subTaskMessages = context.get().dbMessagesMap[subMessageKey] || [];
+ const lastAssistant = subTaskMessages.findLast((m) => m.role === 'assistant');
+ const resultContent = lastAssistant?.content || 'Task completed';
+
+ log(
+ '[%s][exec_client_task] Got result from sub-task: %d chars',
+ taskLogId,
+ resultContent.length,
+ );
+
+ // Count tool calls
+ const totalToolCalls = subTaskMessages.filter((m) => m.role === 'tool').length;
+
+ // Get usage data from runtime result
+ const { usage, cost } = runtimeResult || {};
+
+ log(
+ '[%s][exec_client_task] Runtime usage: tokens=%d, cost=%s, model=%s',
+ taskLogId,
+ usage?.llm?.tokens?.total,
+ cost?.total,
+ taskModel,
+ );
+
+ // 9. Update task message with result and usage (model/provider already set at creation)
+ await context.get().optimisticUpdateMessageContent(
+ taskMessageId,
+ resultContent,
+ {
+ metadata: {
+ cost: cost?.total,
+ duration: usage?.llm?.processingTimeMs,
+ totalInputTokens: usage?.llm?.tokens?.input,
+ totalOutputTokens: usage?.llm?.tokens?.output,
+ totalTokens: usage?.llm?.tokens?.total,
+ },
+ },
+ { operationId: state.operationId },
+ );
+
+ // 10. Update Thread status via API with metadata
+ await aiAgentService.updateClientTaskThreadStatus({
+ threadId,
+ completionReason: 'done',
+ resultContent,
+ metadata: {
+ totalCost: cost?.total,
+ totalMessages: subTaskMessages.length,
+ totalTokens: usage?.llm?.tokens?.total,
+ totalToolCalls,
+ },
+ });
+
+ // 11. Complete operation
+ context.get().completeOperation(taskOperationId);
+
+ // 12. Return success result
+ const updatedMessages = context.get().dbMessagesMap[context.messageKey] || [];
+ return {
+ events,
+ newState: { ...state, messages: updatedMessages },
+ nextContext: {
+ payload: {
+ // Use taskMessageId as parent so subsequent messages are created after the task
+ parentMessageId: taskMessageId,
+ result: {
+ result: resultContent,
+ success: true,
+ taskMessageId,
+ threadId,
+ },
+ } as TaskResultPayload,
+ phase: 'task_result',
+ session: {
+ messageCount: updatedMessages.length,
+ sessionId: state.operationId,
+ status: 'running',
+ stepCount: state.stepCount + 1,
+ },
+ } as AgentRuntimeContext,
+ };
+ } catch (error) {
+ log('[%s][exec_client_task] Error executing client task: %O', taskLogId, error);
+
+ // Update task message with error
+ // Note: taskMessageId may not exist if error occurred before message creation
+ const errorMessage = error instanceof Error ? error.message : 'Unknown error';
+
+ return {
+ events,
+ newState: state,
+ nextContext: {
+ payload: {
+ parentMessageId,
+ result: {
+ error: errorMessage,
+ success: false,
+ taskMessageId: '',
+ threadId: '',
+ },
+ } as TaskResultPayload,
+ phase: 'task_result',
+ session: {
+ messageCount: state.messages.length,
+ sessionId: state.operationId,
+ status: 'running',
+ stepCount: state.stepCount + 1,
+ },
+ } as AgentRuntimeContext,
+ };
+ }
+ },
+
+ /**
+ * exec_client_tasks executor
+ * Executes multiple async tasks on the client side in parallel (desktop only)
+ * Used when tasks require local tools like file system or shell commands
+ *
+ * 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)
+ * 4. Update Thread status via API on completion
+ * 5. Update task message content with result
+ * 6. Return tasks_batch_result phase with all results
+ */
+ exec_client_tasks: async (instruction, state) => {
+ const { parentMessageId, tasks } = (instruction as AgentInstructionExecClientTasks).payload;
+
+ const events: AgentEvent[] = [];
+ const sessionLogId = `${state.operationId}:${state.stepCount}`;
+
+ log(
+ '[%s][exec_client_tasks] Starting client-side execution of %d tasks',
+ sessionLogId,
+ tasks.length,
+ );
+
+ // Check if we're on desktop - if not, this executor shouldn't have been called
+ if (!isDesktop) {
+ log(
+ '[%s][exec_client_tasks] ERROR: Not on desktop, cannot execute client-side tasks',
+ sessionLogId,
+ );
+ return {
+ events,
+ newState: state,
+ nextContext: {
+ payload: {
+ parentMessageId,
+ results: tasks.map(() => ({
+ error: 'Client-side task execution is only available on desktop',
+ success: false,
+ taskMessageId: '',
+ threadId: '',
+ })),
+ } as TasksBatchResultPayload,
+ phase: 'tasks_batch_result',
+ session: {
+ messageCount: state.messages.length,
+ sessionId: state.operationId,
+ status: 'running',
+ stepCount: state.stepCount + 1,
+ },
+ } as AgentRuntimeContext,
+ };
+ }
+
+ // Get context from operation
+ const opContext = getOperationContext();
+ const { agentId, topicId } = opContext;
+
+ if (!agentId || !topicId) {
+ log('[%s][exec_client_tasks] No valid context, cannot execute tasks', sessionLogId);
+ return {
+ events,
+ newState: state,
+ nextContext: {
+ payload: {
+ parentMessageId,
+ results: tasks.map(() => ({
+ error: 'No valid context available',
+ success: false,
+ taskMessageId: '',
+ threadId: '',
+ })),
+ } as TasksBatchResultPayload,
+ phase: 'tasks_batch_result',
+ session: {
+ messageCount: state.messages.length,
+ sessionId: state.operationId,
+ status: 'running',
+ stepCount: state.stepCount + 1,
+ },
+ } as AgentRuntimeContext,
+ };
+ }
+
+ // Execute all tasks in parallel
+ const results = await pMap(
+ tasks,
+ async (task, taskIndex) => {
+ const taskLogId = `${sessionLogId}:client-task-${taskIndex}`;
+ log('[%s] Starting client task: %s', taskLogId, task.description);
+
+ try {
+ // 1. Create task message as placeholder
+ const taskMessageResult = await context.get().optimisticCreateMessage(
+ {
+ agentId,
+ content: '',
+ metadata: { instruction: task.instruction, taskTitle: task.description },
+ parentId: parentMessageId,
+ role: 'task',
+ topicId,
+ },
+ { operationId: state.operationId },
+ );
+
+ if (!taskMessageResult) {
+ log('[%s] Failed to create task message', taskLogId);
+ return {
+ error: 'Failed to create task message',
+ success: false,
+ taskMessageId: '',
+ threadId: '',
+ };
+ }
+
+ const taskMessageId = taskMessageResult.id;
+ log('[%s] Created task message: %s', taskLogId, taskMessageId);
+
+ // 2. Create Thread via API first (to get threadId for operation context)
+ const threadResult = await aiAgentService.createClientTaskThread({
+ agentId,
+ instruction: task.instruction,
+ parentMessageId: taskMessageId,
+ title: task.description,
+ topicId,
+ });
+
+ if (!threadResult.success) {
+ log('[%s] Failed to create client task thread', taskLogId);
+ await context
+ .get()
+ .optimisticUpdateMessageContent(
+ taskMessageId,
+ 'Failed to create task thread',
+ undefined,
+ { operationId: state.operationId },
+ );
+ return {
+ error: 'Failed to create client task thread',
+ success: false,
+ taskMessageId,
+ threadId: '',
+ };
+ }
+
+ const { threadId, userMessageId, threadMessages, messages } = threadResult;
+ log(
+ '[%s] Created thread: %s, userMessageId: %s, threadMessages: %d',
+ taskLogId,
+ threadId,
+ userMessageId,
+ threadMessages.length,
+ );
+
+ // 3. Build sub-task ConversationContext (uses threadId for isolation)
+ const subContext: ConversationContext = {
+ agentId,
+ topicId,
+ threadId,
+ scope: 'thread',
+ };
+
+ // 4. Create a child operation for task execution (now with threadId)
+ const { operationId: taskOperationId } = context.get().startOperation({
+ type: 'execClientTask',
+ context: subContext,
+ parentOperationId: state.operationId,
+ metadata: {
+ startTime: Date.now(),
+ taskDescription: task.description,
+ taskIndex,
+ taskMessageId,
+ executionMode: 'client',
+ },
+ });
+
+ // 5. Sync messages to store
+ // Update main chat messages with latest taskDetail status
+ context.get().replaceMessages(messages, { operationId: state.operationId });
+ // Update thread messages
+ context.get().replaceMessages(threadMessages, { context: subContext });
+
+ // 6. Use server-returned thread messages (already persisted)
+ let subMessages = [...threadMessages];
+
+ // Optionally inherit messages from parent conversation
+ if (task.inheritMessages) {
+ const parentMessages = state.messages.filter((m) => m.role !== 'task');
+ subMessages = [...parentMessages, ...subMessages];
+ // Re-sync with inherited messages
+ context.get().replaceMessages(subMessages, { context: subContext });
+ }
+
+ // 7. Execute using internal_execAgentRuntime (client-side with local tools access)
+ log('[%s] Starting client-side AgentRuntime execution', taskLogId);
+
+ await context.get().internal_execAgentRuntime({
+ context: subContext,
+ messages: subMessages,
+ parentMessageId: userMessageId, // Use server-returned userMessageId
+ parentMessageType: 'user',
+ operationId: taskOperationId,
+ parentOperationId: state.operationId,
+ });
+
+ log('[%s] Client-side AgentRuntime execution completed', taskLogId);
+
+ // 7. Get execution result from sub-task messages
+ const subMessageKey = messageMapKey(subContext);
+ const subTaskMessages = context.get().dbMessagesMap[subMessageKey] || [];
+ const lastAssistant = subTaskMessages.findLast((m) => m.role === 'assistant');
+ const resultContent = lastAssistant?.content || 'Task completed';
+
+ log('[%s] Got result from sub-task: %d chars', taskLogId, resultContent.length);
+
+ // 8. Update task message with result
+ await context
+ .get()
+ .optimisticUpdateMessageContent(taskMessageId, resultContent, undefined, {
+ operationId: state.operationId,
+ });
+
+ // 9. Update Thread status via API
+ await aiAgentService.updateClientTaskThreadStatus({
+ threadId,
+ completionReason: 'done',
+ resultContent,
+ });
+
+ // 10. Complete operation
+ context.get().completeOperation(taskOperationId);
+
+ return {
+ result: resultContent,
+ success: true,
+ taskMessageId,
+ threadId,
+ };
+ } catch (error) {
+ log('[%s] Error executing client task: %O', taskLogId, error);
+ return {
+ error: error instanceof Error ? error.message : 'Unknown error',
+ success: false,
+ taskMessageId: '',
+ threadId: '',
+ };
+ }
+ },
+ { concurrency: 15 },
+ );
+
+ log('[%s][exec_client_tasks] All tasks completed, results: %O', sessionLogId, results);
+
+ // Get latest messages from store
+ const updatedMessages = context.get().dbMessagesMap[context.messageKey] || [];
+ const newState = { ...state, messages: updatedMessages };
+
+ // Use the last successful task's message ID as parent for subsequent messages
+ const lastSuccessfulTaskId = results.findLast((r) => r.success)?.taskMessageId;
+
+ return {
+ events,
+ newState,
+ nextContext: {
+ payload: {
+ // Use last task message as parent so subsequent messages are created after the tasks
+ parentMessageId: lastSuccessfulTaskId || parentMessageId,
+ results,
+ } as TasksBatchResultPayload,
+ phase: 'tasks_batch_result',
+ session: {
+ messageCount: newState.messages.length,
+ sessionId: state.operationId,
+ status: 'running',
+ stepCount: state.stepCount + 1,
+ },
+ } as AgentRuntimeContext,
+ };
+ },
};
return executors;
diff --git a/src/store/chat/slices/aiChat/actions/streamingExecutor.ts b/src/store/chat/slices/aiChat/actions/streamingExecutor.ts
index 9276e72fa15..2d52727481f 100644
--- a/src/store/chat/slices/aiChat/actions/streamingExecutor.ts
+++ b/src/store/chat/slices/aiChat/actions/streamingExecutor.ts
@@ -4,7 +4,9 @@ import {
AgentRuntime,
type AgentRuntimeContext,
type AgentState,
+ type Cost,
GeneralChatAgent,
+ type Usage,
computeStepContext,
} from '@lobechat/agent-runtime';
import { PageAgentIdentifier } from '@lobechat/builtin-tool-page-agent';
@@ -130,7 +132,7 @@ export interface StreamingExecutorAction {
*/
parentOperationId?: string;
skipCreateFirstMessage?: boolean;
- }) => Promise<void>;
+ }) => Promise<{ cost?: Cost; usage?: Usage } | void>;
}
export const streamingExecutor: StateCreator<
@@ -875,5 +877,8 @@ export const streamingExecutor: StateCreator<
console.error('Desktop notification error:', error);
}
}
+
+ // Return usage and cost data for caller to use
+ return { cost: state.cost, usage: state.usage };
},
});
diff --git a/src/store/chat/slices/message/actions/query.ts b/src/store/chat/slices/message/actions/query.ts
index 4167f90a962..8aad3fd7b14 100644
--- a/src/store/chat/slices/message/actions/query.ts
+++ b/src/store/chat/slices/message/actions/query.ts
@@ -1,9 +1,11 @@
import { parse } from '@lobechat/conversation-flow';
import { type ConversationContext, type UIChatMessage } from '@lobechat/types';
import isEqual from 'fast-deep-equal';
+import { type SWRResponse } from 'swr';
import { type StateCreator } from 'zustand/vanilla';
-import { mutate } from '@/libs/swr';
+import { mutate, useClientDataSWRWithSync } from '@/libs/swr';
+import { messageService } from '@/services/message';
import { type ChatStore } from '@/store/chat/store';
import { type MessageMapKeyInput, messageMapKey } from '../../../utils/messageMapKey';
@@ -39,6 +41,18 @@ export interface MessageQueryAction {
operationId?: string;
},
) => void;
+
+ /**
+ * Fetch messages for a specific context using SWR
+ * Used for fetching thread messages or messages for a specific context
+ *
+ * @param context - Conversation context with agentId, topicId, threadId, etc.
+ * @param skipFetch - When true, SWR key is null and no fetch occurs
+ */
+ useFetchMessages: (
+ context: ConversationContext,
+ skipFetch?: boolean,
+ ) => SWRResponse<UIChatMessage[]>;
}
export const messageQuery: StateCreator<
@@ -111,4 +125,22 @@ export const messageQuery: StateCreator<
params?.action ?? 'replaceMessages',
);
},
+
+ useFetchMessages: (context, skipFetch) => {
+ // Skip fetch when skipFetch is true or required fields are missing
+ const shouldFetch = !skipFetch && !!context.agentId && !!context.topicId;
+
+ return useClientDataSWRWithSync<UIChatMessage[]>(
+ shouldFetch ? ['CHAT_STORE_FETCH_MESSAGES', context] : null,
+ () => messageService.getMessages(context),
+ {
+ onData: (data) => {
+ if (!data || !context.topicId) return;
+
+ // Use replaceMessages to store the fetched messages
+ get().replaceMessages(data, { action: 'useFetchMessages', context });
+ },
+ },
+ );
+ },
});
diff --git a/src/store/chat/slices/message/selectors/displayMessage.test.ts b/src/store/chat/slices/message/selectors/displayMessage.test.ts
index 39b3de7bf9f..be608c43b1f 100644
--- a/src/store/chat/slices/message/selectors/displayMessage.test.ts
+++ b/src/store/chat/slices/message/selectors/displayMessage.test.ts
@@ -347,6 +347,16 @@ describe('displayMessageSelectors', () => {
messageMapKey({ agentId: 'testId', groupId: 'groupId', topicId: 'topicId' }),
);
});
+
+ it('should generate correct key with activeThreadId for thread conversations', () => {
+ const state: Partial<ChatStore> = {
+ activeAgentId: 'testId',
+ activeThreadId: 'threadId',
+ activeTopicId: 'topicId',
+ };
+ const result = displayMessageSelectors.currentDisplayChatKey(state as ChatStore);
+ expect(result).toBe('thread_testId_topicId_threadId');
+ });
});
describe('activeDisplayMessages with group chat messages', () => {
diff --git a/src/store/chat/slices/message/selectors/displayMessage.ts b/src/store/chat/slices/message/selectors/displayMessage.ts
index 9fadce86875..f7eb741c3b5 100644
--- a/src/store/chat/slices/message/selectors/displayMessage.ts
+++ b/src/store/chat/slices/message/selectors/displayMessage.ts
@@ -30,6 +30,7 @@ export const currentDisplayChatKey = (s: ChatStoreState) =>
messageMapKey({
agentId: s.activeAgentId,
groupId: s.activeGroupId,
+ threadId: s.activeThreadId,
topicId: s.activeTopicId,
});
diff --git a/src/store/chat/slices/operation/types.ts b/src/store/chat/slices/operation/types.ts
index a60a174fb8d..c7ef3e6f222 100644
--- a/src/store/chat/slices/operation/types.ts
+++ b/src/store/chat/slices/operation/types.ts
@@ -53,6 +53,10 @@ export type OperationType =
| 'groupAgentGenerate' // Group agent generate (deprecated, use groupAgentStream)
| 'groupAgentStream' // Group agent SSE stream (sub-operation of execServerAgentRuntime)
+ // === Async Task (Desktop only) ===
+ | 'execClientTask' // Execute single async sub-agent task on desktop client
+ | 'execClientTasks' // Execute multiple async sub-agent tasks on desktop client
+
// === Others ===
| 'translate' // Translate message
| 'topicSummary' // Topic summary