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: add task manager copilot (#14272)

YuTengjing5722b7159b08
diff --git a/locales/en-US/topic.json b/locales/en-US/topic.json
index 8f683b4d48c..1e8f822c192 100644
--- a/locales/en-US/topic.json
+++ b/locales/en-US/topic.json
@@ -56,6 +56,7 @@
"renameModal.title": "Rename Topic",
"searchPlaceholder": "Search Topics...",
"searchResultEmpty": "No search results found.",
+ "taskManager.agent": "Task Agent",
"taskManager.welcome": "Ask me about your tasks",
"temp": "Temporary",
"title": "Topic"
diff --git a/locales/zh-CN/topic.json b/locales/zh-CN/topic.json
index 83e40468332..ee6cd16884f 100644
--- a/locales/zh-CN/topic.json
+++ b/locales/zh-CN/topic.json
@@ -56,6 +56,7 @@
"renameModal.title": "重命名话题",
"searchPlaceholder": "搜索话题…",
"searchResultEmpty": "暂无搜索结果",
+ "taskManager.agent": "任务助手",
"taskManager.welcome": "问我关于你的任务",
"temp": "临时",
"title": "话题"
diff --git a/packages/builtin-agents/package.json b/packages/builtin-agents/package.json
index 7b8d81b1182..428ae6f3e8e 100644
--- a/packages/builtin-agents/package.json
+++ b/packages/builtin-agents/package.json
@@ -11,6 +11,7 @@
"@lobechat/builtin-tool-group-management": "workspace:*",
"@lobechat/builtin-tool-gtd": "workspace:*",
"@lobechat/builtin-tool-notebook": "workspace:*",
+ "@lobechat/builtin-tool-task": "workspace:*",
"@lobechat/builtin-tool-user-interaction": "workspace:*",
"@lobechat/business-const": "workspace:*",
"@lobechat/const": "workspace:*"
diff --git a/packages/builtin-agents/src/agents/task-agent/index.ts b/packages/builtin-agents/src/agents/task-agent/index.ts
new file mode 100644
index 00000000000..113aae8d8e3
--- /dev/null
+++ b/packages/builtin-agents/src/agents/task-agent/index.ts
@@ -0,0 +1,20 @@
+import { TaskIdentifier } from '@lobechat/builtin-tool-task';
+import { DEFAULT_PROVIDER } from '@lobechat/business-const';
+import { DEFAULT_MODEL } from '@lobechat/const';
+
+import type { BuiltinAgentDefinition } from '../../types';
+import { BUILTIN_AGENT_SLUGS } from '../../types';
+import { systemRoleTemplate } from './systemRole';
+
+export const TASK_AGENT: BuiltinAgentDefinition = {
+ avatar: '/avatars/lobe-ai.png',
+ persist: {
+ model: DEFAULT_MODEL,
+ provider: DEFAULT_PROVIDER,
+ },
+ runtime: (ctx) => ({
+ plugins: [TaskIdentifier, ...(ctx.plugins || [])],
+ systemRole: systemRoleTemplate,
+ }),
+ slug: BUILTIN_AGENT_SLUGS.taskAgent,
+};
diff --git a/packages/builtin-agents/src/agents/task-agent/systemRole.ts b/packages/builtin-agents/src/agents/task-agent/systemRole.ts
new file mode 100644
index 00000000000..44faa42de77
--- /dev/null
+++ b/packages/builtin-agents/src/agents/task-agent/systemRole.ts
@@ -0,0 +1,7 @@
+import { systemPrompt } from '@lobechat/builtin-tool-task';
+
+export const systemRoleTemplate = `You are a dedicated task management assistant.
+
+Use the available task tools to help users create, organize, inspect, update, and triage tasks across their workspace. When the user is viewing the task list, reason about tasks globally. When the user is viewing a task detail page, treat that task as the current task unless the user names another task.
+
+${systemPrompt}`;
diff --git a/packages/builtin-agents/src/index.ts b/packages/builtin-agents/src/index.ts
index ac4d0ec4286..8edbcbac6e3 100644
--- a/packages/builtin-agents/src/index.ts
+++ b/packages/builtin-agents/src/index.ts
@@ -3,6 +3,7 @@ import { GROUP_AGENT_BUILDER } from './agents/group-agent-builder';
import { GROUP_SUPERVISOR } from './agents/group-supervisor';
import { INBOX } from './agents/inbox';
import { PAGE_AGENT } from './agents/page-agent';
+import { TASK_AGENT } from './agents/task-agent';
import { WEB_ONBOARDING } from './agents/web-onboarding';
import type { BuiltinAgentDefinition, BuiltinAgentSlug, RuntimeContext } from './types';
import { BUILTIN_AGENT_SLUGS } from './types';
@@ -15,6 +16,7 @@ export { GROUP_AGENT_BUILDER } from './agents/group-agent-builder';
export { GROUP_SUPERVISOR } from './agents/group-supervisor';
export { INBOX } from './agents/inbox';
export { PAGE_AGENT } from './agents/page-agent';
+export { TASK_AGENT } from './agents/task-agent';
export { WEB_ONBOARDING } from './agents/web-onboarding';
/**
@@ -26,6 +28,7 @@ export const BUILTIN_AGENTS: Record<BuiltinAgentSlug, BuiltinAgentDefinition> =
[BUILTIN_AGENT_SLUGS.groupSupervisor]: GROUP_SUPERVISOR,
[BUILTIN_AGENT_SLUGS.inbox]: INBOX,
[BUILTIN_AGENT_SLUGS.pageAgent]: PAGE_AGENT,
+ [BUILTIN_AGENT_SLUGS.taskAgent]: TASK_AGENT,
[BUILTIN_AGENT_SLUGS.webOnboarding]: WEB_ONBOARDING,
};
diff --git a/packages/builtin-agents/src/types.ts b/packages/builtin-agents/src/types.ts
index 41dd02cebe5..60123d1c35a 100644
--- a/packages/builtin-agents/src/types.ts
+++ b/packages/builtin-agents/src/types.ts
@@ -11,6 +11,7 @@ export const BUILTIN_AGENT_SLUGS = {
groupSupervisor: 'group-supervisor',
inbox: 'inbox',
pageAgent: 'page-agent',
+ taskAgent: 'task-agent',
webOnboarding: 'web-onboarding',
} as const;
diff --git a/packages/builtin-tool-task/src/executor/index.ts b/packages/builtin-tool-task/src/executor/index.ts
index 13a6b35c021..7e7e2a271df 100644
--- a/packages/builtin-tool-task/src/executor/index.ts
+++ b/packages/builtin-tool-task/src/executor/index.ts
@@ -27,6 +27,7 @@ class TaskExecutor extends BaseExecutor<typeof TaskApiName> {
createTask = async (
params: {
instruction: string;
+ assigneeAgentId?: string;
name: string;
parentIdentifier?: string;
priority?: number;
@@ -39,7 +40,8 @@ class TaskExecutor extends BaseExecutor<typeof TaskApiName> {
const parentIdentifier = params.parentIdentifier?.trim() || undefined;
const task = await getTaskStoreState().createTask({
- assigneeAgentId: ctx?.agentId,
+ assigneeAgentId:
+ params.assigneeAgentId ?? (ctx?.scope === 'task' ? undefined : ctx?.agentId),
createdByAgentId: ctx?.agentId,
instruction: params.instruction,
name: params.name,
@@ -110,6 +112,7 @@ class TaskExecutor extends BaseExecutor<typeof TaskApiName> {
editTask = async (
params: {
addDependencies?: string[];
+ assigneeAgentId?: string | null;
description?: string;
identifier: string;
instruction?: string;
@@ -129,6 +132,7 @@ class TaskExecutor extends BaseExecutor<typeof TaskApiName> {
const updateData: {
description?: string;
+ assigneeAgentId?: string | null;
instruction?: string;
name?: string;
priority?: number;
@@ -137,6 +141,14 @@ class TaskExecutor extends BaseExecutor<typeof TaskApiName> {
updateData.name = params.name;
changes.push(`name → "${params.name}"`);
}
+ if (params.assigneeAgentId !== undefined) {
+ updateData.assigneeAgentId = params.assigneeAgentId;
+ changes.push(
+ params.assigneeAgentId
+ ? `assignee agent → ${params.assigneeAgentId}`
+ : 'assignee cleared',
+ );
+ }
if (params.instruction !== undefined) {
updateData.instruction = params.instruction;
changes.push('instruction updated');
@@ -201,6 +213,7 @@ class TaskExecutor extends BaseExecutor<typeof TaskApiName> {
const normalized = normalizeListTasksParams(params, {
currentAgentId: ctx?.agentId,
+ defaultScope: ctx?.scope === 'task' ? 'allAgents' : 'currentAgent',
});
const result = await getTaskStoreState().fetchTaskList(normalized.query);
@@ -225,12 +238,13 @@ class TaskExecutor extends BaseExecutor<typeof TaskApiName> {
updateTaskStatus = async (
params: { error?: string; identifier?: string; status: TaskStatus },
- _ctx?: BuiltinToolContext,
+ ctx?: BuiltinToolContext,
): Promise<BuiltinToolResult> => {
try {
log('[TaskExecutor] updateTaskStatus - params:', params);
- const id = await getTaskStoreState().updateTaskStatus(params.identifier, params.status, {
+ const identifier = params.identifier ?? ctx?.taskId ?? undefined;
+ const id = await getTaskStoreState().updateTaskStatus(identifier, params.status, {
error: params.error,
});
@@ -255,12 +269,14 @@ class TaskExecutor extends BaseExecutor<typeof TaskApiName> {
viewTask = async (
params: { identifier?: string },
- _ctx?: BuiltinToolContext,
+ ctx?: BuiltinToolContext,
): Promise<BuiltinToolResult> => {
try {
log('[TaskExecutor] viewTask - params:', params);
- const detail = await getTaskStoreState().fetchTaskDetail(params.identifier);
+ const detail = await getTaskStoreState().fetchTaskDetail(
+ params.identifier ?? ctx?.taskId ?? undefined,
+ );
return {
content: formatTaskDetail(detail),
diff --git a/packages/builtin-tool-task/src/index.ts b/packages/builtin-tool-task/src/index.ts
index 555cb4b2fcc..67931fa2ab7 100644
--- a/packages/builtin-tool-task/src/index.ts
+++ b/packages/builtin-tool-task/src/index.ts
@@ -5,4 +5,5 @@ export {
normalizeOptionalFilterValues,
} from './listTasks';
export { TaskIdentifier, TaskManifest } from './manifest';
+export { systemPrompt } from './systemRole';
export { TaskApiName } from './types';
diff --git a/packages/builtin-tool-task/src/listTasks.ts b/packages/builtin-tool-task/src/listTasks.ts
index 262c8c3edda..40738df7063 100644
--- a/packages/builtin-tool-task/src/listTasks.ts
+++ b/packages/builtin-tool-task/src/listTasks.ts
@@ -27,6 +27,7 @@ export interface TaskListQuery {
export interface TaskListDisplayFilters {
assigneeAgentId?: string;
isDefaultScope: boolean;
+ isForAllAgents?: boolean;
isForCurrentAgent?: boolean;
parentIdentifier?: string;
priorities?: number[];
@@ -35,6 +36,7 @@ export interface TaskListDisplayFilters {
interface NormalizeListTasksOptions {
currentAgentId?: string;
+ defaultScope?: 'allAgents' | 'currentAgent';
}
export const normalizeOptionalFilterValues = <T>(values?: T[]) =>
@@ -58,20 +60,23 @@ export const normalizeListTasksParams = (
displayFilters: TaskListDisplayFilters;
query: TaskListQuery;
} => {
- const { currentAgentId } = options;
+ const { currentAgentId, defaultScope = 'currentAgent' } = options;
const isDefaultScope = !hasExplicitFilter(params);
const priorities = normalizeOptionalFilterValues(params.priorities);
const statuses =
normalizeOptionalFilterValues(params.statuses) ??
(isDefaultScope ? [...UNFINISHED_TASK_STATUSES] : undefined);
- const assigneeAgentId = params.assigneeAgentId ?? (isDefaultScope ? currentAgentId : undefined);
+ const shouldUseCurrentAgent = isDefaultScope && defaultScope === 'currentAgent';
+ const assigneeAgentId =
+ params.assigneeAgentId ?? (shouldUseCurrentAgent ? currentAgentId : undefined);
return {
displayFilters: {
assigneeAgentId,
isDefaultScope,
- isForCurrentAgent: isDefaultScope && Boolean(currentAgentId),
+ isForAllAgents: isDefaultScope && defaultScope === 'allAgents',
+ isForCurrentAgent: shouldUseCurrentAgent && Boolean(currentAgentId),
parentIdentifier: params.parentIdentifier,
priorities,
statuses,
diff --git a/packages/builtin-tool-task/src/manifest.ts b/packages/builtin-tool-task/src/manifest.ts
index 51dd468569c..06a20e78b01 100644
--- a/packages/builtin-tool-task/src/manifest.ts
+++ b/packages/builtin-tool-task/src/manifest.ts
@@ -20,6 +20,11 @@ export const TaskManifest: BuiltinToolManifest = {
description: 'Detailed instruction for what the task should accomplish.',
type: 'string',
},
+ assigneeAgentId: {
+ description:
+ 'Optional agent ID to assign the task to. In task management context, omit it to create an unassigned task.',
+ type: 'string',
+ },
name: {
description: 'A short, descriptive name for the task.',
type: 'string',
@@ -45,13 +50,13 @@ export const TaskManifest: BuiltinToolManifest = {
},
{
description:
- 'List tasks. Without any filters, returns top-level unfinished tasks of the current agent. If you provide any filter, omitted filters are not applied implicitly.',
+ 'List tasks. Without any filters, returns top-level unfinished tasks. In agent conversations it defaults to the current agent; in task manager context it spans all agents. If you provide any filter, omitted filters are not applied implicitly.',
name: TaskApiName.listTasks,
parameters: {
properties: {
assigneeAgentId: {
description:
- 'Restrict to tasks assigned to this agent. When omitted, no assignee filter is applied unless listTasks is called without any filters, which defaults to the current agent.',
+ 'Restrict to tasks assigned to this agent. When omitted, no assignee filter is applied unless listTasks is called without any filters in an agent conversation, which defaults to the current agent.',
type: 'string',
},
limit: { description: `Max 1-100. Default ${DEFAULT_LIST_TASK_LIMIT}.`, type: 'number' },
@@ -107,6 +112,10 @@ export const TaskManifest: BuiltinToolManifest = {
items: { type: 'string' },
type: 'array',
},
+ assigneeAgentId: {
+ description: 'Assign the task to this agent ID. Pass null to clear the assignee.',
+ type: ['string', 'null'],
+ },
description: {
description:
'Human-readable description (displayed in UI). Separate from instruction, which guides the agent.',
diff --git a/packages/builtin-tool-task/src/systemRole.ts b/packages/builtin-tool-task/src/systemRole.ts
index a57985bb47c..b311a7ae101 100644
--- a/packages/builtin-tool-task/src/systemRole.ts
+++ b/packages/builtin-tool-task/src/systemRole.ts
@@ -1,7 +1,7 @@
export const systemPrompt = `You have access to Task management tools. Use them to:
- **createTask**: Create a new task. Use parentIdentifier to make it a subtask
-- **listTasks**: List tasks. With no filters, defaults to top-level unfinished tasks of the current agent. If you provide any filter, omitted filters are not applied implicitly
+- **listTasks**: List tasks. With no filters, defaults to top-level unfinished tasks of the current agent in normal agent conversations, or top-level unfinished tasks across all agents in task manager conversations. If you provide any filter, omitted filters are not applied implicitly
- **viewTask**: View details of a specific task. Omitting identifier only works when there is a current task context
- **editTask**: Modify a task's fields (name, description, instruction, priority) or dependencies (addDependencies/removeDependencies, batch). For status changes use updateTaskStatus
- **updateTaskStatus**: Change a task's status. If you mark a task as failed, include an error message explaining why. Omitting identifier only works when there is a current task context
diff --git a/packages/database/src/models/__tests__/agent.test.ts b/packages/database/src/models/__tests__/agent.test.ts
index 29b53439f3f..09c10f0ae16 100644
--- a/packages/database/src/models/__tests__/agent.test.ts
+++ b/packages/database/src/models/__tests__/agent.test.ts
@@ -1254,6 +1254,14 @@ describe('AgentModel', () => {
expect(result?.slug).toBe('page-agent');
expect(result?.virtual).toBe(true);
});
+
+ it('should create task-agent builtin agent', async () => {
+ const result = await agentModel.getBuiltinAgent('task-agent');
+
+ expect(result).toBeDefined();
+ expect(result?.slug).toBe('task-agent');
+ expect(result?.virtual).toBe(true);
+ });
});
});
diff --git a/packages/database/src/models/agent.ts b/packages/database/src/models/agent.ts
index cb9c4a4b49b..fc7adbf9a2f 100644
--- a/packages/database/src/models/agent.ts
+++ b/packages/database/src/models/agent.ts
@@ -37,6 +37,16 @@ export class AgentModel {
return this.enrichAgentWithKnowledge(agent);
};
+ existsById = async (id: string): Promise<boolean> => {
+ const rows = await this.db
+ .select({ id: agents.id })
+ .from(agents)
+ .where(and(eq(agents.id, id), eq(agents.userId, this.userId)))
+ .limit(1);
+
+ return rows.length > 0;
+ };
+
/**
* Query non-virtual agents with optional keyword filter.
* Returns minimal agent info (id, title, description, avatar, backgroundColor).
diff --git a/packages/database/src/models/recent.ts b/packages/database/src/models/recent.ts
index 673d419b6da..57018975451 100644
--- a/packages/database/src/models/recent.ts
+++ b/packages/database/src/models/recent.ts
@@ -14,9 +14,9 @@ export interface RecentDbItem {
updatedAt: Date;
}
-// Mirrors `MAIN_SIDEBAR_EXCLUDE_TRIGGERS` in `src/const/topic.ts`. System-trigger
-// topics live in their own surfaces (Task Manager, cron, eval, task runs) and
-// would clutter the main "Recent" list.
+// Mirrors `MAIN_SIDEBAR_EXCLUDE_TRIGGERS` in `src/const/topic.ts` plus the
+// legacy `task_manager` trigger from the previous Task Manager panel.
+// System-trigger topics live in their own surfaces and would clutter Recent.
const SYSTEM_TOPIC_TRIGGERS = ['cron', 'eval', 'task_manager', 'task'];
// Excluded so file uploads and web-browsing tool scrapes don't surface as
diff --git a/packages/prompts/src/prompts/task/buildTaskDetailPrompt.test.ts b/packages/prompts/src/prompts/task/buildTaskDetailPrompt.test.ts
index c6f4484c96f..15cf9f526a0 100644
--- a/packages/prompts/src/prompts/task/buildTaskDetailPrompt.test.ts
+++ b/packages/prompts/src/prompts/task/buildTaskDetailPrompt.test.ts
@@ -24,6 +24,20 @@ describe('buildTaskDetailPrompt', () => {
expect(result).not.toContain('<high_priority_instruction>');
});
+ it('includes default Lobe AI assignee hint when provided', () => {
+ const result = buildTaskDetailPrompt(
+ {
+ defaultAssigneeAgentId: 'agt_inbox',
+ task: baseTask,
+ },
+ NOW,
+ );
+
+ expect(result).toContain('<task_manager_defaults>');
+ expect(result).toContain('Default Lobe AI agent id: agt_inbox');
+ expect(result).toContain('Use this id as assigneeAgentId');
+ });
+
it('includes subtasks, dependencies, and review', () => {
const result = buildTaskDetailPrompt(
{
diff --git a/packages/prompts/src/prompts/task/buildTaskDetailPrompt.ts b/packages/prompts/src/prompts/task/buildTaskDetailPrompt.ts
index f88c23dd49a..3e452e823db 100644
--- a/packages/prompts/src/prompts/task/buildTaskDetailPrompt.ts
+++ b/packages/prompts/src/prompts/task/buildTaskDetailPrompt.ts
@@ -1,7 +1,9 @@
import type { TaskDetailData, TaskDetailWorkspaceNode } from './index';
import { briefIcon, priorityLabel, statusIcon, timeAgo } from './index';
+import type { TaskManagerPromptDefaults } from './taskManagerDefaults';
+import { buildTaskManagerDefaultsBlock } from './taskManagerDefaults';
-export interface BuildTaskDetailPromptInput {
+export interface BuildTaskDetailPromptInput extends TaskManagerPromptDefaults {
task: TaskDetailData;
}
@@ -15,6 +17,7 @@ export const buildTaskDetailPrompt = (input: BuildTaskDetailPromptInput, now?: D
const lines: string[] = [
`<page_context>The user is currently viewing the detail page of task ${task.identifier}. When the user says "this task" or refers ambiguously, it means ${task.identifier}.</page_context>`,
+ ...buildTaskManagerDefaultsBlock(input),
'<task>',
`<hint>This tag contains the complete context of the task the user is viewing. Do NOT call viewTask to re-fetch it.</hint>`,
`${task.identifier} ${task.name || '(unnamed)'}`,
diff --git a/packages/prompts/src/prompts/task/buildTaskListPrompt.test.ts b/packages/prompts/src/prompts/task/buildTaskListPrompt.test.ts
index 24d65515f5e..9ca035d3ee3 100644
--- a/packages/prompts/src/prompts/task/buildTaskListPrompt.test.ts
+++ b/packages/prompts/src/prompts/task/buildTaskListPrompt.test.ts
@@ -69,4 +69,19 @@ describe('buildTaskListPrompt', () => {
expect(result).toMatchSnapshot();
expect(result).not.toContain('ago');
});
+
+ it('includes default Lobe AI assignee hint when provided', () => {
+ const result = buildTaskListPrompt(
+ {
+ defaultAssigneeAgentId: 'agt_inbox',
+ tasks: [],
+ total: 0,
+ },
+ NOW,
+ );
+
+ expect(result).toContain('<task_manager_defaults>');
+ expect(result).toContain('Default Lobe AI agent id: agt_inbox');
+ expect(result).toContain('Do not use it as a listTasks filter');
+ });
});
diff --git a/packages/prompts/src/prompts/task/buildTaskListPrompt.ts b/packages/prompts/src/prompts/task/buildTaskListPrompt.ts
index 20a5121c18d..153c173c1f8 100644
--- a/packages/prompts/src/prompts/task/buildTaskListPrompt.ts
+++ b/packages/prompts/src/prompts/task/buildTaskListPrompt.ts
@@ -1,7 +1,9 @@
import type { TaskSummary } from './index';
import { priorityLabel, statusIcon, timeAgo } from './index';
+import type { TaskManagerPromptDefaults } from './taskManagerDefaults';
+import { buildTaskManagerDefaultsBlock } from './taskManagerDefaults';
-export interface BuildTaskListPromptInput {
+export interface BuildTaskListPromptInput extends TaskManagerPromptDefaults {
tasks: Array<TaskSummary & { createdAt?: string | Date }>;
total: number;
}
@@ -16,6 +18,7 @@ export const buildTaskListPrompt = (input: BuildTaskListPromptInput, now?: Date)
const lines: string[] = [
'<task_list>',
`<hint>The user is currently viewing the tasks list page. These are the ${shown} task(s) displayed in the UI. Do NOT call listTasks to re-fetch them.</hint>`,
+ ...buildTaskManagerDefaultsBlock(input),
];
if (shown === 0) {
diff --git a/packages/prompts/src/prompts/task/index.ts b/packages/prompts/src/prompts/task/index.ts
index 8e4abdab31d..46ea3d6b529 100644
--- a/packages/prompts/src/prompts/task/index.ts
+++ b/packages/prompts/src/prompts/task/index.ts
@@ -88,6 +88,7 @@ export const formatTaskCreated = (
export interface TaskListFilters {
assigneeAgentId?: string;
isDefaultScope?: boolean;
+ isForAllAgents?: boolean;
isForCurrentAgent?: boolean;
parentIdentifier?: string;
priorities?: number[];
@@ -96,6 +97,7 @@ export interface TaskListFilters {
const buildTaskListLabel = (filters: TaskListFilters): string => {
if (filters.isDefaultScope) {
+ if (filters.isForAllAgents) return 'top-level unfinished tasks across all agents';
return filters.isForCurrentAgent
? 'top-level unfinished tasks of the current agent'
: 'top-level unfinished tasks';
@@ -615,3 +617,5 @@ export type { BuildTaskDetailPromptInput } from './buildTaskDetailPrompt';
export { buildTaskDetailPrompt } from './buildTaskDetailPrompt';
export type { BuildTaskListPromptInput } from './buildTaskListPrompt';
export { buildTaskListPrompt } from './buildTaskListPrompt';
+export type { TaskManagerPromptDefaults } from './taskManagerDefaults';
+export { buildTaskManagerDefaultsPrompt } from './taskManagerDefaults';
diff --git a/packages/prompts/src/prompts/task/taskManagerDefaults.ts b/packages/prompts/src/prompts/task/taskManagerDefaults.ts
new file mode 100644
index 00000000000..13e1be064c7
--- /dev/null
+++ b/packages/prompts/src/prompts/task/taskManagerDefaults.ts
@@ -0,0 +1,21 @@
+export interface TaskManagerPromptDefaults {
+ defaultAssigneeAgentId?: string;
+}
+
+export const buildTaskManagerDefaultsBlock = ({
+ defaultAssigneeAgentId,
+}: TaskManagerPromptDefaults): string[] => {
+ if (!defaultAssigneeAgentId) return [];
+
+ return [
+ '<task_manager_defaults>',
+ `Default Lobe AI agent id: ${defaultAssigneeAgentId}`,
+ 'Use this id as assigneeAgentId when you decide a task should be assigned to the default Lobe AI assistant.',
+ "Do not use it as a listTasks filter unless the user asks for Lobe AI's tasks.",
+ '</task_manager_defaults>',
+ '',
+ ];
+};
+
+export const buildTaskManagerDefaultsPrompt = (defaults: TaskManagerPromptDefaults): string =>
+ buildTaskManagerDefaultsBlock(defaults).join('\n').trim();
diff --git a/packages/types/src/agentExecution/index.ts b/packages/types/src/agentExecution/index.ts
index ef7c16587d7..ba4a301c066 100644
--- a/packages/types/src/agentExecution/index.ts
+++ b/packages/types/src/agentExecution/index.ts
@@ -5,6 +5,8 @@ import type { ChatTopic } from '../topic';
* Application context for message storage
*/
export interface ExecAgentAppContext {
+ /** Optional default assignee candidate for task manager prompts */
+ defaultTaskAssigneeAgentId?: string;
/** Current document ID for page-scoped conversations */
documentId?: string | null;
/** Group ID for group chat */
@@ -13,6 +15,8 @@ export interface ExecAgentAppContext {
scope?: string | null;
/** Session ID */
sessionId?: string;
+ /** Current task identifier when executing from a task detail surface */
+ taskId?: string | null;
/** Thread ID for threaded conversations */
threadId?: string | null;
/** Topic ID */
diff --git a/packages/types/src/conversation.ts b/packages/types/src/conversation.ts
index 777f0acd23b..1f56c983beb 100644
--- a/packages/types/src/conversation.ts
+++ b/packages/types/src/conversation.ts
@@ -6,6 +6,7 @@ import type { IThreadType } from './topic/thread';
* - thread: Agent thread conversation
* - group: Group main conversation
* - group_agent: Agent conversation within a group
+ * - task: Task manager side panel conversation
* - sub_agent: Agent-to-agent communication (non-group, uses subAgentId for config/display only)
*/
export type MessageMapScope =
@@ -15,6 +16,7 @@ export type MessageMapScope =
| 'group_agent'
| 'group_agent_builder'
| 'page'
+ | 'task'
| 'agent_builder'
| 'sub_agent';
@@ -118,6 +120,11 @@ export interface MessageMapContext {
*/
export interface ConversationContext {
agentId: string;
+ /**
+ * Optional default assignee candidate for task manager conversations.
+ * This is a prompt hint only; task tools still require an explicit assigneeAgentId.
+ */
+ defaultTaskAssigneeAgentId?: string;
/**
* Current document ID for page-scoped conversations.
* Used by page editor integrations to distinguish the active document from
@@ -154,6 +161,7 @@ export interface ConversationContext {
* - 'thread': Agent thread conversation
* - 'group': Group main conversation
* - 'group_agent': Agent conversation within a group
+ * - 'task': Task manager side panel conversation
* @default 'main' (auto-detected based on threadId)
*/
scope?: MessageMapScope;
@@ -201,12 +209,6 @@ export interface ConversationContext {
* When present, allows unauthenticated access to topic messages
*/
topicShareId?: string;
- /**
- * Trigger value applied when sendMessage creates a new topic from this
- * context (e.g. `'task_manager'`). Stamped on the topic row to support
- * page-specific filtering. Only consumed during new-topic creation.
- */
- topicTrigger?: string;
/**
* Task Manager page the user is currently viewing. When set, streamingExecutor
* builds `RuntimeInitialContext.taskManager` from the task store.
diff --git a/packages/types/src/tool/builtin.ts b/packages/types/src/tool/builtin.ts
index 44b0fc0d579..ae733befb3e 100644
--- a/packages/types/src/tool/builtin.ts
+++ b/packages/types/src/tool/builtin.ts
@@ -469,6 +469,11 @@ export interface BuiltinToolContext {
*/
stepContext?: RuntimeStepContext;
+ /**
+ * Current task identifier or database id when the conversation is scoped to a task detail page.
+ */
+ taskId?: string | null;
+
/**
* The current topic ID (only available when operating within a topic)
* Used by tools that need to create messages or operations within a topic
diff --git a/src/const/topic.ts b/src/const/topic.ts
index 1d4ef80aada..bc84246fac3 100644
--- a/src/const/topic.ts
+++ b/src/const/topic.ts
@@ -1,6 +1,5 @@
/**
- * Well-known `topic.trigger` values used to segment the same agent's topics
- * across different panels (Task Manager vs. main chat).
+ * Well-known `topic.trigger` values used to segment system-owned topics.
*
* `RunTask` is what `TaskRunnerService` writes when starting an agent run for
* a task; the literal `'task'` is intentional and matches existing DB rows.
@@ -9,21 +8,14 @@ export const TopicTrigger = {
Cron: 'cron',
Eval: 'eval',
RunTask: 'task',
- TaskManager: 'task_manager',
} as const;
/**
- * Triggers to exclude from the main chat sidebar so page-owned topics
- * (cron jobs, evals, task manager) don't pollute the user's main history.
+ * Triggers to exclude from the main chat sidebar so system-owned topics
+ * (cron jobs, evals, task runs) don't pollute the user's main history.
*/
export const MAIN_SIDEBAR_EXCLUDE_TRIGGERS: string[] = [
TopicTrigger.Cron,
TopicTrigger.Eval,
- TopicTrigger.TaskManager,
TopicTrigger.RunTask,
];
-
-/**
- * Triggers the Task Manager panel fetches.
- */
-export const TASK_MANAGER_INCLUDE_TRIGGERS: string[] = [TopicTrigger.TaskManager];
diff --git a/src/features/AgentTaskManager/AgentSelectorAction.test.tsx b/src/features/AgentTaskManager/AgentSelectorAction.test.tsx
new file mode 100644
index 00000000000..c9a6abd6761
--- /dev/null
+++ b/src/features/AgentTaskManager/AgentSelectorAction.test.tsx
@@ -0,0 +1,172 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { fireEvent, render } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import AgentSelectorAction from './AgentSelectorAction';
+
+const mocks = vi.hoisted(() => ({
+ agentState: {
+ agentMap: {
+ agt_task: {
+ avatar: 'task-avatar',
+ description: 'Task manager',
+ },
+ },
+ builtinAgentIdMap: {
+ 'task-agent': 'agt_task',
+ },
+ },
+ conversationState: {
+ context: {
+ agentId: 'agt_task',
+ },
+ },
+ fetchAgentList: vi.fn(),
+ homeState: {
+ agentGroups: [] as any[],
+ isAgentListInit: true,
+ pinnedAgents: [] as any[],
+ ungroupedAgents: [
+ { id: 'agt_custom', title: 'Custom Agent', type: 'agent' },
+ { id: 'grp_custom', title: 'Custom Group', type: 'group' },
+ ],
+ },
+}));
+
+vi.mock('@lobehub/ui', () => ({
+ Center: ({ children }: { children: ReactNode }) => (
+ <div data-testid="selector-trigger">{children}</div>
+ ),
+ Flexbox: ({ children }: { children: ReactNode }) => <div>{children}</div>,
+ Popover: ({
+ children,
+ content,
+ onOpenChange,
+ }: {
+ children: ReactNode;
+ content: ReactNode;
+ onOpenChange?: (open: boolean) => void;
+ }) => (
+ <div>
+ <button data-testid="open-popover" onClick={() => onOpenChange?.(true)}>
+ {children}
+ </button>
+ <div data-testid="popover-content">{content}</div>
+ </div>
+ ),
+}));
+
+vi.mock('antd-style', () => ({
+ createStaticStyles: () => ({
+ chevron: 'chevron',
+ container: 'container',
+ }),
+ cx: (...classes: string[]) => classes.filter(Boolean).join(' '),
+}));
+
+vi.mock('lucide-react', () => ({
+ ChevronsUpDownIcon: () => <span data-testid="chevron" />,
+}));
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string) => (key === 'taskManager.agent' ? 'Task Manager' : key),
+ }),
+}));
+
+vi.mock('@/features/Conversation', () => ({
+ conversationSelectors: {
+ agentId: (state: typeof mocks.conversationState) => state.context.agentId,
+ },
+ useConversationStore: (selector: (state: typeof mocks.conversationState) => unknown) =>
+ selector(mocks.conversationState),
+}));
+
+vi.mock('@/features/NavPanel/components/SkeletonList', () => ({
+ default: () => <div data-testid="skeleton" />,
+}));
+
+vi.mock('@/features/PageEditor/Copilot/AgentSelector/AgentItem', () => ({
+ default: ({
+ agentId,
+ agentTitle,
+ onAgentChange,
+ }: {
+ agentId: string;
+ agentTitle: string;
+ onAgentChange: (id: string) => void;
+ }) => (
+ <button data-agent-id={agentId} onClick={() => onAgentChange(agentId)}>
+ {agentTitle}
+ </button>
+ ),
+}));
+
+vi.mock('@/hooks/useFetchAgentList', () => ({
+ useFetchAgentList: () => mocks.fetchAgentList(),
+}));
+
+vi.mock('@/routes/(main)/home/_layout/Body/Agent/List/AgentItem/Avatar', () => ({
+ default: ({ avatar }: { avatar?: string }) => <span data-avatar={avatar} data-testid="avatar" />,
+}));
+
+vi.mock('@/routes/(main)/home/_layout/Body/Agent/ModalProvider', () => ({
+ AgentModalProvider: ({ children }: { children: ReactNode }) => <>{children}</>,
+}));
+
+vi.mock('@/store/agent', () => ({
+ useAgentStore: (selector: (state: typeof mocks.agentState) => unknown) =>
+ selector(mocks.agentState),
+}));
+
+vi.mock('@/store/home', () => ({
+ useHomeStore: (selector: (state: typeof mocks.homeState) => unknown) => selector(mocks.homeState),
+}));
+
+describe('AgentSelectorAction', () => {
+ beforeEach(() => {
+ mocks.fetchAgentList.mockClear();
+ mocks.conversationState.context.agentId = 'agt_task';
+ mocks.homeState.isAgentListInit = true;
+ mocks.homeState.ungroupedAgents = [
+ { id: 'agt_custom', title: 'Custom Agent', type: 'agent' },
+ { id: 'grp_custom', title: 'Custom Group', type: 'group' },
+ ];
+ });
+
+ it('adds the builtin task agent and filters out group sessions', () => {
+ render(<AgentSelectorAction onAgentChange={vi.fn()} />);
+
+ expect(mocks.fetchAgentList).toHaveBeenCalledOnce();
+ expect(document.body.textContent).toContain('Task Manager');
+ expect(document.body.textContent).toContain('Custom Agent');
+ expect(document.body.textContent).not.toContain('Custom Group');
+ });
+
+ it('uses the active agent avatar and forwards agent changes', () => {
+ const onAgentChange = vi.fn();
+ const { getByText, getByTestId } = render(
+ <AgentSelectorAction onAgentChange={onAgentChange} />,
+ );
+
+ expect(getByTestId('avatar').dataset.avatar).toBe('task-avatar');
+
+ fireEvent.click(getByText('Custom Agent'));
+ expect(onAgentChange).toHaveBeenCalledWith('agt_custom');
+ });
+
+ it('does not duplicate the task agent when it already exists in the home list', () => {
+ mocks.homeState.ungroupedAgents = [
+ { id: 'agt_task', title: 'Task Manager From Home', type: 'agent' },
+ { id: 'agt_custom', title: 'Custom Agent', type: 'agent' },
+ ];
+
+ render(<AgentSelectorAction onAgentChange={vi.fn()} />);
+
+ expect(document.body.textContent).not.toContain('Task ManagerTask Manager');
+ expect(document.body.textContent).toContain('Task Manager From Home');
+ });
+});
diff --git a/src/features/AgentTaskManager/AgentSelectorAction.tsx b/src/features/AgentTaskManager/AgentSelectorAction.tsx
new file mode 100644
index 00000000000..e676d5a35c5
--- /dev/null
+++ b/src/features/AgentTaskManager/AgentSelectorAction.tsx
@@ -0,0 +1,145 @@
+import { Center, Flexbox, Popover } from '@lobehub/ui';
+import { createStaticStyles, cx } from 'antd-style';
+import { ChevronsUpDownIcon } from 'lucide-react';
+import { memo, Suspense, useCallback, useMemo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { conversationSelectors, useConversationStore } from '@/features/Conversation';
+import SkeletonList from '@/features/NavPanel/components/SkeletonList';
+import AgentItem from '@/features/PageEditor/Copilot/AgentSelector/AgentItem';
+import { useFetchAgentList } from '@/hooks/useFetchAgentList';
+import AgentAvatar from '@/routes/(main)/home/_layout/Body/Agent/List/AgentItem/Avatar';
+import { AgentModalProvider } from '@/routes/(main)/home/_layout/Body/Agent/ModalProvider';
+import { useAgentStore } from '@/store/agent';
+import { builtinAgentSelectors } from '@/store/agent/selectors';
+import { useHomeStore } from '@/store/home';
+import { homeAgentListSelectors } from '@/store/home/selectors';
+
+const styles = createStaticStyles(({ css, cssVar }) => ({
+ chevron: css`
+ color: ${cssVar.colorTextQuaternary};
+ `,
+ container: css`
+ cursor: pointer;
+
+ border-radius: 12px;
+ border-start-start-radius: 8px;
+ border-end-start-radius: 8px;
+
+ background: ${cssVar.colorFillTertiary};
+
+ :hover {
+ background: ${cssVar.colorFillSecondary};
+ }
+ `,
+}));
+
+interface AgentSelectorActionProps {
+ onAgentChange: (id: string) => void;
+}
+
+const AgentSelectorAction = memo<AgentSelectorActionProps>(({ onAgentChange }) => {
+ const { t } = useTranslation(['chat', 'topic']);
+ const [open, setOpen] = useState(false);
+ const agentId = useConversationStore(conversationSelectors.agentId);
+
+ const agents = useHomeStore(homeAgentListSelectors.allAgents);
+ const isAgentListInit = useHomeStore(homeAgentListSelectors.isAgentListInit);
+ const taskAgentId = useAgentStore(builtinAgentSelectors.taskAgentId);
+ const taskAgentData = useAgentStore((s) => s.agentMap[taskAgentId || '']);
+
+ useFetchAgentList();
+
+ const agentsWithBuiltin = useMemo(() => {
+ const availableAgents = agents.filter((agent) => agent.type === 'agent');
+ const hasTaskAgent = availableAgents.some((agent) => agent.id === taskAgentId);
+
+ if (taskAgentId && !hasTaskAgent) {
+ return [
+ {
+ avatar: taskAgentData?.avatar || null,
+ description: taskAgentData?.description || null,
+ id: taskAgentId,
+ pinned: false,
+ title: t('taskManager.agent', { ns: 'topic' }),
+ type: 'agent' as const,
+ updatedAt: new Date(),
+ },
+ ...availableAgents,
+ ];
+ }
+
+ return availableAgents;
+ }, [agents, taskAgentData, taskAgentId, t]);
+
+ const activeAgent = useMemo(
+ () => agentsWithBuiltin.find((agent) => agent.id === agentId),
+ [agentId, agentsWithBuiltin],
+ );
+
+ const handleAgentChange = useCallback(
+ (id: string) => {
+ onAgentChange(id);
+ },
+ [onAgentChange],
+ );
+
+ const renderAgents = (
+ <Flexbox
+ gap={4}
+ padding={8}
+ style={{
+ maxHeight: '50vh',
+ overflowY: 'auto',
+ width: '100%',
+ }}
+ >
+ {agentsWithBuiltin.map((agent) => (
+ <AgentItem
+ active={agent.id === agentId}
+ agentId={agent.id}
+ agentTitle={agent.title || t('untitledAgent', { ns: 'chat' })}
+ avatar={agent.avatar}
+ key={agent.id}
+ onAgentChange={handleAgentChange}
+ onClose={() => setOpen(false)}
+ />
+ ))}
+ </Flexbox>
+ );
+
+ return (
+ <Popover
+ open={open}
+ placement="topLeft"
+ trigger="click"
+ content={
+ <Suspense fallback={<SkeletonList rows={6} />}>
+ <AgentModalProvider>
+ {isAgentListInit ? renderAgents : <SkeletonList rows={6} />}
+ </AgentModalProvider>
+ </Suspense>
+ }
+ styles={{
+ content: {
+ padding: 0,
+ width: 240,
+ },
+ }}
+ onOpenChange={setOpen}
+ >
+ <Center horizontal className={cx(styles.container)} height={28} paddingInline={6}>
+ <Flexbox horizontal align={'center'} gap={4}>
+ <AgentAvatar
+ avatar={typeof activeAgent?.avatar === 'string' ? activeAgent.avatar : undefined}
+ />
+ <ChevronsUpDownIcon className={styles.chevron} size={14} />
+ </Flexbox>
+ </Center>
+ </Popover>
+ );
+});
+
+AgentSelectorAction.displayName = 'AgentSelectorAction';
+
+export default AgentSelectorAction;
diff --git a/src/features/AgentTaskManager/Conversation.tsx b/src/features/AgentTaskManager/Conversation.tsx
index d1edf1f9452..33f9ab66064 100644
--- a/src/features/AgentTaskManager/Conversation.tsx
+++ b/src/features/AgentTaskManager/Conversation.tsx
@@ -1,14 +1,11 @@
'use client';
-import { type ConversationContext } from '@lobechat/types';
+import { isChatGroupSessionId } from '@lobechat/types';
import { Flexbox, Text } from '@lobehub/ui';
-import debug from 'debug';
-import { memo, useEffect, useMemo } from 'react';
+import { memo, useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
-import { useMatch } from 'react-router-dom';
import DragUploadZone, { useUploadFiles } from '@/components/DragUploadZone';
-import { TopicTrigger } from '@/const/topic';
import { actionMap } from '@/features/ChatInput/ActionBar/config';
import { ActionBarContext } from '@/features/ChatInput/ActionBar/context';
import {
@@ -16,28 +13,23 @@ import {
COMPACT_ACTION_BAR_STYLE,
COMPACT_SEND_BUTTON_PROPS,
} from '@/features/ChatInput/compactPreset';
-import { ChatInput, ChatList, ConversationProvider } from '@/features/Conversation';
-import { type ConversationHooks } from '@/features/Conversation/types';
+import {
+ ChatInput,
+ ChatList,
+ conversationSelectors,
+ useConversationStore,
+} from '@/features/Conversation';
import CopilotModelSelect from '@/features/PageEditor/Copilot/CopilotModelSelect';
-import { useOperationState } from '@/hooks/useOperationState';
import { useAgentStore } from '@/store/agent';
import { agentByIdSelectors } from '@/store/agent/selectors';
-import { useChatStore } from '@/store/chat';
-import { messageMapKey } from '@/store/chat/utils/messageMapKey';
-import { useTaskChatStore } from '@/store/taskChat';
+import AgentSelectorAction from './AgentSelectorAction';
import Toolbar from './Toolbar';
-const log = debug('lobe-render:agent-task-manager:Conversation');
-
const Search = actionMap['search'];
const EMPTY_LEFT_ACTIONS: [] = [];
-const HOOKS: ConversationHooks = {
- onTopicCreated: (topicId: string) => useTaskChatStore.getState().onTopicCreated(topicId),
-};
-
const Welcome = memo(() => {
const { t } = useTranslation('topic');
return (
@@ -52,83 +44,60 @@ const Welcome = memo(() => {
Welcome.displayName = 'Welcome';
const Conversation = memo(() => {
- const activeAgentId = useChatStore((s) => s.activeAgentId);
- const taskTopicId = useTaskChatStore((s) => s.activeTopicId);
+ const [setActiveAgentId, useFetchAgentConfig] = useAgentStore((s) => [
+ s.setActiveAgentId,
+ s.useFetchAgentConfig,
+ ]);
+ const currentAgentId = useConversationStore(conversationSelectors.agentId);
- const model = useAgentStore((s) => agentByIdSelectors.getAgentModelById(activeAgentId)(s));
+ useFetchAgentConfig(true, currentAgentId);
+
+ const model = useAgentStore((s) => agentByIdSelectors.getAgentModelById(currentAgentId)(s));
const provider = useAgentStore((s) =>
- agentByIdSelectors.getAgentModelProviderById(activeAgentId)(s),
+ agentByIdSelectors.getAgentModelProviderById(currentAgentId)(s),
);
const { handleUploadFiles } = useUploadFiles({ model, provider });
- useEffect(() => {
- useTaskChatStore.getState().switchTopic(null);
- }, [activeAgentId]);
-
- const detailMatch = useMatch('/task/:taskId');
- const viewedTaskId = detailMatch?.params.taskId;
-
- const context = useMemo<ConversationContext>(
- () => ({
- agentId: activeAgentId,
- isolatedTopic: true,
- scope: 'main',
- topicId: taskTopicId,
- topicTrigger: TopicTrigger.TaskManager,
- viewedTask: viewedTaskId ? { taskId: viewedTaskId, type: 'detail' } : undefined,
- }),
- [activeAgentId, taskTopicId, viewedTaskId],
+ const handleAgentChange = useCallback(
+ (id: string) => {
+ if (!id || id === currentAgentId || isChatGroupSessionId(id)) return;
+ setActiveAgentId(id);
+ },
+ [currentAgentId, setActiveAgentId],
);
- const chatKey = messageMapKey(context);
- const replaceMessages = useChatStore((s) => s.replaceMessages);
- const messages = useChatStore((s) => s.dbMessagesMap[chatKey]);
- log('contextKey %s: %o', chatKey, messages);
-
- const operationState = useOperationState(context);
-
const leftContent = useMemo(
() => (
<ActionBarContext value={COMPACT_ACTION_BAR_CONTEXT}>
<Flexbox horizontal align={'center'} gap={2}>
+ <AgentSelectorAction onAgentChange={handleAgentChange} />
<Search />
</Flexbox>
</ActionBarContext>
),
- [],
+ [handleAgentChange],
);
const modelSelector = useMemo(() => <CopilotModelSelect />, []);
return (
- <ConversationProvider
- context={context}
- hasInitMessages={!!messages}
- hooks={HOOKS}
- messages={messages}
- operationState={operationState}
- onMessagesChange={(msgs, ctx) => {
- replaceMessages(msgs, { context: ctx });
- }}
- >
- <DragUploadZone style={{ flex: 1, height: '100%' }} onUploadFiles={handleUploadFiles}>
- <Flexbox flex={1} height={'100%'} style={{ overflow: 'hidden' }}>
- <Toolbar />
- <Flexbox flex={1} style={{ overflow: 'hidden' }}>
- <ChatList welcome={<Welcome />} />
- </Flexbox>
- <ChatInput
- actionBarStyle={COMPACT_ACTION_BAR_STYLE}
- allowExpand={false}
- leftActions={EMPTY_LEFT_ACTIONS}
- leftContent={leftContent}
- sendAreaPrefix={modelSelector}
- sendButtonProps={COMPACT_SEND_BUTTON_PROPS}
- showRuntimeConfig={false}
- />
+ <DragUploadZone style={{ flex: 1, height: '100%' }} onUploadFiles={handleUploadFiles}>
+ <Flexbox flex={1} height={'100%'} style={{ overflow: 'hidden' }}>
+ <Toolbar />
+ <Flexbox flex={1} style={{ overflow: 'hidden' }}>
+ <ChatList welcome={<Welcome />} />
</Flexbox>
- </DragUploadZone>
- </ConversationProvider>
+ <ChatInput
+ actionBarStyle={COMPACT_ACTION_BAR_STYLE}
+ allowExpand={false}
+ leftActions={EMPTY_LEFT_ACTIONS}
+ leftContent={leftContent}
+ sendAreaPrefix={modelSelector}
+ sendButtonProps={COMPACT_SEND_BUTTON_PROPS}
+ showRuntimeConfig={false}
+ />
+ </Flexbox>
+ </DragUploadZone>
);
});
diff --git a/src/features/AgentTaskManager/TaskAgentProvider.test.tsx b/src/features/AgentTaskManager/TaskAgentProvider.test.tsx
new file mode 100644
index 00000000000..bd5b19d8cca
--- /dev/null
+++ b/src/features/AgentTaskManager/TaskAgentProvider.test.tsx
@@ -0,0 +1,164 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';
+import { render, waitFor } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { TaskAgentProvider } from './TaskAgentProvider';
+
+const mocks = vi.hoisted(() => {
+ const agentState = {
+ activeAgentId: undefined as string | undefined,
+ builtinAgentIdMap: {
+ 'task-agent': 'agt_task',
+ 'inbox': 'agt_inbox',
+ },
+ setActiveAgentId: vi.fn((id: string) => {
+ agentState.activeAgentId = id;
+ }),
+ };
+
+ const chatState = {
+ activeTopicId: null as string | null | undefined,
+ dbMessagesMap: {} as Record<string, unknown[]>,
+ replaceMessages: vi.fn(),
+ switchTopic: vi.fn((id: string | null) => {
+ chatState.activeTopicId = id;
+ return Promise.resolve();
+ }),
+ };
+
+ return {
+ agentState,
+ chatState,
+ initBuiltinAgent: vi.fn(),
+ operationState: undefined,
+ providerContexts: [] as any[],
+ routeMatch: undefined as { params: { taskId?: string } } | undefined,
+ };
+});
+
+vi.mock('@/components/Loading/BrandTextLoading', () => ({
+ default: ({ debugId }: { debugId: string }) => <div data-testid="loading">{debugId}</div>,
+}));
+
+vi.mock('@/features/Conversation', () => ({
+ ConversationProvider: ({ children, context }: { children: ReactNode; context: any }) => {
+ mocks.providerContexts.push(context);
+ return <div data-testid="conversation-provider">{children}</div>;
+ },
+}));
+
+vi.mock('@/hooks/useInitBuiltinAgent', () => ({
+ useInitBuiltinAgent: (slug: string) => mocks.initBuiltinAgent(slug),
+}));
+
+vi.mock('@/hooks/useOperationState', () => ({
+ useOperationState: () => mocks.operationState,
+}));
+
+vi.mock('@/store/agent', () => ({
+ useAgentStore: Object.assign(
+ (selector: (state: typeof mocks.agentState) => unknown) => {
+ return selector(mocks.agentState);
+ },
+ {
+ getState: () => mocks.agentState,
+ },
+ ),
+}));
+
+vi.mock('@/store/chat', () => ({
+ useChatStore: Object.assign(
+ (selector: (state: typeof mocks.chatState) => unknown) => {
+ return selector(mocks.chatState);
+ },
+ {
+ getState: () => mocks.chatState,
+ setState: (partial: Partial<typeof mocks.chatState>) => {
+ Object.assign(mocks.chatState, partial);
+ },
+ },
+ ),
+}));
+
+vi.mock('react-router-dom', () => ({
+ useMatch: () => mocks.routeMatch,
+}));
+
+describe('TaskAgentProvider', () => {
+ beforeEach(() => {
+ mocks.agentState.activeAgentId = undefined;
+ mocks.agentState.setActiveAgentId.mockClear();
+ mocks.chatState.activeTopicId = null;
+ mocks.chatState.dbMessagesMap = {};
+ mocks.chatState.replaceMessages.mockClear();
+ mocks.chatState.switchTopic.mockClear();
+ mocks.initBuiltinAgent.mockClear();
+ mocks.providerContexts = [];
+ mocks.routeMatch = undefined;
+ });
+
+ it('initializes builtin agents and builds task list context', () => {
+ render(
+ <TaskAgentProvider>
+ <div>content</div>
+ </TaskAgentProvider>,
+ );
+
+ expect(mocks.initBuiltinAgent).toHaveBeenCalledWith(BUILTIN_AGENT_SLUGS.inbox);
+ expect(mocks.initBuiltinAgent).toHaveBeenCalledWith(BUILTIN_AGENT_SLUGS.taskAgent);
+ expect(mocks.providerContexts.at(-1)).toMatchObject({
+ agentId: 'agt_task',
+ defaultTaskAssigneeAgentId: 'agt_inbox',
+ scope: 'task',
+ topicId: null,
+ viewedTask: { type: 'list' },
+ });
+ });
+
+ it('forwards the viewed task detail context from the route', () => {
+ mocks.routeMatch = { params: { taskId: 'T-1' } };
+
+ render(
+ <TaskAgentProvider>
+ <div>content</div>
+ </TaskAgentProvider>,
+ );
+
+ expect(mocks.providerContexts.at(-1)?.viewedTask).toEqual({ taskId: 'T-1', type: 'detail' });
+ });
+
+ it('clears a stale topic only once for the selected agent', async () => {
+ mocks.chatState.activeTopicId = 'tpc_stale';
+
+ const { rerender } = render(
+ <TaskAgentProvider>
+ <div>content</div>
+ </TaskAgentProvider>,
+ );
+
+ await waitFor(() => {
+ expect(mocks.chatState.switchTopic).toHaveBeenCalledWith(null, {
+ scope: 'task',
+ skipRefreshMessage: true,
+ });
+ });
+
+ mocks.chatState.switchTopic.mockClear();
+ mocks.chatState.activeTopicId = 'tpc_created';
+
+ rerender(
+ <TaskAgentProvider>
+ <div>content</div>
+ </TaskAgentProvider>,
+ );
+
+ await waitFor(() => {
+ expect(mocks.providerContexts.at(-1)?.topicId).toBe('tpc_created');
+ });
+ expect(mocks.chatState.switchTopic).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/features/AgentTaskManager/TaskAgentProvider.tsx b/src/features/AgentTaskManager/TaskAgentProvider.tsx
new file mode 100644
index 00000000000..7807597ace0
--- /dev/null
+++ b/src/features/AgentTaskManager/TaskAgentProvider.tsx
@@ -0,0 +1,91 @@
+import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';
+import type { ConversationContext } from '@lobechat/types';
+import { isChatGroupSessionId } from '@lobechat/types';
+import type { ReactNode } from 'react';
+import { memo, useEffect, useMemo, useRef } from 'react';
+import { useMatch } from 'react-router-dom';
+
+import Loading from '@/components/Loading/BrandTextLoading';
+import { ConversationProvider } from '@/features/Conversation';
+import { useInitBuiltinAgent } from '@/hooks/useInitBuiltinAgent';
+import { useOperationState } from '@/hooks/useOperationState';
+import { useAgentStore } from '@/store/agent';
+import { builtinAgentSelectors } from '@/store/agent/selectors';
+import { useChatStore } from '@/store/chat';
+import { messageMapKey } from '@/store/chat/utils/messageMapKey';
+
+interface TaskAgentProviderProps {
+ children: ReactNode;
+}
+
+export const TaskAgentProvider = memo<TaskAgentProviderProps>(({ children }) => {
+ useInitBuiltinAgent(BUILTIN_AGENT_SLUGS.inbox);
+ useInitBuiltinAgent(BUILTIN_AGENT_SLUGS.taskAgent);
+
+ const inboxAgentId = useAgentStore(builtinAgentSelectors.inboxAgentId);
+ const taskAgentId = useAgentStore(builtinAgentSelectors.taskAgentId);
+ const activeAgentId = useAgentStore((s) => s.activeAgentId);
+ const setActiveAgentId = useAgentStore((s) => s.setActiveAgentId);
+ const activeTopicId = useChatStore((s) => s.activeTopicId);
+ const syncedAgentIdRef = useRef<string | undefined>(undefined);
+
+ const detailMatch = useMatch('/task/:taskId');
+ const viewedTaskId = detailMatch?.params.taskId;
+
+ const selectedAgentId =
+ !activeAgentId || isChatGroupSessionId(activeAgentId) ? taskAgentId : activeAgentId;
+
+ useEffect(() => {
+ if (!selectedAgentId) return;
+
+ if (useAgentStore.getState().activeAgentId !== selectedAgentId) {
+ setActiveAgentId(selectedAgentId);
+ }
+
+ const chatState = useChatStore.getState();
+ if (chatState.activeAgentId !== selectedAgentId) {
+ useChatStore.setState({ activeAgentId: selectedAgentId });
+ }
+
+ if (syncedAgentIdRef.current === selectedAgentId) return;
+ syncedAgentIdRef.current = selectedAgentId;
+
+ if (chatState.activeTopicId) {
+ void chatState.switchTopic(null, { scope: 'task', skipRefreshMessage: true });
+ }
+ }, [selectedAgentId, setActiveAgentId]);
+
+ const context = useMemo<ConversationContext>(
+ () => ({
+ agentId: selectedAgentId || '',
+ defaultTaskAssigneeAgentId: inboxAgentId,
+ scope: 'task',
+ topicId: activeTopicId,
+ viewedTask: viewedTaskId ? { taskId: viewedTaskId, type: 'detail' } : { type: 'list' },
+ }),
+ [activeTopicId, inboxAgentId, selectedAgentId, viewedTaskId],
+ );
+
+ const chatKey = useMemo(() => messageMapKey(context), [context]);
+ const replaceMessages = useChatStore((s) => s.replaceMessages);
+ const messages = useChatStore((s) => s.dbMessagesMap[chatKey]);
+ const operationState = useOperationState(context);
+
+ if (!taskAgentId) return <Loading debugId="TaskAgentProvider" />;
+
+ return (
+ <ConversationProvider
+ context={context}
+ hasInitMessages={!!messages}
+ messages={messages}
+ operationState={operationState}
+ onMessagesChange={(msgs, ctx) => {
+ replaceMessages(msgs, { context: ctx });
+ }}
+ >
+ {children}
+ </ConversationProvider>
+ );
+});
+
+TaskAgentProvider.displayName = 'TaskAgentProvider';
diff --git a/src/features/AgentTaskManager/Toolbar.tsx b/src/features/AgentTaskManager/Toolbar.tsx
index 8cb7e92d31a..3af423da2cb 100644
--- a/src/features/AgentTaskManager/Toolbar.tsx
+++ b/src/features/AgentTaskManager/Toolbar.tsx
@@ -4,31 +4,35 @@ import { memo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { DESKTOP_HEADER_ICON_SIZE } from '@/const/layoutTokens';
-import { TASK_MANAGER_INCLUDE_TRIGGERS } from '@/const/topic';
import { conversationSelectors, useConversationStore } from '@/features/Conversation';
import NavHeader from '@/features/NavHeader';
import TopicItem from '@/features/PageEditor/Copilot/TopicSelector/TopicItem';
+import { useChatStore } from '@/store/chat';
+import { topicSelectors } from '@/store/chat/slices/topic/selectors';
import { useGlobalStore } from '@/store/global';
-import { useTaskChatStore } from '@/store/taskChat';
const Toolbar = memo(() => {
const { t } = useTranslation('topic');
const [topicPopoverOpen, setTopicPopoverOpen] = useState(false);
const agentId = useConversationStore(conversationSelectors.agentId);
- useTaskChatStore((s) => s.useFetchTopics)(agentId, TASK_MANAGER_INCLUDE_TRIGGERS);
+ useChatStore((s) => s.useFetchTopics)(true, { agentId });
- const [activeTopicId, switchTopic] = useTaskChatStore((s) => [s.activeTopicId, s.switchTopic]);
- const topics = useTaskChatStore((s) => s.topics);
+ const [activeTopicId, switchTopic, topics] = useChatStore((s) => [
+ s.activeTopicId,
+ s.switchTopic,
+ topicSelectors.currentTopics(s),
+ ]);
+ const currentTopic = useChatStore(topicSelectors.currentActiveTopic);
const toggleTaskAgentPanel = useGlobalStore((s) => s.toggleTaskAgentPanel);
const isLoadingTopics = topics === undefined;
- const topicTitle = topics?.find((topic) => topic.id === activeTopicId)?.title || t('title');
+ const topicTitle = currentTopic?.title || t('title');
const hasTopics = !!topics && topics.length > 0;
const handleCreate = () => {
- switchTopic(null);
+ switchTopic(null, { scope: 'task' });
};
return (
@@ -76,11 +80,6 @@ const Toolbar = memo(() => {
topicTitle={topic.title}
onClose={() => setTopicPopoverOpen(false)}
onTopicChange={(id) => switchTopic(id)}
- onDelete={(deletedId) => {
- const store = useTaskChatStore.getState();
- void store.refreshTopics();
- if (store.activeTopicId === deletedId) store.switchTopic(null);
- }}
/>
))}
</Flexbox>
diff --git a/src/features/AgentTaskManager/index.tsx b/src/features/AgentTaskManager/index.tsx
index ea44b26984b..8536e38acc6 100644
--- a/src/features/AgentTaskManager/index.tsx
+++ b/src/features/AgentTaskManager/index.tsx
@@ -5,6 +5,7 @@ import { useGlobalStore } from '@/store/global';
import { systemStatusSelectors } from '@/store/global/selectors';
import Conversation from './Conversation';
+import { TaskAgentProvider } from './TaskAgentProvider';
const AgentTaskManager = memo(() => {
const [expand, toggleTaskAgentPanel] = useGlobalStore((s) => [
@@ -20,7 +21,9 @@ const AgentTaskManager = memo(() => {
minWidth={320}
onExpandChange={(next) => toggleTaskAgentPanel(next)}
>
- <Conversation />
+ <TaskAgentProvider>
+ <Conversation />
+ </TaskAgentProvider>
</RightPanel>
);
});
diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskDetailPage.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskDetailPage.tsx
index 79d0d9f3603..dea88a06e85 100644
--- a/src/features/AgentTasks/AgentTaskDetail/TaskDetailPage.tsx
+++ b/src/features/AgentTasks/AgentTaskDetail/TaskDetailPage.tsx
@@ -6,7 +6,6 @@ import Loading from '@/components/Loading/BrandTextLoading';
import NavHeader from '@/features/NavHeader';
import ToggleRightPanelButton from '@/features/RightPanel/ToggleRightPanelButton';
import WideScreenContainer from '@/features/WideScreenContainer';
-import { useChatStore } from '@/store/chat';
import { useGlobalStore } from '@/store/global';
import { systemStatusSelectors } from '@/store/global/selectors';
import { useTaskStore } from '@/store/task';
@@ -28,11 +27,10 @@ import TaskSubtasks from './TaskSubtasks';
import TopicChatDrawer from './TopicChatDrawer';
interface TaskDetailPageProps {
- agentId?: string;
taskId: string;
}
-const TaskDetailPage = memo<TaskDetailPageProps>(({ agentId, taskId }) => {
+const TaskDetailPage = memo<TaskDetailPageProps>(({ taskId }) => {
const setActiveTaskId = useTaskStore((s) => s.setActiveTaskId);
const useFetchTaskDetail = useTaskStore((s) => s.useFetchTaskDetail);
const isLoading = useTaskStore(taskDetailSelectors.isTaskDetailLoading);
@@ -48,19 +46,6 @@ const TaskDetailPage = memo<TaskDetailPageProps>(({ agentId, taskId }) => {
return () => setActiveTaskId(undefined);
}, [taskId, setActiveTaskId]);
- // Sync the task's assignee agent into chat store so the right-side
- // AgentTaskManager conversation knows which agent to talk to.
- useEffect(() => {
- if (!agentId) return;
- useChatStore.setState({ activeAgentId: agentId }, false, 'TaskDetailPage/syncAgentId');
- return () => {
- const current = useChatStore.getState().activeAgentId;
- if (current === agentId) {
- useChatStore.setState({ activeAgentId: undefined }, false, 'TaskDetailPage/clearAgentId');
- }
- };
- }, [agentId]);
-
useFetchTaskDetail(taskId);
return (
diff --git a/src/features/AgentTasks/features/AgentTaskCardList.tsx b/src/features/AgentTasks/features/AgentTaskCardList.tsx
index 412fe985169..231a2c1f5e7 100644
--- a/src/features/AgentTasks/features/AgentTaskCardList.tsx
+++ b/src/features/AgentTasks/features/AgentTaskCardList.tsx
@@ -4,6 +4,7 @@ import { Fragment, memo, useCallback, useMemo } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAgentStore } from '@/store/agent';
+import { featureFlagsSelectors, useServerConfigStore } from '@/store/serverConfig';
import { useTaskStore } from '@/store/task';
import { taskListSelectors } from '@/store/task/selectors';
@@ -14,8 +15,9 @@ import TaskListHeader from './TaskListHeader';
const AgentTaskCardList = memo(() => {
const agentId = useAgentStore((s) => s.activeAgentId);
const navigate = useNavigate();
+ const { enableAgentTask } = useServerConfigStore(featureFlagsSelectors);
const useFetchTaskList = useTaskStore((s) => s.useFetchTaskList);
- useFetchTaskList({ agentId });
+ useFetchTaskList({ agentId, enabled: !!enableAgentTask });
const tasks = useTaskStore(taskListSelectors.taskList);
const isInit = useTaskStore(taskListSelectors.isTaskListInit);
@@ -27,6 +29,7 @@ const AgentTaskCardList = memo(() => {
const visibleTasks = useMemo(() => getVisibleTaskCardTasks(tasks), [tasks]);
const displayTasks = useMemo(() => getDisplayTaskCardTasks(tasks), [tasks]);
+ if (!enableAgentTask) return null;
if (!isInit || visibleTasks.length === 0) return null;
return (
diff --git a/src/helpers/toolEngineering/index.ts b/src/helpers/toolEngineering/index.ts
index f3de109d14f..5a457e9b245 100644
--- a/src/helpers/toolEngineering/index.ts
+++ b/src/helpers/toolEngineering/index.ts
@@ -14,7 +14,6 @@ import { type ChatCompletionTool, type ToolManifest, type WorkingModel } from '@
import { isToolAvailableInCurrentEnv } from '@/helpers/toolAvailability';
import { getAgentStoreState } from '@/store/agent';
import { agentChatConfigSelectors, agentSelectors } from '@/store/agent/selectors';
-import { getChatStoreState } from '@/store/chat';
import { getToolStoreState } from '@/store/tool';
import {
klavisStoreSelectors,
@@ -126,11 +125,6 @@ export const createAgentToolsEngine = (
const searchConfig = getSearchConfig(workingModel.model, workingModel.provider);
const agentState = getAgentStoreState();
const userPlugins = agentSelectors.currentAgentPlugins(agentState);
- // Page-level scenario-enabled tool ids (e.g. tasks page enables `lobe-task`).
- // Set by page layouts via `useChatStore.setState({ scenarioEnabledToolIds })`,
- // cleared on unmount. Only effective when the id is also in `defaultToolIds`
- // or `pluginIds` — rules only apply to tools that reach the candidate pool.
- const scenarioEnabledToolIds = getChatStoreState().scenarioEnabledToolIds ?? [];
return createToolsEngine({
defaultToolIds,
@@ -158,8 +152,6 @@ export const createAgentToolsEngine = (
...Object.fromEntries(userPlugins.map((id) => [id, true])),
// Always-on builtin tools
...Object.fromEntries(alwaysOnToolIds.map((id) => [id, true])),
- // Page-level scenario-enabled tools (e.g. tasks page enables `lobe-task`)
- ...Object.fromEntries(scenarioEnabledToolIds.map((id) => [id, true])),
// System-level rules (may override user selection for specific tools)
[CloudSandboxManifest.identifier]:
agentChatConfigSelectors.isCloudSandboxEnabled(agentState),
diff --git a/src/hooks/useScenarioEnabledTools.ts b/src/hooks/useScenarioEnabledTools.ts
deleted file mode 100644
index 448101d62ae..00000000000
--- a/src/hooks/useScenarioEnabledTools.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-import { useEffect, useRef } from 'react';
-
-import { useChatStore } from '@/store/chat';
-
-/**
- * Enables the given built-in tools for any LLM step triggered while this hook is
- * mounted, then resets on unmount. Use from a route-level layout/page to scope
- * tool availability to a specific view.
- */
-export const useScenarioEnabledTools = (...toolIds: string[]) => {
- const key = toolIds.join('|');
- const toolsRef = useRef(toolIds);
- toolsRef.current = toolIds;
-
- useEffect(() => {
- useChatStore.setState({ scenarioEnabledToolIds: toolsRef.current });
- return () => {
- useChatStore.setState({ scenarioEnabledToolIds: undefined });
- };
- }, [key]);
-};
diff --git a/src/locales/default/topic.ts b/src/locales/default/topic.ts
index 76e1a589720..05c398065cc 100644
--- a/src/locales/default/topic.ts
+++ b/src/locales/default/topic.ts
@@ -59,6 +59,7 @@ export default {
'renameModal.title': 'Rename Topic',
'searchPlaceholder': 'Search Topics...',
'searchResultEmpty': 'No search results found.',
+ 'taskManager.agent': 'Task Agent',
'taskManager.welcome': 'Ask me about your tasks',
'temp': 'Temporary',
'title': 'Topic',
diff --git a/src/routes/(main)/task/[taskId]/index.tsx b/src/routes/(main)/task/[taskId]/index.tsx
index 55c339cad55..09ab6838b26 100644
--- a/src/routes/(main)/task/[taskId]/index.tsx
+++ b/src/routes/(main)/task/[taskId]/index.tsx
@@ -4,18 +4,13 @@ import { memo } from 'react';
import { useParams } from 'react-router-dom';
import { TaskDetailPage } from '@/features/AgentTasks';
-import { useTaskStore } from '@/store/task';
const TaskDetailRoute = memo(() => {
const { taskId } = useParams<{ taskId?: string }>();
- const agentId = useTaskStore((s) =>
- taskId ? (s.taskDetailMap[taskId]?.agentId ?? undefined) : undefined,
- );
-
if (!taskId) return null;
- return <TaskDetailPage agentId={agentId} taskId={taskId} />;
+ return <TaskDetailPage taskId={taskId} />;
});
export default TaskDetailRoute;
diff --git a/src/routes/(main)/task/_layout/index.tsx b/src/routes/(main)/task/_layout/index.tsx
index 31168aed20c..a7dfadbd024 100644
--- a/src/routes/(main)/task/_layout/index.tsx
+++ b/src/routes/(main)/task/_layout/index.tsx
@@ -1,16 +1,15 @@
'use client';
-import { TaskIdentifier } from '@lobechat/builtin-tool-task';
import { Flexbox } from '@lobehub/ui';
import { memo } from 'react';
import { Navigate, Outlet } from 'react-router-dom';
import AgentTaskManager from '@/features/AgentTaskManager';
-import { useScenarioEnabledTools } from '@/hooks/useScenarioEnabledTools';
+import { useIsMobile } from '@/hooks/useIsMobile';
import { featureFlagsSelectors, useServerConfigStore } from '@/store/serverConfig';
const TaskDetailLayout = memo(() => {
- useScenarioEnabledTools(TaskIdentifier);
+ const isMobile = useIsMobile();
const serverConfigInit = useServerConfigStore((s) => s.serverConfigInit);
const { enableAgentTask } = useServerConfigStore(featureFlagsSelectors);
@@ -19,11 +18,11 @@ const TaskDetailLayout = memo(() => {
}
return (
- <Flexbox horizontal flex={1} height={'100%'} width={'100%'}>
+ <Flexbox flex={1} height={'100%'} horizontal={!isMobile} width={'100%'}>
<Flexbox flex={1} style={{ minWidth: 0 }}>
<Outlet />
</Flexbox>
- <AgentTaskManager />
+ {!isMobile && <AgentTaskManager />}
</Flexbox>
);
});
diff --git a/src/routes/(main)/tasks/_layout/index.tsx b/src/routes/(main)/tasks/_layout/index.tsx
index e2fc5ba8fc0..48372fde926 100644
--- a/src/routes/(main)/tasks/_layout/index.tsx
+++ b/src/routes/(main)/tasks/_layout/index.tsx
@@ -1,15 +1,15 @@
'use client';
-import { TaskIdentifier } from '@lobechat/builtin-tool-task';
import { Flexbox } from '@lobehub/ui';
import { memo } from 'react';
import { Navigate, Outlet } from 'react-router-dom';
-import { useScenarioEnabledTools } from '@/hooks/useScenarioEnabledTools';
+import AgentTaskManager from '@/features/AgentTaskManager';
+import { useIsMobile } from '@/hooks/useIsMobile';
import { featureFlagsSelectors, useServerConfigStore } from '@/store/serverConfig';
const AllTasksLayout = memo(() => {
- useScenarioEnabledTools(TaskIdentifier);
+ const isMobile = useIsMobile();
const serverConfigInit = useServerConfigStore((s) => s.serverConfigInit);
const { enableAgentTask } = useServerConfigStore(featureFlagsSelectors);
@@ -18,8 +18,11 @@ const AllTasksLayout = memo(() => {
}
return (
- <Flexbox flex={1} height={'100%'} width={'100%'}>
- <Outlet />
+ <Flexbox flex={1} height={'100%'} horizontal={!isMobile} width={'100%'}>
+ <Flexbox flex={1} style={{ minWidth: 0 }}>
+ <Outlet />
+ </Flexbox>
+ {!isMobile && <AgentTaskManager />}
</Flexbox>
);
});
diff --git a/src/server/routers/lambda/__tests__/integration/task.integration.test.ts b/src/server/routers/lambda/__tests__/integration/task.integration.test.ts
index 4d83ea72b8a..2d2f848a573 100644
--- a/src/server/routers/lambda/__tests__/integration/task.integration.test.ts
+++ b/src/server/routers/lambda/__tests__/integration/task.integration.test.ts
@@ -54,6 +54,7 @@ vi.mock('@/server/modules/ModelRuntime', () => ({
describe('Task Router Integration', () => {
let serverDB: LobeChatDatabase;
let userId: string;
+ let otherUserId: string | undefined;
let testAgentId: string;
let testTopicId: string;
let caller: ReturnType<typeof taskRouter.createCaller>;
@@ -76,6 +77,8 @@ describe('Task Router Integration', () => {
afterEach(async () => {
await cleanupTestUser(serverDB, userId);
+ if (otherUserId) await cleanupTestUser(serverDB, otherUserId);
+ otherUserId = undefined;
});
describe('create + find + detail', () => {
@@ -123,6 +126,35 @@ describe('Task Router Integration', () => {
expect(result.data.createdByAgentId).toBeNull();
expect(result.data.createdByUserId).toBe(userId);
});
+
+ it('should reject assigneeAgentId from another user when creating', async () => {
+ otherUserId = await createTestUser(serverDB);
+ const otherAgentId = await createTestAgent(serverDB, otherUserId);
+
+ await expect(
+ caller.create({
+ assigneeAgentId: otherAgentId,
+ instruction: 'Cross-user assignment',
+ name: 'Cross-user Task',
+ }),
+ ).rejects.toThrow('Assignee agent not found');
+ });
+
+ it('should reject assigneeAgentId from another user when updating', async () => {
+ otherUserId = await createTestUser(serverDB);
+ const otherAgentId = await createTestAgent(serverDB, otherUserId);
+ const task = await caller.create({
+ instruction: 'Created via UI',
+ name: 'UI Task',
+ });
+
+ await expect(
+ caller.update({
+ assigneeAgentId: otherAgentId,
+ id: task.data.id,
+ }),
+ ).rejects.toThrow('Assignee agent not found');
+ });
});
describe('subtasks + dependencies', () => {
diff --git a/src/server/routers/lambda/aiAgent.ts b/src/server/routers/lambda/aiAgent.ts
index 47a032a4fcb..4f50cc77501 100644
--- a/src/server/routers/lambda/aiAgent.ts
+++ b/src/server/routers/lambda/aiAgent.ts
@@ -137,10 +137,12 @@ const ExecAgentSchema = z
/** Application context for message storage */
appContext: z
.object({
+ defaultTaskAssigneeAgentId: z.string().optional(),
documentId: z.string().optional().nullable(),
groupId: z.string().optional().nullable(),
scope: z.string().optional().nullable(),
sessionId: z.string().optional(),
+ taskId: z.string().optional().nullable(),
threadId: z.string().optional().nullable(),
topicId: z.string().optional().nullable(),
})
diff --git a/src/server/routers/lambda/task.ts b/src/server/routers/lambda/task.ts
index 28f696e4292..151367ae00a 100644
--- a/src/server/routers/lambda/task.ts
+++ b/src/server/routers/lambda/task.ts
@@ -97,6 +97,21 @@ async function resolveOrThrow(model: TaskModel, id: string) {
return task;
}
+async function assertAssigneeAgentBelongsToUser(
+ model: AgentModel,
+ assigneeAgentId?: string | null,
+) {
+ if (!assigneeAgentId) return;
+
+ const exists = await model.existsById(assigneeAgentId);
+ if (!exists) {
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message: 'Assignee agent not found',
+ });
+ }
+}
+
export const taskRouter = router({
reorderSubtasks: taskProcedure
.input(
@@ -318,6 +333,7 @@ export const taskRouter = router({
create: taskProcedure.input(createSchema).mutation(async ({ input, ctx }) => {
try {
const model = ctx.taskModel;
+ await assertAssigneeAgentBelongsToUser(ctx.agentModel, input.assigneeAgentId);
// Resolve parentTaskId if it's an identifier
const createData = { ...input };
@@ -930,6 +946,7 @@ export const taskRouter = router({
const { id, ...data } = input;
try {
const model = ctx.taskModel;
+ await assertAssigneeAgentBelongsToUser(ctx.agentModel, data.assigneeAgentId);
const resolved = await resolveOrThrow(model, id);
const task = await model.update(resolved.id, data);
if (!task) throw new TRPCError({ code: 'NOT_FOUND', message: 'Task not found' });
diff --git a/src/server/services/agentRuntime/types.ts b/src/server/services/agentRuntime/types.ts
index 25a64893ecc..3c91f768227 100644
--- a/src/server/services/agentRuntime/types.ts
+++ b/src/server/services/agentRuntime/types.ts
@@ -149,6 +149,7 @@ export interface OperationCreationParams {
agentConfig?: any;
appContext: {
agentId?: string;
+ defaultTaskAssigneeAgentId?: string;
documentId?: string | null;
groupId?: string | null;
scope?: string | null;
diff --git a/src/server/services/aiAgent/__tests__/execAgent.builtinRuntime.test.ts b/src/server/services/aiAgent/__tests__/execAgent.builtinRuntime.test.ts
index b103d914ffd..f1e8eab409c 100644
--- a/src/server/services/aiAgent/__tests__/execAgent.builtinRuntime.test.ts
+++ b/src/server/services/aiAgent/__tests__/execAgent.builtinRuntime.test.ts
@@ -6,11 +6,14 @@ import { createServerAgentToolsEngine } from '@/server/modules/Mecha';
import { AiAgentService } from '../index';
-const { mockCreateOperation, mockGetAgentConfig, mockMessageCreate } = vi.hoisted(() => ({
- mockCreateOperation: vi.fn(),
- mockGetAgentConfig: vi.fn(),
- mockMessageCreate: vi.fn(),
-}));
+const { mockCreateOperation, mockGetAgentConfig, mockMessageCreate, mockResolveTask } = vi.hoisted(
+ () => ({
+ mockCreateOperation: vi.fn(),
+ mockGetAgentConfig: vi.fn(),
+ mockMessageCreate: vi.fn(),
+ mockResolveTask: vi.fn(),
+ }),
+);
vi.mock('@/libs/trusted-client', () => ({
generateTrustedClientToken: vi.fn().mockReturnValue(undefined),
@@ -59,6 +62,12 @@ vi.mock('@/database/models/thread', () => ({
})),
}));
+vi.mock('@/database/models/task', () => ({
+ TaskModel: vi.fn().mockImplementation(() => ({
+ resolve: mockResolveTask,
+ })),
+}));
+
vi.mock('@/server/services/agentRuntime', () => ({
AgentRuntimeService: vi.fn().mockImplementation(() => ({
createOperation: mockCreateOperation,
@@ -120,6 +129,7 @@ describe('AiAgentService.execAgent - builtin agent runtime config', () => {
beforeEach(() => {
vi.clearAllMocks();
mockMessageCreate.mockResolvedValue({ id: 'msg-1' });
+ mockResolveTask.mockResolvedValue(null);
mockCreateOperation.mockResolvedValue({
autoStarted: true,
messageId: 'queue-msg-1',
@@ -255,4 +265,39 @@ describe('AiAgentService.execAgent - builtin agent runtime config', () => {
}),
);
});
+
+ it('should normalize task identifier from appContext before creating runtime operation', async () => {
+ mockResolveTask.mockResolvedValue({ id: 'task-row-1', identifier: 'T-1' });
+ mockGetAgentConfig.mockResolvedValue({
+ chatConfig: {},
+ id: 'agent-task',
+ model: 'gpt-4',
+ plugins: [],
+ provider: 'openai',
+ systemRole: '',
+ });
+
+ await service.execAgent({
+ agentId: 'agent-task',
+ appContext: {
+ defaultTaskAssigneeAgentId: 'agt_inbox',
+ scope: 'task',
+ taskId: 'T-1',
+ topicId: 'topic-1',
+ },
+ prompt: 'Show current task',
+ });
+
+ const callArgs = mockCreateOperation.mock.calls[0][0];
+ expect(mockResolveTask).toHaveBeenCalledWith('T-1');
+ expect(callArgs.appContext).toMatchObject({
+ defaultTaskAssigneeAgentId: 'agt_inbox',
+ scope: 'task',
+ taskId: 'task-row-1',
+ topicId: 'topic-1',
+ });
+ expect(callArgs.initialContext.initialContext.taskManager.contextPrompt).toContain(
+ 'Default Lobe AI agent id: agt_inbox',
+ );
+ });
});
diff --git a/src/server/services/aiAgent/index.ts b/src/server/services/aiAgent/index.ts
index ce399da382a..79036fc634d 100644
--- a/src/server/services/aiAgent/index.ts
+++ b/src/server/services/aiAgent/index.ts
@@ -9,6 +9,7 @@ import {
generateSystemPrompt,
RemoteDeviceManifest,
} from '@lobechat/builtin-tool-remote-device';
+import { TaskIdentifier } from '@lobechat/builtin-tool-task';
import { builtinTools, manualModeExcludeToolIds } from '@lobechat/builtin-tools';
import { LOADING_FLAT } from '@lobechat/const';
import type {
@@ -19,6 +20,7 @@ import type {
} from '@lobechat/context-engine';
import { SkillEngine } from '@lobechat/context-engine';
import type { LobeChatDatabase } from '@lobechat/database';
+import { buildTaskManagerDefaultsPrompt } from '@lobechat/prompts';
import type {
ChatFileItem,
ChatTopicBotContext,
@@ -42,6 +44,7 @@ import { AiModelModel } from '@/database/models/aiModel';
import { FileModel } from '@/database/models/file';
import { MessageModel } from '@/database/models/message';
import { PluginModel } from '@/database/models/plugin';
+import { TaskModel } from '@/database/models/task';
import { ThreadModel } from '@/database/models/thread';
import { TopicModel } from '@/database/models/topic';
import { UserModel } from '@/database/models/user';
@@ -195,6 +198,7 @@ export class AiAgentService {
private readonly agentService: AgentService;
private readonly messageModel: MessageModel;
private readonly pluginModel: PluginModel;
+ private readonly taskModel: TaskModel;
private readonly threadModel: ThreadModel;
private readonly topicModel: TopicModel;
private readonly agentRuntimeService: AgentRuntimeService;
@@ -213,6 +217,7 @@ export class AiAgentService {
this.agentService = new AgentService(db, userId);
this.messageModel = new MessageModel(db, userId);
this.pluginModel = new PluginModel(db, userId);
+ this.taskModel = new TaskModel(db, userId);
this.threadModel = new ThreadModel(db, userId);
this.topicModel = new TopicModel(db, userId);
this.agentRuntimeService = new AgentRuntimeService(db, userId, options?.runtimeOptions);
@@ -220,6 +225,17 @@ export class AiAgentService {
this.klavisService = new KlavisService({ db, userId });
}
+ private async resolveOperationTaskId(
+ idOrIdentifier?: string | null,
+ ): Promise<string | undefined> {
+ if (!idOrIdentifier) return;
+
+ // Task detail routes use human-readable identifiers such as `T-1`, while
+ // operation runtimes store this value in FK-backed records.
+ const task = await this.taskModel.resolve(idOrIdentifier);
+ return task?.id;
+ }
+
/**
* Execute agent with just a prompt
*
@@ -281,6 +297,8 @@ export class AiAgentService {
log('execAgent: identifier=%s, prompt=%s', identifier, prompt.slice(0, 50));
+ const operationTaskId = await this.resolveOperationTaskId(taskId ?? appContext?.taskId);
+
const assistantMessageRef: { current?: string } = {};
const updateAbortedAssistantMessage = async (errorMessage: string) => {
if (!assistantMessageRef.current) return;
@@ -385,6 +403,25 @@ export class AiAgentService {
log('execAgent: injected page-agent runtime for page scope');
}
+ if (appContext?.scope === 'task' && agentSlug !== BUILTIN_AGENT_SLUGS.taskAgent) {
+ const taskAgentRuntime = getAgentRuntimeConfig(BUILTIN_AGENT_SLUGS.taskAgent, {
+ model: agentConfig.model,
+ plugins: agentConfig.plugins ?? [],
+ });
+ const taskAgentSystemRole = taskAgentRuntime?.systemRole || '';
+
+ if (taskAgentSystemRole) {
+ agentConfig.systemRole = agentConfig.systemRole
+ ? `${agentConfig.systemRole}\n\n${taskAgentSystemRole}`
+ : taskAgentSystemRole;
+ }
+
+ agentConfig.plugins = agentConfig.plugins?.includes(TaskIdentifier)
+ ? agentConfig.plugins
+ : [TaskIdentifier, ...(agentConfig.plugins ?? [])];
+ log('execAgent: injected task-agent runtime for task scope');
+ }
+
await throwIfExecutionAborted('agent configuration');
// 2.5. Append additional instructions to agent's systemRole
@@ -517,12 +554,12 @@ export class AiAgentService {
// Prepare metadata with cronJobId, taskId, botContext, and bound device if provided
const metadata =
- cronJobId || taskId || botContext || requestedDeviceId
+ cronJobId || operationTaskId || botContext || requestedDeviceId
? {
bot: botContext,
boundDeviceId: requestedDeviceId,
cronJobId: cronJobId || undefined,
- taskId: taskId || undefined,
+ taskId: operationTaskId,
}
: undefined;
@@ -1406,6 +1443,20 @@ export class AiAgentService {
}
}
+ if (appContext?.scope === 'task' && appContext.defaultTaskAssigneeAgentId) {
+ initialContext = {
+ ...initialContext,
+ initialContext: {
+ ...initialContext.initialContext,
+ taskManager: {
+ contextPrompt: buildTaskManagerDefaultsPrompt({
+ defaultAssigneeAgentId: appContext.defaultTaskAssigneeAgentId,
+ }),
+ },
+ },
+ };
+ }
+
// 16b. Human-approval resume — override initialContext based on the
// user's decision. The DB write above has already persisted the
// intervention status, so `allMessages` reflects the decision for the
@@ -1520,10 +1571,11 @@ export class AiAgentService {
userTimezone,
appContext: {
agentId: resolvedAgentId,
+ defaultTaskAssigneeAgentId: appContext?.defaultTaskAssigneeAgentId,
documentId: appContext?.documentId,
groupId: appContext?.groupId,
scope: appContext?.scope,
- taskId,
+ taskId: operationTaskId,
threadId: appContext?.threadId,
topicId,
trigger,
diff --git a/src/server/services/toolExecution/serverRuntimes/__tests__/task.test.ts b/src/server/services/toolExecution/serverRuntimes/__tests__/task.test.ts
index 0dee4e27380..008ae489843 100644
--- a/src/server/services/toolExecution/serverRuntimes/__tests__/task.test.ts
+++ b/src/server/services/toolExecution/serverRuntimes/__tests__/task.test.ts
@@ -1,3 +1,4 @@
+import { normalizeListTasksParams, UNFINISHED_TASK_STATUSES } from '@lobechat/builtin-tool-task';
import { describe, expect, it, vi } from 'vitest';
import { createTaskRuntime } from '../task';
@@ -7,6 +8,59 @@ vi.mock('@/server/routers/lambda/task', () => ({
}));
describe('createTaskRuntime', () => {
+ describe('normalizeListTasksParams', () => {
+ it('defaults to top-level unfinished tasks for the current agent', () => {
+ const result = normalizeListTasksParams({}, { currentAgentId: 'agt-1' });
+
+ expect(result.query).toMatchObject({
+ assigneeAgentId: 'agt-1',
+ parentTaskId: null,
+ statuses: UNFINISHED_TASK_STATUSES,
+ });
+ expect(result.displayFilters).toMatchObject({
+ assigneeAgentId: 'agt-1',
+ isDefaultScope: true,
+ isForCurrentAgent: true,
+ });
+ });
+
+ it('can default to top-level unfinished tasks across all agents', () => {
+ const result = normalizeListTasksParams(
+ {},
+ { currentAgentId: 'agt-1', defaultScope: 'allAgents' },
+ );
+
+ expect(result.query).toMatchObject({
+ assigneeAgentId: undefined,
+ parentTaskId: null,
+ statuses: UNFINISHED_TASK_STATUSES,
+ });
+ expect(result.displayFilters).toMatchObject({
+ isDefaultScope: true,
+ isForAllAgents: true,
+ isForCurrentAgent: false,
+ });
+ });
+
+ it('does not apply implicit assignee when explicit filters are present', () => {
+ const result = normalizeListTasksParams(
+ { statuses: ['completed'] },
+ { currentAgentId: 'agt-1' },
+ );
+
+ expect(result.query).toMatchObject({
+ assigneeAgentId: undefined,
+ parentTaskId: undefined,
+ statuses: ['completed'],
+ });
+ expect(result.displayFilters).toMatchObject({
+ isDefaultScope: false,
+ isForAllAgents: false,
+ isForCurrentAgent: false,
+ });
+ });
+ });
+
describe('createTask', () => {
const fakeTask = {
id: 'task-1',
@@ -17,19 +71,23 @@ describe('createTaskRuntime', () => {
};
const makeDeps = () => {
+ const agentModel = {
+ existsById: vi.fn().mockResolvedValue(true),
+ };
const taskModel = {
create: vi.fn().mockResolvedValue(fakeTask),
resolve: vi.fn(),
};
const taskService = {} as any;
const taskCaller = {} as any;
- return { taskCaller, taskModel, taskService };
+ return { agentModel, taskCaller, taskModel, taskService };
};
it('passes createdByAgentId when invoked by an agent (activity should attribute the agent)', async () => {
const deps = makeDeps();
const runtime = createTaskRuntime({
+ agentModel: deps.agentModel as any,
agentId: 'agt-xyz',
taskCaller: deps.taskCaller,
taskModel: deps.taskModel as any,
@@ -54,6 +112,7 @@ describe('createTaskRuntime', () => {
const deps = makeDeps();
const runtime = createTaskRuntime({
+ agentModel: deps.agentModel as any,
taskCaller: deps.taskCaller,
taskModel: deps.taskModel as any,
taskService: deps.taskService,
@@ -72,11 +131,88 @@ describe('createTaskRuntime', () => {
);
});
+ it('does not default assigneeAgentId in task manager scope', async () => {
+ const deps = makeDeps();
+
+ const runtime = createTaskRuntime({
+ agentModel: deps.agentModel as any,
+ agentId: 'agt-xyz',
+ scope: 'task',
+ taskCaller: deps.taskCaller,
+ taskModel: deps.taskModel as any,
+ taskService: deps.taskService,
+ });
+
+ await runtime.createTask({
+ instruction: 'Do something',
+ name: 'Test',
+ });
+
+ expect(deps.taskModel.create).toHaveBeenCalledWith(
+ expect.objectContaining({
+ assigneeAgentId: undefined,
+ createdByAgentId: 'agt-xyz',
+ }),
+ );
+ });
+
+ it('uses explicit assigneeAgentId in task manager scope', async () => {
+ const deps = makeDeps();
+
+ const runtime = createTaskRuntime({
+ agentModel: deps.agentModel as any,
+ agentId: 'agt-manager',
+ scope: 'task',
+ taskCaller: deps.taskCaller,
+ taskModel: deps.taskModel as any,
+ taskService: deps.taskService,
+ });
+
+ await runtime.createTask({
+ assigneeAgentId: 'agt-worker',
+ instruction: 'Do something',
+ name: 'Test',
+ });
+
+ expect(deps.taskModel.create).toHaveBeenCalledWith(
+ expect.objectContaining({
+ assigneeAgentId: 'agt-worker',
+ createdByAgentId: 'agt-manager',
+ }),
+ );
+ expect(deps.agentModel.existsById).toHaveBeenCalledWith('agt-worker');
+ });
+
+ it('rejects explicit assigneeAgentId that is not owned by the current user', async () => {
+ const deps = makeDeps();
+ deps.agentModel.existsById.mockResolvedValue(false);
+
+ const runtime = createTaskRuntime({
+ agentModel: deps.agentModel as any,
+ agentId: 'agt-manager',
+ scope: 'task',
+ taskCaller: deps.taskCaller,
+ taskModel: deps.taskModel as any,
+ taskService: deps.taskService,
+ });
+
+ const result = await runtime.createTask({
+ assigneeAgentId: 'agt-other-user',
+ instruction: 'Do something',
+ name: 'Test',
+ });
+
+ expect(result.success).toBe(false);
+ expect(result.content).toBe('Assignee agent not found: agt-other-user');
+ expect(deps.taskModel.create).not.toHaveBeenCalled();
+ });
+
it('resolves and uses parentTaskId when parentIdentifier is provided', async () => {
const deps = makeDeps();
deps.taskModel.resolve = vi.fn().mockResolvedValue({ id: 'parent-id', identifier: 'T-99' });
const runtime = createTaskRuntime({
+ agentModel: deps.agentModel as any,
agentId: 'agt-xyz',
taskCaller: deps.taskCaller,
taskModel: deps.taskModel as any,
@@ -102,6 +238,7 @@ describe('createTaskRuntime', () => {
deps.taskModel.resolve = vi.fn().mockResolvedValue(null);
const runtime = createTaskRuntime({
+ agentModel: deps.agentModel as any,
agentId: 'agt-xyz',
taskCaller: deps.taskCaller,
taskModel: deps.taskModel as any,
@@ -118,4 +255,85 @@ describe('createTaskRuntime', () => {
expect(deps.taskModel.create).not.toHaveBeenCalled();
});
});
+
+ describe('editTask', () => {
+ const makeDeps = () => {
+ const agentModel = {
+ existsById: vi.fn().mockResolvedValue(true),
+ };
+ const taskModel = {
+ resolve: vi.fn().mockResolvedValue({ id: 'task-1', identifier: 'T-1' }),
+ update: vi.fn().mockResolvedValue({}),
+ };
+ const taskService = {} as any;
+ const taskCaller = {} as any;
+ return { agentModel, taskCaller, taskModel, taskService };
+ };
+
+ it('rejects explicit assigneeAgentId that is not owned by the current user', async () => {
+ const deps = makeDeps();
+ deps.agentModel.existsById.mockResolvedValue(false);
+
+ const runtime = createTaskRuntime({
+ agentModel: deps.agentModel as any,
+ agentId: 'agt-manager',
+ taskCaller: deps.taskCaller,
+ taskModel: deps.taskModel as any,
+ taskService: deps.taskService,
+ });
+
+ const result = await runtime.editTask({
+ assigneeAgentId: 'agt-other-user',
+ identifier: 'T-1',
+ });
+
+ expect(result.success).toBe(false);
+ expect(result.content).toBe('Assignee agent not found: agt-other-user');
+ expect(deps.taskModel.update).not.toHaveBeenCalled();
+ });
+
+ it('allows clearing assigneeAgentId without ownership lookup', async () => {
+ const deps = makeDeps();
+
+ const runtime = createTaskRuntime({
+ agentModel: deps.agentModel as any,
+ agentId: 'agt-manager',
+ taskCaller: deps.taskCaller,
+ taskModel: deps.taskModel as any,
+ taskService: deps.taskService,
+ });
+
+ const result = await runtime.editTask({
+ assigneeAgentId: null,
+ identifier: 'T-1',
+ });
+
+ expect(result.success).toBe(true);
+ expect(deps.agentModel.existsById).not.toHaveBeenCalled();
+ expect(deps.taskModel.update).toHaveBeenCalledWith('task-1', { assigneeAgentId: null });
+ });
+ });
+
+ describe('listTasks', () => {
+ it('uses all-agent default scope in task manager context', async () => {
+ const taskCaller = { list: vi.fn().mockResolvedValue({ data: [] }) };
+ const runtime = createTaskRuntime({
+ agentModel: { existsById: vi.fn() } as any,
+ agentId: 'agt-xyz',
+ scope: 'task',
+ taskCaller: taskCaller as any,
+ taskModel: {} as any,
+ taskService: {} as any,
+ });
+
+ await runtime.listTasks({});
+
+ expect(taskCaller.list).toHaveBeenCalledWith(
+ expect.objectContaining({
+ assigneeAgentId: undefined,
+ parentTaskId: null,
+ }),
+ );
+ });
+ });
});
diff --git a/src/server/services/toolExecution/serverRuntimes/task.ts b/src/server/services/toolExecution/serverRuntimes/task.ts
index c3688cb510b..6de7d2086a0 100644
--- a/src/server/services/toolExecution/serverRuntimes/task.ts
+++ b/src/server/services/toolExecution/serverRuntimes/task.ts
@@ -11,6 +11,7 @@ import {
} from '@lobechat/prompts';
import type { TaskStatus } from '@lobechat/types';
+import { AgentModel } from '@/database/models/agent';
import { TaskModel } from '@/database/models/task';
import { taskRouter } from '@/server/routers/lambda/task';
import { TaskService } from '@/server/services/task';
@@ -18,230 +19,264 @@ import { TaskService } from '@/server/services/task';
import { type ServerRuntimeRegistration } from './types';
export const createTaskRuntime = ({
+ agentModel,
agentId,
+ scope,
taskId,
taskCaller,
taskModel,
taskService,
}: {
+ agentModel: AgentModel;
agentId?: string;
+ scope?: string | null;
taskId?: string;
taskCaller: ReturnType<typeof taskRouter.createCaller>;
taskModel: TaskModel;
taskService: TaskService;
-}) => ({
- createTask: async (args: {
- instruction: string;
- name: string;
- parentIdentifier?: string;
- priority?: number;
- sortOrder?: number;
- }) => {
- let parentTaskId: string | undefined;
- let parentLabel: string | undefined;
-
- if (args.parentIdentifier) {
- const parent = await taskModel.resolve(args.parentIdentifier);
- if (!parent)
- return { content: `Parent task not found: ${args.parentIdentifier}`, success: false };
- parentTaskId = parent.id;
- parentLabel = parent.identifier;
- }
+}) => {
+ const resolveAssigneeAgent = async (assigneeAgentId?: string | null) => {
+ if (!assigneeAgentId) return { success: true } as const;
- const task = await taskModel.create({
- assigneeAgentId: agentId,
- createdByAgentId: agentId,
- instruction: args.instruction,
- name: args.name,
- parentTaskId,
- priority: args.priority,
- sortOrder: args.sortOrder,
- });
+ const exists = await agentModel.existsById(assigneeAgentId);
+ if (exists) return { success: true } as const;
return {
- content: formatTaskCreated({
- identifier: task.identifier,
+ content: `Assignee agent not found: ${assigneeAgentId}`,
+ success: false,
+ } as const;
+ };
+
+ return {
+ createTask: async (args: {
+ instruction: string;
+ assigneeAgentId?: string;
+ name: string;
+ parentIdentifier?: string;
+ priority?: number;
+ sortOrder?: number;
+ }) => {
+ let parentTaskId: string | undefined;
+ let parentLabel: string | undefined;
+
+ if (args.parentIdentifier) {
+ const parent = await taskModel.resolve(args.parentIdentifier);
+ if (!parent)
+ return { content: `Parent task not found: ${args.parentIdentifier}`, success: false };
+ parentTaskId = parent.id;
+ parentLabel = parent.identifier;
+ }
+
+ const assigneeResult = await resolveAssigneeAgent(args.assigneeAgentId);
+ if (!assigneeResult.success) return assigneeResult;
+
+ const task = await taskModel.create({
+ assigneeAgentId: args.assigneeAgentId ?? (scope === 'task' ? undefined : agentId),
+ createdByAgentId: agentId,
instruction: args.instruction,
- name: task.name,
- parentLabel,
- priority: task.priority,
- status: task.status,
- }),
- success: true,
- };
- },
-
- deleteTask: async (args: { identifier: string }) => {
- const task = await taskModel.resolve(args.identifier);
- if (!task) return { content: `Task not found: ${args.identifier}`, success: false };
-
- await taskModel.delete(task.id);
-
- return {
- content: formatTaskDeleted(task.identifier, task.name),
- success: true,
- };
- },
-
- editTask: async (args: {
- addDependencies?: string[];
- description?: string;
- identifier: string;
- instruction?: string;
- name?: string;
- priority?: number;
- removeDependencies?: string[];
- }) => {
- const task = await taskModel.resolve(args.identifier);
- if (!task) return { content: `Task not found: ${args.identifier}`, success: false };
-
- const updateData: Record<string, any> = {};
- const changes: string[] = [];
- const ops: Promise<unknown>[] = [];
-
- if (args.name !== undefined) {
- updateData.name = args.name;
- changes.push(`name → "${args.name}"`);
- }
- if (args.instruction !== undefined) {
- updateData.instruction = args.instruction;
- changes.push(`instruction updated`);
- }
- if (args.description !== undefined) {
- updateData.description = args.description;
- changes.push('description updated');
- }
- if (args.priority !== undefined) {
- updateData.priority = args.priority;
- changes.push(`priority → ${priorityLabel(args.priority)}`);
- }
-
- if (Object.keys(updateData).length > 0) {
- ops.push(taskModel.update(task.id, updateData));
- }
-
- const applyDeps = async (
- ids: string[],
- apply: (depId: string) => Promise<unknown>,
- onChange: (depIdentifier: string) => void,
- ): Promise<string | undefined> => {
- const resolved = await Promise.all(
- ids.map((id) => taskModel.resolve(id).then((r) => ({ id, resolved: r }))),
- );
- const missing = resolved.find((r) => !r.resolved);
- if (missing) return `Dependency task not found: ${missing.id}`;
-
- await Promise.all(resolved.map(({ resolved: dep }) => apply(dep!.id)));
- resolved.forEach(({ resolved: dep }) => onChange(dep!.identifier));
- };
-
- const depResults: Promise<string | undefined>[] = [];
- if (args.addDependencies?.length) {
- depResults.push(
- applyDeps(
- args.addDependencies,
- (depId) => taskModel.addDependency(task.id, depId),
- (depIdentifier) => changes.push(formatDependencyAdded(task.identifier, depIdentifier)),
- ),
- );
- }
- if (args.removeDependencies?.length) {
- depResults.push(
- applyDeps(
- args.removeDependencies,
- (depId) => taskModel.removeDependency(task.id, depId),
- (depIdentifier) => changes.push(formatDependencyRemoved(task.identifier, depIdentifier)),
- ),
- );
- }
-
- const [, depErrors] = await Promise.all([Promise.all(ops), Promise.all(depResults)]);
- const firstDepError = depErrors.find((e) => e);
- if (firstDepError) return { content: firstDepError, success: false };
-
- return { content: formatTaskEdited(task.identifier, changes), success: true };
- },
-
- listTasks: async (args: {
- assigneeAgentId?: string;
- limit?: number;
- offset?: number;
- parentIdentifier?: string;
- priorities?: number[];
- statuses?: TaskStatus[];
- }) => {
- const normalized = normalizeListTasksParams(args, {
- currentAgentId: agentId,
- });
-
- try {
- const result = await taskCaller.list(normalized.query);
+ name: args.name,
+ parentTaskId,
+ priority: args.priority,
+ sortOrder: args.sortOrder,
+ });
return {
- content: formatTaskList(result.data, normalized.displayFilters),
+ content: formatTaskCreated({
+ identifier: task.identifier,
+ instruction: args.instruction,
+ name: task.name,
+ parentLabel,
+ priority: task.priority,
+ status: task.status,
+ }),
success: true,
};
- } catch (error) {
- const message = error instanceof Error ? error.message : 'Failed to list tasks';
-
- return {
- content: `Failed to list tasks: ${message}`,
- success: false,
- };
- }
- },
+ },
- updateTaskStatus: async (args: { error?: string; identifier?: string; status: TaskStatus }) => {
- const id = args.identifier || taskId;
- if (!id) {
- return {
- content: 'No task identifier provided and no current task context.',
- success: false,
- };
- }
+ deleteTask: async (args: { identifier: string }) => {
+ const task = await taskModel.resolve(args.identifier);
+ if (!task) return { content: `Task not found: ${args.identifier}`, success: false };
- try {
- const result = await taskCaller.updateStatus({
- error: args.error,
- id,
- status: args.status,
- });
+ await taskModel.delete(task.id);
return {
- content:
- args.status === 'failed' && args.error
- ? `Task ${result.data.identifier} status updated to failed. Error: ${args.error}`
- : `Task ${result.data.identifier} status updated to ${args.status}.`,
+ content: formatTaskDeleted(task.identifier, task.name),
success: true,
};
- } catch (error) {
- const message = error instanceof Error ? error.message : 'Failed to update task status';
-
- return {
- content: `Failed to update task status: ${message}`,
- success: false,
+ },
+
+ editTask: async (args: {
+ addDependencies?: string[];
+ assigneeAgentId?: string | null;
+ description?: string;
+ identifier: string;
+ instruction?: string;
+ name?: string;
+ priority?: number;
+ removeDependencies?: string[];
+ }) => {
+ const task = await taskModel.resolve(args.identifier);
+ if (!task) return { content: `Task not found: ${args.identifier}`, success: false };
+
+ const updateData: Record<string, any> = {};
+ const changes: string[] = [];
+ const ops: Promise<unknown>[] = [];
+
+ if (args.name !== undefined) {
+ updateData.name = args.name;
+ changes.push(`name → "${args.name}"`);
+ }
+ if (args.assigneeAgentId !== undefined) {
+ const assigneeResult = await resolveAssigneeAgent(args.assigneeAgentId);
+ if (!assigneeResult.success) return assigneeResult;
+
+ updateData.assigneeAgentId = args.assigneeAgentId;
+ changes.push(
+ args.assigneeAgentId ? `assignee agent → ${args.assigneeAgentId}` : 'assignee cleared',
+ );
+ }
+ if (args.instruction !== undefined) {
+ updateData.instruction = args.instruction;
+ changes.push(`instruction updated`);
+ }
+ if (args.description !== undefined) {
+ updateData.description = args.description;
+ changes.push('description updated');
+ }
+ if (args.priority !== undefined) {
+ updateData.priority = args.priority;
+ changes.push(`priority → ${priorityLabel(args.priority)}`);
+ }
+
+ if (Object.keys(updateData).length > 0) {
+ ops.push(taskModel.update(task.id, updateData));
+ }
+
+ const applyDeps = async (
+ ids: string[],
+ apply: (depId: string) => Promise<unknown>,
+ onChange: (depIdentifier: string) => void,
+ ): Promise<string | undefined> => {
+ const resolved = await Promise.all(
+ ids.map((id) => taskModel.resolve(id).then((r) => ({ id, resolved: r }))),
+ );
+ const missing = resolved.find((r) => !r.resolved);
+ if (missing) return `Dependency task not found: ${missing.id}`;
+
+ await Promise.all(resolved.map(({ resolved: dep }) => apply(dep!.id)));
+ resolved.forEach(({ resolved: dep }) => onChange(dep!.identifier));
};
- }
- },
- viewTask: async (args: { identifier?: string }) => {
- const id = args.identifier || taskId;
- if (!id) {
- return {
- content: 'No task identifier provided and no current task context.',
- success: false,
- };
- }
+ const depResults: Promise<string | undefined>[] = [];
+ if (args.addDependencies?.length) {
+ depResults.push(
+ applyDeps(
+ args.addDependencies,
+ (depId) => taskModel.addDependency(task.id, depId),
+ (depIdentifier) => changes.push(formatDependencyAdded(task.identifier, depIdentifier)),
+ ),
+ );
+ }
+ if (args.removeDependencies?.length) {
+ depResults.push(
+ applyDeps(
+ args.removeDependencies,
+ (depId) => taskModel.removeDependency(task.id, depId),
+ (depIdentifier) =>
+ changes.push(formatDependencyRemoved(task.identifier, depIdentifier)),
+ ),
+ );
+ }
+
+ const [, depErrors] = await Promise.all([Promise.all(ops), Promise.all(depResults)]);
+ const firstDepError = depErrors.find((e) => e);
+ if (firstDepError) return { content: firstDepError, success: false };
+
+ return { content: formatTaskEdited(task.identifier, changes), success: true };
+ },
+
+ listTasks: async (args: {
+ assigneeAgentId?: string;
+ limit?: number;
+ offset?: number;
+ parentIdentifier?: string;
+ priorities?: number[];
+ statuses?: TaskStatus[];
+ }) => {
+ const normalized = normalizeListTasksParams(args, {
+ currentAgentId: agentId,
+ defaultScope: scope === 'task' ? 'allAgents' : 'currentAgent',
+ });
- const detail = await taskService.getTaskDetail(id);
- if (!detail) return { content: `Task not found: ${id}`, success: false };
+ try {
+ const result = await taskCaller.list(normalized.query);
+
+ return {
+ content: formatTaskList(result.data, normalized.displayFilters),
+ success: true,
+ };
+ } catch (error) {
+ const message = error instanceof Error ? error.message : 'Failed to list tasks';
+
+ return {
+ content: `Failed to list tasks: ${message}`,
+ success: false,
+ };
+ }
+ },
+
+ updateTaskStatus: async (args: { error?: string; identifier?: string; status: TaskStatus }) => {
+ const id = args.identifier || taskId;
+ if (!id) {
+ return {
+ content: 'No task identifier provided and no current task context.',
+ success: false,
+ };
+ }
+
+ try {
+ const result = await taskCaller.updateStatus({
+ error: args.error,
+ id,
+ status: args.status,
+ });
+
+ return {
+ content:
+ args.status === 'failed' && args.error
+ ? `Task ${result.data.identifier} status updated to failed. Error: ${args.error}`
+ : `Task ${result.data.identifier} status updated to ${args.status}.`,
+ success: true,
+ };
+ } catch (error) {
+ const message = error instanceof Error ? error.message : 'Failed to update task status';
+
+ return {
+ content: `Failed to update task status: ${message}`,
+ success: false,
+ };
+ }
+ },
+
+ viewTask: async (args: { identifier?: string }) => {
+ const id = args.identifier || taskId;
+ if (!id) {
+ return {
+ content: 'No task identifier provided and no current task context.',
+ success: false,
+ };
+ }
+
+ const detail = await taskService.getTaskDetail(id);
+ if (!detail) return { content: `Task not found: ${id}`, success: false };
- return {
- content: formatTaskDetail(detail),
- success: true,
- };
- },
-});
+ return {
+ content: formatTaskDetail(detail),
+ success: true,
+ };
+ },
+ };
+};
export const taskRuntime: ServerRuntimeRegistration = {
factory: (context) => {
@@ -249,12 +284,15 @@ export const taskRuntime: ServerRuntimeRegistration = {
throw new Error('userId and serverDB are required for Task tool execution');
}
+ const agentModel = new AgentModel(context.serverDB, context.userId);
const taskModel = new TaskModel(context.serverDB, context.userId);
const taskService = new TaskService(context.serverDB, context.userId);
const taskCaller = taskRouter.createCaller({ userId: context.userId });
return createTaskRuntime({
+ agentModel,
agentId: context.agentId,
+ scope: context.scope,
taskCaller,
taskId: context.taskId,
taskModel,
diff --git a/src/services/aiAgent.ts b/src/services/aiAgent.ts
index 5c8d7b7a66b..62fcc2c6ca8 100644
--- a/src/services/aiAgent.ts
+++ b/src/services/aiAgent.ts
@@ -1,4 +1,4 @@
-import type { ExecAgentResult } from '@lobechat/types';
+import type { ExecAgentAppContext, ExecAgentResult } from '@lobechat/types';
import { lambdaClient } from '@/libs/trpc/client';
@@ -26,14 +26,7 @@ export interface ResumeApprovalParam {
export interface ExecAgentTaskParams {
agentId?: string;
- appContext?: {
- documentId?: string | null;
- groupId?: string | null;
- scope?: string | null;
- sessionId?: string;
- threadId?: string | null;
- topicId?: string | null;
- };
+ appContext?: ExecAgentAppContext;
autoStart?: boolean;
/**
* Runtime of the client initiating this request. When 'desktop', server
diff --git a/src/services/chat/mecha/agentConfigResolver.test.ts b/src/services/chat/mecha/agentConfigResolver.test.ts
index be2ce7d5ae9..9b6ca119a8d 100644
--- a/src/services/chat/mecha/agentConfigResolver.test.ts
+++ b/src/services/chat/mecha/agentConfigResolver.test.ts
@@ -3,6 +3,7 @@ import { GroupManagementIdentifier } from '@lobechat/builtin-tool-group-manageme
import { GTDIdentifier } from '@lobechat/builtin-tool-gtd';
import { NotebookIdentifier } from '@lobechat/builtin-tool-notebook';
import { PageAgentIdentifier } from '@lobechat/builtin-tool-page-agent';
+import { TaskIdentifier } from '@lobechat/builtin-tool-task';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import * as agentStore from '@/store/agent';
@@ -13,6 +14,19 @@ import * as userSelectors from '@/store/user/selectors';
import { resolveAgentConfig } from './agentConfigResolver';
+vi.hoisted(() => {
+ const storage = new Map<string, string>();
+ Object.defineProperty(globalThis, 'localStorage', {
+ configurable: true,
+ value: {
+ clear: () => storage.clear(),
+ getItem: (key: string) => storage.get(key) ?? null,
+ removeItem: (key: string) => storage.delete(key),
+ setItem: (key: string, value: string) => storage.set(key, value),
+ },
+ });
+});
+
describe('resolveAgentConfig', () => {
const mockAgentStoreState = { someState: true };
const mockAgentConfig = {
@@ -738,6 +752,60 @@ describe('resolveAgentConfig', () => {
});
});
+ describe('Task Manager Integration (scope: task)', () => {
+ beforeEach(() => {
+ vi.spyOn(agentSelectors.agentSelectors, 'getAgentSlugById').mockReturnValue(() => undefined);
+
+ vi.spyOn(builtinAgents, 'getAgentRuntimeConfig').mockReturnValue({
+ plugins: [TaskIdentifier],
+ systemRole: 'Task agent system prompt...',
+ });
+ });
+
+ it('should inject task tools for custom agent in task scope', () => {
+ const result = resolveAgentConfig({
+ agentId: 'custom-agent',
+ scope: 'task',
+ });
+
+ expect(result.plugins).toEqual([TaskIdentifier, 'plugin-a', 'plugin-b']);
+ expect(result.agentConfig.systemRole).toContain('Task agent system prompt');
+ expect(result.isBuiltinAgent).toBe(false);
+ });
+
+ it('should not duplicate TaskIdentifier if already present', () => {
+ const result = resolveAgentConfig({
+ agentId: 'custom-agent',
+ plugins: [TaskIdentifier, 'other-plugin'],
+ scope: 'task',
+ });
+
+ expect(result.plugins.filter((p) => p === TaskIdentifier)).toHaveLength(1);
+ expect(result.plugins).toEqual([TaskIdentifier, 'other-plugin']);
+ });
+
+ it('should not duplicate injection when task-agent itself is used in task scope', () => {
+ vi.spyOn(agentSelectors.agentSelectors, 'getAgentSlugById').mockReturnValue(
+ () => 'task-agent',
+ );
+
+ vi.spyOn(builtinAgents, 'getAgentRuntimeConfig').mockReturnValue({
+ plugins: [TaskIdentifier],
+ systemRole: 'Task agent system prompt',
+ });
+
+ const result = resolveAgentConfig({
+ agentId: 'task-agent-id',
+ scope: 'task',
+ });
+
+ expect(result.plugins.filter((p) => p === TaskIdentifier)).toHaveLength(1);
+ expect(result.agentConfig.systemRole).toBe('Task agent system prompt');
+ expect(result.isBuiltinAgent).toBe(true);
+ expect(result.slug).toBe('task-agent');
+ });
+ });
+
describe('supervisor agent (detected via groupId)', () => {
const mockGroupStoreState = { groupMap: {} };
const mockGroupWithSupervisor = {
diff --git a/src/services/chat/mecha/agentConfigResolver.ts b/src/services/chat/mecha/agentConfigResolver.ts
index 69758084354..43ab4315003 100644
--- a/src/services/chat/mecha/agentConfigResolver.ts
+++ b/src/services/chat/mecha/agentConfigResolver.ts
@@ -1,6 +1,7 @@
import { type BuiltinAgentSlug } from '@lobechat/builtin-agents';
import { BUILTIN_AGENT_SLUGS, getAgentRuntimeConfig } from '@lobechat/builtin-agents';
import { PageAgentIdentifier } from '@lobechat/builtin-tool-page-agent';
+import { TaskIdentifier } from '@lobechat/builtin-tool-task';
import { type LobeToolManifest } from '@lobechat/context-engine';
import {
type ChatCompletionTool,
@@ -295,6 +296,31 @@ export const resolveAgentConfig = (ctx: AgentConfigResolverContext): ResolvedAge
};
}
+ if (ctx.scope === 'task') {
+ const taskAgentPlugins = finalPlugins.includes(TaskIdentifier)
+ ? finalPlugins
+ : [TaskIdentifier, ...finalPlugins];
+ const taskAgentRuntime = getAgentRuntimeConfig(BUILTIN_AGENT_SLUGS.taskAgent, {});
+ const taskAgentSystemRole = taskAgentRuntime?.systemRole || '';
+ const mergedSystemRole = taskAgentSystemRole
+ ? systemRoleWithLocale
+ ? `${systemRoleWithLocale}\n\n${taskAgentSystemRole}`
+ : taskAgentSystemRole
+ : systemRoleWithLocale || '';
+
+ finalAgentConfig = {
+ ...finalAgentConfig,
+ systemRole: mergedSystemRole,
+ };
+
+ return {
+ agentConfig: finalAgentConfig,
+ chatConfig: finalChatConfig,
+ isBuiltinAgent: false,
+ plugins: applyPluginFilters(taskAgentPlugins),
+ };
+ }
+
// Not in page scope - return standard config
return {
agentConfig: finalAgentConfig,
@@ -406,6 +432,21 @@ export const resolveAgentConfig = (ctx: AgentConfigResolverContext): ResolvedAge
};
}
+ if (ctx.scope === 'task' && slug !== BUILTIN_AGENT_SLUGS.taskAgent) {
+ if (!finalPlugins.includes(TaskIdentifier)) {
+ finalPlugins = [TaskIdentifier, ...finalPlugins];
+ }
+
+ const taskAgentRuntime = getAgentRuntimeConfig(BUILTIN_AGENT_SLUGS.taskAgent, {});
+ const taskAgentSystemRole = taskAgentRuntime?.systemRole || '';
+
+ if (taskAgentSystemRole) {
+ resolvedSystemRole = resolvedSystemRole
+ ? `${resolvedSystemRole}\n\n${taskAgentSystemRole}`
+ : taskAgentSystemRole;
+ }
+ }
+
// Merge runtime systemRole into agent config
const resolvedAgentConfig: LobeAgentConfig = {
...agentConfig,
diff --git a/src/store/agent/selectors/builtinAgentSelectors.test.ts b/src/store/agent/selectors/builtinAgentSelectors.test.ts
index 9cf426f8a3f..d892ce1c795 100644
--- a/src/store/agent/selectors/builtinAgentSelectors.test.ts
+++ b/src/store/agent/selectors/builtinAgentSelectors.test.ts
@@ -69,6 +69,24 @@ describe('builtinAgentSelectors', () => {
});
});
+ describe('taskAgentId', () => {
+ it('should return task agent id', () => {
+ const state = createState({
+ builtinAgentIdMap: { [BUILTIN_AGENT_SLUGS.taskAgent]: 'task-agent-456' },
+ });
+
+ expect(builtinAgentSelectors.taskAgentId(state)).toBe('task-agent-456');
+ });
+
+ it('should return undefined when task agent not initialized', () => {
+ const state = createState({
+ builtinAgentIdMap: {},
+ });
+
+ expect(builtinAgentSelectors.taskAgentId(state)).toBeUndefined();
+ });
+ });
+
describe('agentBuilderId', () => {
it('should return agent builder id', () => {
const state = createState({
diff --git a/src/store/agent/selectors/builtinAgentSelectors.ts b/src/store/agent/selectors/builtinAgentSelectors.ts
index 7fb20e8a1a4..e81ade317f7 100644
--- a/src/store/agent/selectors/builtinAgentSelectors.ts
+++ b/src/store/agent/selectors/builtinAgentSelectors.ts
@@ -18,6 +18,11 @@ const isBuiltinAgentInit = (slug: string) => (s: AgentStoreState) => !!s.builtin
*/
const pageAgentId = (s: AgentStoreState) => s.builtinAgentIdMap[BUILTIN_AGENT_SLUGS.pageAgent];
+/**
+ * Get task agent ID (convenience selector)
+ */
+const taskAgentId = (s: AgentStoreState) => s.builtinAgentIdMap[BUILTIN_AGENT_SLUGS.taskAgent];
+
/**
* Get agent builder ID (convenience selector)
*/
@@ -57,4 +62,5 @@ export const builtinAgentSelectors = {
isInboxAgent,
isInboxAgentConfigInit,
pageAgentId,
+ taskAgentId,
};
diff --git a/src/store/chat/agents/createAgentExecutors.ts b/src/store/chat/agents/createAgentExecutors.ts
index 2bdab878b1a..8666a60f489 100644
--- a/src/store/chat/agents/createAgentExecutors.ts
+++ b/src/store/chat/agents/createAgentExecutors.ts
@@ -684,8 +684,11 @@ export const createAgentExecutors = (context: {
type: 'toolCalling',
context: {
agentId: opContext.agentId!,
+ groupId: opContext.groupId,
+ scope: opContext.scope,
topicId: opContext.topicId,
threadId: opContext.threadId,
+ viewedTask: opContext.viewedTask,
},
parentOperationId: context.operationId,
metadata: {
diff --git a/src/store/chat/slices/aiChat/actions/__tests__/gateway.test.ts b/src/store/chat/slices/aiChat/actions/__tests__/gateway.test.ts
index 73ad9e142ba..adad7193939 100644
--- a/src/store/chat/slices/aiChat/actions/__tests__/gateway.test.ts
+++ b/src/store/chat/slices/aiChat/actions/__tests__/gateway.test.ts
@@ -369,6 +369,46 @@ describe('GatewayActionImpl', () => {
);
});
+ it('should forward task manager default assignee and current task context', async () => {
+ const { action } = createExecuteTestAction();
+
+ vi.mocked(aiAgentService.execAgentTask).mockResolvedValue({
+ agentId: 'agent-task',
+ assistantMessageId: 'ast-1',
+ autoStarted: true,
+ createdAt: new Date().toISOString(),
+ message: 'ok',
+ operationId: 'server-op-1',
+ status: 'created',
+ success: true,
+ timestamp: new Date().toISOString(),
+ token: 'test-token',
+ topicId: 'topic-1',
+ userMessageId: 'usr-1',
+ });
+
+ await action.executeGatewayAgent({
+ context: {
+ agentId: 'agent-task',
+ defaultTaskAssigneeAgentId: 'agt_inbox',
+ scope: 'task',
+ topicId: 'topic-1',
+ viewedTask: { taskId: 'T-1', type: 'detail' },
+ },
+ message: 'Assign this task',
+ });
+
+ expect(aiAgentService.execAgentTask).toHaveBeenCalledWith(
+ expect.objectContaining({
+ appContext: expect.objectContaining({
+ defaultTaskAssigneeAgentId: 'agt_inbox',
+ scope: 'task',
+ taskId: 'T-1',
+ }),
+ }),
+ );
+ });
+
it('should forward empty prompt for continue generation', async () => {
const { action } = createExecuteTestAction();
diff --git a/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts b/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts
index 615c26afd24..9da317083a6 100644
--- a/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts
+++ b/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts
@@ -659,7 +659,6 @@ export class ConversationLifecycleActionImpl {
? {
topicMessageIds: forceNewTopicFromExisting ? [] : messages.map((m) => m.id),
title: message.slice(0, 20) || t('defaultTitle', { ns: 'topic' }),
- trigger: context.topicTrigger,
}
: undefined,
agentId: operationContext.agentId,
diff --git a/src/store/chat/slices/aiChat/actions/gateway.ts b/src/store/chat/slices/aiChat/actions/gateway.ts
index f26d7779194..e5e4944894f 100644
--- a/src/store/chat/slices/aiChat/actions/gateway.ts
+++ b/src/store/chat/slices/aiChat/actions/gateway.ts
@@ -231,13 +231,16 @@ export class GatewayActionImpl {
window.global_serverConfigStore!.getState().serverConfig.agentGatewayUrl!;
const isCreateNewTopic = !context.topicId;
+ const taskId = context.viewedTask?.type === 'detail' ? context.viewedTask.taskId : undefined;
const result = await aiAgentService.execAgentTask({
agentId: context.agentId,
appContext: {
+ defaultTaskAssigneeAgentId: context.defaultTaskAssigneeAgentId,
documentId: context.documentId,
groupId: context.groupId,
scope: context.scope,
+ taskId,
threadId: context.threadId,
topicId: context.topicId,
},
diff --git a/src/store/chat/slices/aiChat/actions/streamingExecutor.ts b/src/store/chat/slices/aiChat/actions/streamingExecutor.ts
index c982ee734d6..ccd0b7a2669 100644
--- a/src/store/chat/slices/aiChat/actions/streamingExecutor.ts
+++ b/src/store/chat/slices/aiChat/actions/streamingExecutor.ts
@@ -316,12 +316,17 @@ export class StreamingExecutorActionImpl {
if (viewedTask.type === 'list') {
contextPrompt = buildTaskListPrompt({
+ defaultAssigneeAgentId: operation.context.defaultTaskAssigneeAgentId,
tasks: taskState.tasks,
total: taskState.tasksTotal || taskState.tasks.length,
});
} else {
const detail = taskState.taskDetailMap[viewedTask.taskId];
- if (detail) contextPrompt = buildTaskDetailPrompt({ task: detail });
+ if (detail)
+ contextPrompt = buildTaskDetailPrompt({
+ defaultAssigneeAgentId: operation.context.defaultTaskAssigneeAgentId,
+ task: detail,
+ });
}
if (contextPrompt) {
diff --git a/src/store/chat/slices/aiChat/initialState.ts b/src/store/chat/slices/aiChat/initialState.ts
index 87d65933adb..f94140e9bae 100644
--- a/src/store/chat/slices/aiChat/initialState.ts
+++ b/src/store/chat/slices/aiChat/initialState.ts
@@ -16,12 +16,6 @@ export interface ChatAIChatState {
* UI can render a distinct "running on device" state.
*/
pendingClientToolExecutions: Record<string, boolean>;
- /**
- * Tool ids enabled by the current runtime scenario/page (for example the
- * tasks page enabling `lobe-task` while its panel is mounted).
- * Transient state, not persisted — cleared on reload or when pages unmount.
- */
- scenarioEnabledToolIds?: string[];
searchWorkflowLoadingIds: string[];
threadInputEditor: ChatInputEditor | null;
/**
@@ -36,7 +30,6 @@ export const initialAiChatState: ChatAIChatState = {
inputMessage: '',
mainInputEditor: null,
pendingClientToolExecutions: {},
- scenarioEnabledToolIds: undefined,
searchWorkflowLoadingIds: [],
threadInputEditor: null,
toolCallingStreamIds: {},
diff --git a/src/store/chat/slices/plugin/actions/pluginTypes.ts b/src/store/chat/slices/plugin/actions/pluginTypes.ts
index 091ef879642..55494bfd9c7 100644
--- a/src/store/chat/slices/plugin/actions/pluginTypes.ts
+++ b/src/store/chat/slices/plugin/actions/pluginTypes.ts
@@ -86,6 +86,8 @@ export class PluginTypesActionImpl {
let groupId = operation?.context?.groupId ?? rootRuntimeOperationContext?.groupId;
const documentId = operation?.context?.documentId ?? rootRuntimeOperationContext?.documentId;
const scope = operation?.context?.scope ?? rootRuntimeOperationContext?.scope;
+ const viewedTask = operation?.context?.viewedTask ?? rootRuntimeOperationContext?.viewedTask;
+ const taskId = viewedTask?.type === 'detail' ? viewedTask.taskId : undefined;
const topicId = operation?.context?.topicId ?? rootRuntimeOperationContext?.topicId;
// For agent-builder tools, inject activeAgentId from store if not in context
@@ -138,6 +140,7 @@ export class PluginTypesActionImpl {
operationId,
rootRuntimeOperationId,
scope,
+ taskId,
topicId,
});
@@ -154,6 +157,7 @@ export class PluginTypesActionImpl {
scope,
signal: operation?.abortController?.signal,
stepContext,
+ taskId,
topicId,
});
diff --git a/src/store/chat/utils/messageMapKey.test.ts b/src/store/chat/utils/messageMapKey.test.ts
index 71370fe54b7..ae36dad6abd 100644
--- a/src/store/chat/utils/messageMapKey.test.ts
+++ b/src/store/chat/utils/messageMapKey.test.ts
@@ -63,6 +63,22 @@ describe('messageMapKey', () => {
});
});
+ describe('Task mode', () => {
+ it('should generate key for a new task manager topic', () => {
+ const result = messageMapKey({ scope: 'task', agentId: 'agt_task' });
+ expect(result).toBe('task_agt_task_new');
+ });
+
+ it('should generate key for an existing task manager topic', () => {
+ const result = messageMapKey({
+ scope: 'task',
+ agentId: 'agt_task',
+ topicId: 'tpc_task',
+ });
+ expect(result).toBe('task_agt_task_tpc_task');
+ });
+ });
+
describe('Group mode with groupId (auto-detected)', () => {
it('should auto-detect group scope when groupId is present', () => {
const result = messageMapKey({
diff --git a/src/store/chat/utils/messageMapKey.ts b/src/store/chat/utils/messageMapKey.ts
index 601c5ac691a..38513054cd5 100644
--- a/src/store/chat/utils/messageMapKey.ts
+++ b/src/store/chat/utils/messageMapKey.ts
@@ -141,6 +141,8 @@ const generateKey = (context: MessageMapContext): string => {
* - Group existing topic: `group_grp_xxx_tpc_yyy`
* - Group agent new topic: `group_agent_grp_xxx_tpc_yyy_new`
* - Group agent existing topic: `group_agent_grp_xxx_tpc_yyy_tpc_zzz`
+ * - Task new topic: `task_agt_xxx_new`
+ * - Task existing topic: `task_agt_xxx_tpc_yyy`
*
* Auto-detection rules (when scope is not explicitly set):
* - If threadId exists: scope = 'thread', subTopicId = threadId
diff --git a/src/store/taskChat/action.ts b/src/store/taskChat/action.ts
deleted file mode 100644
index 5a088c7f639..00000000000
--- a/src/store/taskChat/action.ts
+++ /dev/null
@@ -1,83 +0,0 @@
-import isEqual from 'fast-deep-equal';
-import { type SWRResponse } from 'swr';
-
-import { mutate, useClientDataSWRWithSync } from '@/libs/swr';
-import { topicService } from '@/services/topic';
-import { useChatStore } from '@/store/chat';
-import { type StoreSetter } from '@/store/types';
-import { type ChatTopic } from '@/types/topic';
-import { setNamespace } from '@/utils/storeDebug';
-
-import { type TaskChatStore } from './store';
-
-const n = setNamespace('taskChat');
-
-const SWR_USE_FETCH_TASK_TOPICS = 'SWR_USE_FETCH_TASK_TOPICS';
-
-type Setter = StoreSetter<TaskChatStore>;
-
-export const createTaskChatSlice = (set: Setter, get: () => TaskChatStore, _api?: unknown) =>
- new TaskChatActionImpl(set, get, _api);
-
-export class TaskChatActionImpl {
- readonly #get: () => TaskChatStore;
- readonly #set: Setter;
-
- constructor(set: Setter, get: () => TaskChatStore, _api?: unknown) {
- void _api;
- this.#set = set;
- this.#get = get;
- }
-
- switchTopic = (id: string | null): void => {
- if (this.#get().activeTopicId === id) return;
- this.#set({ activeTopicId: id }, false, n('switchTopic'));
- };
-
- /**
- * Called by `ConversationHooks.onTopicCreated` after the backend creates
- * a new topic from this panel's sendMessage. Writes the new id into the
- * isolated store and refreshes the local topic list.
- */
- onTopicCreated = async (topicId: string): Promise<void> => {
- this.#set({ activeTopicId: topicId }, false, n('onTopicCreated'));
- await this.refreshTopics();
- };
-
- refreshTopics = async (): Promise<void> => {
- const { activeAgentId } = useChatStore.getState();
- if (!activeAgentId) return;
- await mutate(
- (key) =>
- Array.isArray(key) && key[0] === SWR_USE_FETCH_TASK_TOPICS && key[1] === activeAgentId,
- );
- };
-
- useFetchTopics = (
- agentId: string | undefined,
- includeTriggers: string[],
- ): SWRResponse<ChatTopic[]> => {
- return useClientDataSWRWithSync<ChatTopic[]>(
- agentId ? [SWR_USE_FETCH_TASK_TOPICS, agentId, includeTriggers.join(',')] : null,
- async () => {
- if (!agentId) return [];
- const result = await topicService.getTopics({
- agentId,
- current: 0,
- includeTriggers,
- pageSize: 100,
- });
- return result.items;
- },
- {
- onData: (topics) => {
- if (!topics) return;
- if (isEqual(topics, this.#get().topics)) return;
- this.#set({ topics }, false, n('useFetchTopics(onData)'));
- },
- },
- );
- };
-}
-
-export type TaskChatAction = Pick<TaskChatActionImpl, keyof TaskChatActionImpl>;
diff --git a/src/store/taskChat/index.ts b/src/store/taskChat/index.ts
deleted file mode 100644
index a08172352c1..00000000000
--- a/src/store/taskChat/index.ts
+++ /dev/null
@@ -1 +0,0 @@
-export { getTaskChatStoreState, type TaskChatStore, useTaskChatStore } from './store';
diff --git a/src/store/taskChat/initialState.ts b/src/store/taskChat/initialState.ts
deleted file mode 100644
index e32efaea96f..00000000000
--- a/src/store/taskChat/initialState.ts
+++ /dev/null
@@ -1,25 +0,0 @@
-import { type ChatTopic } from '@/types/topic';
-
-/**
- * State for the Task Manager right-side panel.
- *
- * Isolated from the main `useChatStore` so that switching/creating a Task
- * Manager topic does not mutate the main chat's `activeTopicId`.
- *
- * Messages are NOT duplicated here — they live in `useChatStore.dbMessagesMap`,
- * keyed by `messageMapKey(context)`. As long as the Task Manager uses its own
- * `activeTopicId` in the context it builds, the messages are naturally stored
- * under a different key.
- */
-export interface TaskChatState {
- activeTopicId: string | null;
- /**
- * `undefined` means topics have not been fetched yet (loading state).
- */
- topics: ChatTopic[] | undefined;
-}
-
-export const initialState: TaskChatState = {
- activeTopicId: null,
- topics: undefined,
-};
diff --git a/src/store/taskChat/store.ts b/src/store/taskChat/store.ts
deleted file mode 100644
index 7ac2451d572..00000000000
--- a/src/store/taskChat/store.ts
+++ /dev/null
@@ -1,39 +0,0 @@
-import { shallow } from 'zustand/shallow';
-import { createWithEqualityFn } from 'zustand/traditional';
-import { type StateCreator } from 'zustand/vanilla';
-
-import { createDevtools } from '../middleware/createDevtools';
-import { expose } from '../middleware/expose';
-import { flattenActions } from '../utils/flattenActions';
-import { type ResetableStore, ResetableStoreAction } from '../utils/resetableStore';
-import { createTaskChatSlice, type TaskChatAction } from './action';
-import { initialState, type TaskChatState } from './initialState';
-
-export type TaskChatStore = TaskChatState & TaskChatAction & ResetableStore;
-
-type TaskChatStoreAction = TaskChatAction & ResetableStore;
-
-class TaskChatResetAction extends ResetableStoreAction<TaskChatStore> {
- protected readonly resetActionName = 'resetTaskChatStore';
-}
-
-const createStore: StateCreator<TaskChatStore, [['zustand/devtools', never]]> = (
- ...parameters: Parameters<StateCreator<TaskChatStore, [['zustand/devtools', never]]>>
-) => ({
- ...initialState,
- ...flattenActions<TaskChatStoreAction>([
- createTaskChatSlice(...parameters),
- new TaskChatResetAction(...parameters),
- ]),
-});
-
-const devtools = createDevtools('taskChat');
-
-export const useTaskChatStore = createWithEqualityFn<TaskChatStore>()(
- devtools(createStore),
- shallow,
-);
-
-expose('taskChat', useTaskChatStore);
-
-export const getTaskChatStoreState = () => useTaskChatStore.getState();