π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
β¨ feat(task): add comment tools and reparent support (#14515)
YuTengjinge1a5b27db0c2
diff --git a/packages/builtin-tool-task/src/client/Inspector/EditTask/index.tsx b/packages/builtin-tool-task/src/client/Inspector/EditTask/index.tsxindex ff9b2345867..3182b29c1c2 100644--- a/packages/builtin-tool-task/src/client/Inspector/EditTask/index.tsx+++ b/packages/builtin-tool-task/src/client/Inspector/EditTask/index.tsx@@ -131,6 +131,21 @@ export const EditTaskInspector = memo<BuiltinInspectorProps<EditTaskParams, Edit});}+ if (params.parentIdentifier !== undefined) {+ segments.push({+ content:+ params.parentIdentifier === null ? (+ <span className={styles.chip}>{t('builtins.lobe-task.edit.parentClear')}</span>+ ) : (+ <>+ <span className={styles.label}>{t('builtins.lobe-task.edit.parent')}</span>+ <span className={styles.chip}>{params.parentIdentifier}</span>+ </>+ ),+ key: 'parent',+ });+ }+if (params.assigneeAgentId !== undefined) {segments.push({content:diff --git a/packages/builtin-tool-task/src/client/Inspector/TaskComment/index.tsx b/packages/builtin-tool-task/src/client/Inspector/TaskComment/index.tsxnew file mode 100644index 00000000000..0195c401d99--- /dev/null+++ b/packages/builtin-tool-task/src/client/Inspector/TaskComment/index.tsx@@ -0,0 +1,128 @@+'use client';++import type { BuiltinInspectorProps } from '@lobechat/types';+import { createStaticStyles, cx } from 'antd-style';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import { inspectorTextStyles, shinyTextStyles } from '@/styles';++import type {+ AddTaskCommentParams,+ AddTaskCommentState,+ DeleteTaskCommentParams,+ DeleteTaskCommentState,+ UpdateTaskCommentParams,+ UpdateTaskCommentState,+} from '../../../types';+import { TaskApiName } from '../../../types';++const styles = createStaticStyles(({ css, cssVar }) => ({+ chip: css`+ overflow: hidden;+ display: inline-flex;+ flex-shrink: 1;+ align-items: center;++ min-width: 0;+ max-width: 220px;+ margin-inline-start: 6px;+ padding-block: 1px;+ padding-inline: 8px;+ border-radius: 999px;++ font-family: ${cssVar.fontFamilyCode};+ font-size: 12px;+ color: ${cssVar.colorTextSecondary};+ text-overflow: ellipsis;+ white-space: nowrap;++ background: ${cssVar.colorFillTertiary};+ `,+ contentChip: css`+ overflow: hidden;+ display: inline-flex;+ flex-shrink: 1;+ align-items: center;++ min-width: 0;+ max-width: 260px;+ margin-inline-start: 6px;+ padding-block: 1px;+ padding-inline: 8px;+ border-radius: 999px;++ font-size: 12px;+ color: ${cssVar.colorText};+ text-overflow: ellipsis;+ white-space: nowrap;++ background: ${cssVar.colorFillTertiary};+ `,+}));++interface TaskCommentInspectorProps extends BuiltinInspectorProps<+ AddTaskCommentParams | UpdateTaskCommentParams | DeleteTaskCommentParams,+ AddTaskCommentState | UpdateTaskCommentState | DeleteTaskCommentState+> {+ apiName: string;+}++const selectLabelKey = (apiName: string) => {+ switch (apiName) {+ case TaskApiName.addTaskComment: {+ return 'builtins.lobe-task.apiName.addTaskComment';+ }+ case TaskApiName.updateTaskComment: {+ return 'builtins.lobe-task.apiName.updateTaskComment';+ }+ case TaskApiName.deleteTaskComment: {+ return 'builtins.lobe-task.apiName.deleteTaskComment';+ }+ default: {+ return 'builtins.lobe-task.apiName.addTaskComment';+ }+ }+};++export const TaskCommentInspector = memo<TaskCommentInspectorProps>(+ ({ apiName, args, partialArgs, isArgumentsStreaming, isLoading }) => {+ const { t } = useTranslation('plugin');++ const params = args || partialArgs || {};+ const identifier = 'identifier' in params ? params.identifier : undefined;+ const commentId = 'commentId' in params ? params.commentId : undefined;+ const content = 'content' in params ? params.content : undefined;++ return (+ <div+ className={cx(+ inspectorTextStyles.root,+ (isArgumentsStreaming || isLoading) && shinyTextStyles.shinyText,+ )}+ >+ <span>{t(selectLabelKey(apiName))}</span>+ {identifier && <span className={styles.chip}>{identifier}</span>}+ {commentId && <span className={styles.chip}>{commentId}</span>}+ {content && <span className={styles.contentChip}>{content}</span>}+ </div>+ );+ },+);++TaskCommentInspector.displayName = 'TaskCommentInspector';++export const AddTaskCommentInspector = (+ props: BuiltinInspectorProps<AddTaskCommentParams, AddTaskCommentState>,+) => <TaskCommentInspector {...props} apiName={TaskApiName.addTaskComment} />;+AddTaskCommentInspector.displayName = 'AddTaskCommentInspector';++export const UpdateTaskCommentInspector = (+ props: BuiltinInspectorProps<UpdateTaskCommentParams, UpdateTaskCommentState>,+) => <TaskCommentInspector {...props} apiName={TaskApiName.updateTaskComment} />;+UpdateTaskCommentInspector.displayName = 'UpdateTaskCommentInspector';++export const DeleteTaskCommentInspector = (+ props: BuiltinInspectorProps<DeleteTaskCommentParams, DeleteTaskCommentState>,+) => <TaskCommentInspector {...props} apiName={TaskApiName.deleteTaskComment} />;+DeleteTaskCommentInspector.displayName = 'DeleteTaskCommentInspector';diff --git a/packages/builtin-tool-task/src/client/Inspector/index.ts b/packages/builtin-tool-task/src/client/Inspector/index.tsindex 200a3e098c9..f95f6d858b3 100644--- a/packages/builtin-tool-task/src/client/Inspector/index.ts+++ b/packages/builtin-tool-task/src/client/Inspector/index.ts@@ -8,6 +8,11 @@ import { EditTaskInspector } from './EditTask';import { ListTasksInspector } from './ListTasks';import { RunTaskInspector } from './RunTask';import { RunTasksInspector } from './RunTasks';+import {+ AddTaskCommentInspector,+ DeleteTaskCommentInspector,+ UpdateTaskCommentInspector,+} from './TaskComment';import { UpdateTaskStatusInspector } from './UpdateTaskStatus';import { ViewTaskInspector } from './ViewTask';@@ -18,13 +23,16 @@ import { ViewTaskInspector } from './ViewTask';* in the conversation UI for the lobe-task built-in tool.*/export const TaskInspectors: Record<string, BuiltinInspector> = {+ [TaskApiName.addTaskComment]: AddTaskCommentInspector as BuiltinInspector,[TaskApiName.createTask]: CreateTaskInspector as BuiltinInspector,[TaskApiName.createTasks]: CreateTasksInspector as BuiltinInspector,[TaskApiName.deleteTask]: DeleteTaskInspector as BuiltinInspector,+ [TaskApiName.deleteTaskComment]: DeleteTaskCommentInspector as BuiltinInspector,[TaskApiName.editTask]: EditTaskInspector as BuiltinInspector,[TaskApiName.listTasks]: ListTasksInspector as BuiltinInspector,[TaskApiName.runTask]: RunTaskInspector as BuiltinInspector,[TaskApiName.runTasks]: RunTasksInspector as BuiltinInspector,+ [TaskApiName.updateTaskComment]: UpdateTaskCommentInspector as BuiltinInspector,[TaskApiName.updateTaskStatus]: UpdateTaskStatusInspector as BuiltinInspector,[TaskApiName.viewTask]: ViewTaskInspector as BuiltinInspector,};@@ -36,5 +44,10 @@ export { EditTaskInspector } from './EditTask';export { ListTasksInspector } from './ListTasks';export { RunTaskInspector } from './RunTask';export { RunTasksInspector } from './RunTasks';+export {+ AddTaskCommentInspector,+ DeleteTaskCommentInspector,+ UpdateTaskCommentInspector,+} from './TaskComment';export { UpdateTaskStatusInspector } from './UpdateTaskStatus';export { ViewTaskInspector } from './ViewTask';diff --git a/packages/builtin-tool-task/src/client/index.ts b/packages/builtin-tool-task/src/client/index.tsindex 4827413637a..f3473a9d335 100644--- a/packages/builtin-tool-task/src/client/index.ts+++ b/packages/builtin-tool-task/src/client/index.ts@@ -1,13 +1,16 @@// Inspector components (customized tool call headers)export {+ AddTaskCommentInspector,CreateTaskInspector,CreateTasksInspector,+ DeleteTaskCommentInspector,DeleteTaskInspector,EditTaskInspector,ListTasksInspector,RunTaskInspector,RunTasksInspector,TaskInspectors,+ UpdateTaskCommentInspector,UpdateTaskStatusInspector,ViewTaskInspector,} from './Inspector';diff --git a/packages/builtin-tool-task/src/executor/index.ts b/packages/builtin-tool-task/src/executor/index.tsindex 7f35bd94efd..55b16a4ca23 100644--- a/packages/builtin-tool-task/src/executor/index.ts+++ b/packages/builtin-tool-task/src/executor/index.ts@@ -17,7 +17,14 @@ import { getTaskStoreState } from '@/store/task';import { normalizeListTasksParams } from '../listTasks';import { TaskIdentifier } from '../manifest';-import type { CreateTaskParams, CreateTasksItemResult, RunTasksItemResult } from '../types';+import type {+ AddTaskCommentParams,+ CreateTaskParams,+ CreateTasksItemResult,+ DeleteTaskCommentParams,+ RunTasksItemResult,+ UpdateTaskCommentParams,+} from '../types';import { TaskApiName } from '../types';const log = debug('lobe-task:executor');@@ -26,6 +33,42 @@ class TaskExecutor extends BaseExecutor<typeof TaskApiName> {readonly identifier = TaskIdentifier;protected readonly apiEnum = TaskApiName;+ addTaskComment = async (+ params: AddTaskCommentParams,+ ctx?: BuiltinToolContext,+ ): Promise<BuiltinToolResult> => {+ const identifier = params.identifier?.trim() || ctx?.taskId || undefined;+ if (!identifier) {+ return {+ content: 'No task identifier provided.',+ error: { message: 'identifier is required', type: 'MissingIdentifier' },+ success: false,+ };+ }++ try {+ log('[TaskExecutor] addTaskComment - identifier:', identifier);+ const result = await getTaskStoreState().addComment(identifier, params.content, {+ authorAgentId: ctx?.agentId,+ });+ const commentId = (result as { data?: { id?: string } } | undefined)?.data?.id;++ return {+ content: `Comment added to task ${identifier}.`,+ state: { commentId, identifier, success: true },+ success: true,+ };+ } catch (error) {+ log('[TaskExecutor] addTaskComment - error:', error);+ const message = error instanceof Error ? error.message : 'Failed to add task comment';+ return {+ content: `Failed to add task comment: ${message}`,+ error: { message, type: 'AddTaskCommentFailed' },+ success: false,+ };+ }+ };+createTask = async (params: {instruction: string;@@ -164,6 +207,30 @@ class TaskExecutor extends BaseExecutor<typeof TaskApiName> {}};+ deleteTaskComment = async (+ params: DeleteTaskCommentParams,+ ctx?: BuiltinToolContext,+ ): Promise<BuiltinToolResult> => {+ try {+ log('[TaskExecutor] deleteTaskComment - commentId:', params.commentId);+ await getTaskStoreState().deleteComment(params.commentId, ctx?.taskId ?? undefined);++ return {+ content: `Comment ${params.commentId} deleted.`,+ state: { commentId: params.commentId, success: true },+ success: true,+ };+ } catch (error) {+ log('[TaskExecutor] deleteTaskComment - error:', error);+ const message = error instanceof Error ? error.message : 'Failed to delete task comment';+ return {+ content: `Failed to delete task comment: ${message}`,+ error: { message, type: 'DeleteTaskCommentFailed' },+ success: false,+ };+ }+ };+editTask = async (params: {addDependencies?: string[];@@ -172,6 +239,7 @@ class TaskExecutor extends BaseExecutor<typeof TaskApiName> {identifier: string;instruction?: string;name?: string;+ parentIdentifier?: string | null;priority?: number;removeDependencies?: string[];},@@ -190,6 +258,7 @@ class TaskExecutor extends BaseExecutor<typeof TaskApiName> {assigneeAgentId?: string | null;instruction?: string;name?: string;+ parentTaskId?: string | null;priority?: number;} = {};if (params.name !== undefined) {@@ -212,6 +281,11 @@ class TaskExecutor extends BaseExecutor<typeof TaskApiName> {updateData.description = params.description;changes.push('description updated');}+ if (params.parentIdentifier !== undefined) {+ const parentIdentifier = params.parentIdentifier?.trim() || null;+ updateData.parentTaskId = parentIdentifier;+ changes.push(parentIdentifier ? `parent β ${parentIdentifier}` : 'parent cleared');+ }if (params.priority !== undefined) {updateData.priority = params.priority;changes.push(`priority β ${priorityLabel(params.priority)}`);@@ -392,6 +466,34 @@ class TaskExecutor extends BaseExecutor<typeof TaskApiName> {};};+ updateTaskComment = async (+ params: UpdateTaskCommentParams,+ ctx?: BuiltinToolContext,+ ): Promise<BuiltinToolResult> => {+ try {+ log('[TaskExecutor] updateTaskComment - commentId:', params.commentId);+ await getTaskStoreState().updateComment(+ params.commentId,+ params.content,+ ctx?.taskId ?? undefined,+ );++ return {+ content: `Comment ${params.commentId} updated.`,+ state: { commentId: params.commentId, success: true },+ success: true,+ };+ } catch (error) {+ log('[TaskExecutor] updateTaskComment - error:', error);+ const message = error instanceof Error ? error.message : 'Failed to update task comment';+ return {+ content: `Failed to update task comment: ${message}`,+ error: { message, type: 'UpdateTaskCommentFailed' },+ success: false,+ };+ }+ };+updateTaskStatus = async (params: { error?: string; identifier?: string; status: TaskStatus },ctx?: BuiltinToolContext,diff --git a/packages/builtin-tool-task/src/manifest.ts b/packages/builtin-tool-task/src/manifest.tsindex 9f0cf6eab9e..478cd9b3319 100644--- a/packages/builtin-tool-task/src/manifest.ts+++ b/packages/builtin-tool-task/src/manifest.ts@@ -150,9 +150,64 @@ export const TaskManifest: BuiltinToolManifest = {type: 'object',},},+ // ==================== Task Comments ===================={description:- "Edit a task's fields (name, description, instruction, priority) or dependencies (batched). Status changes go through updateTaskStatus.",+ 'Add a comment to a task. If identifier is omitted, this only works when there is a current task context. Use comments to record decisions, progress, or feedback that should appear in task activities.',+ name: TaskApiName.addTaskComment,+ parameters: {+ properties: {+ content: {+ description: 'Comment content to add to the task.',+ type: 'string',+ },+ identifier: {+ description:+ 'The task identifier to comment on (e.g. "TASK-1"). If omitted, the current task is used only when a current task context exists.',+ type: 'string',+ },+ },+ required: ['content'],+ type: 'object',+ },+ },+ {+ description:+ 'Update an existing task comment by commentId. Use viewTask to inspect task activities and find comment ids.',+ name: TaskApiName.updateTaskComment,+ parameters: {+ properties: {+ commentId: {+ description: 'The task comment id to update.',+ type: 'string',+ },+ content: {+ description: 'Updated comment content.',+ type: 'string',+ },+ },+ required: ['commentId', 'content'],+ type: 'object',+ },+ },+ {+ description:+ 'Delete an existing task comment by commentId. Use viewTask to inspect task activities and find comment ids.',+ name: TaskApiName.deleteTaskComment,+ parameters: {+ properties: {+ commentId: {+ description: 'The task comment id to delete.',+ type: 'string',+ },+ },+ required: ['commentId'],+ type: 'object',+ },+ },+ {+ description:+ "Edit a task's fields (name, description, instruction, priority), parent, or dependencies (batched). Status changes go through updateTaskStatus.",name: TaskApiName.editTask,parameters: {properties: {@@ -183,6 +238,11 @@ export const TaskManifest: BuiltinToolManifest = {description: 'Updated name for the task.',type: 'string',},+ parentIdentifier: {+ description:+ 'Set the parent task by identifier (e.g. "TASK-1"). Pass null to move this task to top level. Omit to keep the current parent.',+ type: ['string', 'null'],+ },priority: {description: 'Updated priority level: 0=none, 1=urgent, 2=high, 3=normal, 4=low.',type: 'number',@@ -284,7 +344,7 @@ export const TaskManifest: BuiltinToolManifest = {identifier: TaskIdentifier,meta: {avatar: '\uD83D\uDCCB',- description: 'Create, list, edit, delete tasks with dependencies',+ description: 'Create, list, edit, comment on, and delete tasks with dependencies',title: 'Task Tools',},systemRole: systemPrompt,diff --git a/packages/builtin-tool-task/src/systemRole.ts b/packages/builtin-tool-task/src/systemRole.tsindex fcb8e29401b..6fa8310d09b 100644--- a/packages/builtin-tool-task/src/systemRole.ts+++ b/packages/builtin-tool-task/src/systemRole.ts@@ -4,7 +4,8 @@ export const systemPrompt = `You have access to Task management tools. Use them- **createTasks**: Create multiple tasks in one call. Prefer this when you are about to create more than one task in a row (e.g. all subtasks under one parent, or all chapters of an outline) β it cuts the number of tool calls and keeps the batch atomic from the user's perspective- **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+- **addTaskComment / updateTaskComment / deleteTaskComment**: Record, revise, or remove task comments. Use viewTask to inspect existing comments and their comment ids+- **editTask**: Modify a task's fields (name, description, instruction, priority), parent (parentIdentifier), or dependencies (addDependencies/removeDependencies, batch). Use parentIdentifier=null to move a task to the top level. For status changes use updateTaskStatus- **runTask**: Actually START a task β kicks off the assigned agent in a new (or continued) topic. Use this to launch execution; do NOT use updateTaskStatus(running) to start a task, that only flips a flag without executing. The task must have an assigneeAgentId- **runTasks**: Start multiple tasks in one call. Prefer this when launching a batch of related subtasks (e.g. all subtasks you just created); cuts down on tool calls and makes the start atomic from the user's perspective- **updateTaskStatus**: Change a task's status. If you mark a task as failed, include an error message explaining why. Use this to mark tasks completed/cancelled/paused/failed β NOT to start them (use runTask for that). Omitting identifier only works when there is a current task contextdiff --git a/packages/builtin-tool-task/src/types.ts b/packages/builtin-tool-task/src/types.tsindex 201afc41f70..1af19944255 100644--- a/packages/builtin-tool-task/src/types.ts+++ b/packages/builtin-tool-task/src/types.ts@@ -1,6 +1,9 @@import type { TaskStatus } from '@lobechat/types';export const TaskApiName = {+ /** Add a comment to a task */+ addTaskComment: 'addTaskComment',+/** Create a new task, optionally as a subtask of another task */createTask: 'createTask',@@ -10,7 +13,10 @@ export const TaskApiName = {/** Delete a task */deleteTask: 'deleteTask',- /** Edit a task's name, description, instruction, priority, or dependencies */+ /** Delete a task comment */+ deleteTaskComment: 'deleteTaskComment',++ /** Edit a task's name, description, instruction, priority, parent, or dependencies */editTask: 'editTask',/** List tasks with optional filters */@@ -22,6 +28,9 @@ export const TaskApiName = {/** Trigger async runs for multiple tasks in one call */runTasks: 'runTasks',+ /** Update a task comment */+ updateTaskComment: 'updateTaskComment',+/** Update a task's status (e.g. complete, cancel) */updateTaskStatus: 'updateTaskStatus',@@ -97,6 +106,38 @@ export interface ViewTaskState {success: boolean;}+// ==================== task comments ====================++export interface AddTaskCommentParams {+ content: string;+ identifier?: string;+}++export interface AddTaskCommentState {+ commentId?: string;+ identifier: string;+ success: boolean;+}++export interface UpdateTaskCommentParams {+ commentId: string;+ content: string;+}++export interface UpdateTaskCommentState {+ commentId: string;+ success: boolean;+}++export interface DeleteTaskCommentParams {+ commentId: string;+}++export interface DeleteTaskCommentState {+ commentId: string;+ success: boolean;+}+// ==================== editTask ====================export interface EditTaskParams {@@ -106,6 +147,7 @@ export interface EditTaskParams {identifier: string;instruction?: string;name?: string;+ parentIdentifier?: string | null;priority?: number;removeDependencies?: string[];}diff --git a/packages/prompts/src/prompts/task/buildTaskDetailPrompt.ts b/packages/prompts/src/prompts/task/buildTaskDetailPrompt.tsindex 3e452e823db..90bd3b94cee 100644--- a/packages/prompts/src/prompts/task/buildTaskDetailPrompt.ts+++ b/packages/prompts/src/prompts/task/buildTaskDetailPrompt.ts@@ -119,7 +119,7 @@ export const buildTaskDetailPrompt = (input: BuildTaskDetailPromptInput, now?: Dconst author = act.agentId ? 'π€ agent' : 'π€ user';const content = act.content || '';const truncated = content.length > 200 ? content.slice(0, 200) + '...' : content;- lines.push(` π ${ago} ${author} ${truncated}`);+ lines.push(` π ${ago} ${author} ${truncated}${idSuffix}`);}}}diff --git a/packages/prompts/src/prompts/task/index.ts b/packages/prompts/src/prompts/task/index.tsindex 46ea3d6b529..51f10ccee5e 100644--- a/packages/prompts/src/prompts/task/index.ts+++ b/packages/prompts/src/prompts/task/index.ts@@ -251,7 +251,7 @@ export const formatTaskDetail = (t: TaskDetailData): string => {const author = act.agentId ? 'π€ agent' : 'π€ user';const content = act.content || '';const truncated = content.length > 80 ? content.slice(0, 80) + '...' : content;- lines.push(` π ${act.time || ''} ${author} ${truncated}`);+ lines.push(` π ${act.time || ''} ${author} ${truncated}${idSuffix}`);}}}diff --git a/src/locales/default/plugin.ts b/src/locales/default/plugin.tsindex 7258a8b51fe..db0b3c4acaa 100644--- a/src/locales/default/plugin.ts+++ b/src/locales/default/plugin.ts@@ -261,11 +261,14 @@ export default {'builtins.lobe-skills.title': 'Skills','builtins.lobe-task.apiName.createTask': 'Create task','builtins.lobe-task.apiName.createTasks': 'Create tasks',+ 'builtins.lobe-task.apiName.addTaskComment': 'Add comment','builtins.lobe-task.apiName.deleteTask': 'Delete task',+ 'builtins.lobe-task.apiName.deleteTaskComment': 'Delete comment','builtins.lobe-task.apiName.editTask': 'Edit task','builtins.lobe-task.apiName.listTasks': 'List tasks','builtins.lobe-task.apiName.runTask': 'Run task','builtins.lobe-task.apiName.runTasks': 'Run tasks',+ 'builtins.lobe-task.apiName.updateTaskComment': 'Update comment','builtins.lobe-task.apiName.updateTaskStatus': 'Update status','builtins.lobe-task.apiName.viewTask': 'View task','builtins.lobe-task.create.subtaskOf': 'Subtask of {{parent}}',@@ -276,6 +279,8 @@ export default {'builtins.lobe-task.edit.blocksOn': 'blocks on','builtins.lobe-task.edit.description': 'description updated','builtins.lobe-task.edit.instruction': 'instruction updated',+ 'builtins.lobe-task.edit.parent': 'parent',+ 'builtins.lobe-task.edit.parentClear': 'top level','builtins.lobe-task.edit.priority': 'priority','builtins.lobe-task.edit.rename': 'rename','builtins.lobe-task.edit.unassign': 'unassign',diff --git a/src/server/routers/lambda/__tests__/integration/task.integration.test.ts b/src/server/routers/lambda/__tests__/integration/task.integration.test.tsindex 9b7540b00dd..ec8d67214a8 100644--- a/src/server/routers/lambda/__tests__/integration/task.integration.test.ts+++ b/src/server/routers/lambda/__tests__/integration/task.integration.test.ts@@ -187,6 +187,53 @@ describe('Task Router Integration', () => {const ch2Sub = detail.data.subtasks!.find((s) => s.name === 'Chapter 2');expect(ch2Sub?.blockedBy).toBeTruthy();});++ it('should reparent tasks and allow moving them back to top level', async () => {+ const parent = await caller.create({ instruction: 'Parent', name: 'Parent' });+ const newParent = await caller.create({ instruction: 'New parent', name: 'New Parent' });+ const child = await caller.create({+ instruction: 'Child',+ name: 'Child',+ parentTaskId: parent.data.id,+ });++ const reparented = await caller.update({+ id: child.data.identifier,+ parentTaskId: newParent.data.identifier,+ });++ expect(reparented.data.parentTaskId).toBe(newParent.data.id);++ const topLevel = await caller.update({+ id: child.data.identifier,+ parentTaskId: null,+ });++ expect(topLevel.data.parentTaskId).toBeNull();+ });++ it('should reject reparenting a task to itself or its descendant', async () => {+ const parent = await caller.create({ instruction: 'Parent', name: 'Parent' });+ const child = await caller.create({+ instruction: 'Child',+ name: 'Child',+ parentTaskId: parent.data.id,+ });++ await expect(+ caller.update({+ id: parent.data.identifier,+ parentTaskId: parent.data.identifier,+ }),+ ).rejects.toThrow('Task cannot be parented to itself');++ await expect(+ caller.update({+ id: parent.data.identifier,+ parentTaskId: child.data.identifier,+ }),+ ).rejects.toThrow('Task cannot be parented to its own descendant');+ });});describe('status transitions', () => {@@ -234,6 +281,34 @@ describe('Task Router Integration', () => {expect(commentActivities).toHaveLength(2);expect(commentActivities?.[0].content).toBe('First comment');});++ it('should add agent-authored comments and support update/delete', async () => {+ const task = await caller.create({ instruction: 'Test' });++ const added = await caller.addComment({+ authorAgentId: testAgentId,+ content: 'Agent progress note',+ id: task.data.id,+ });++ expect(added.data.authorAgentId).toBe(testAgentId);+ expect(added.data.authorUserId).toBeNull();++ await caller.updateComment({+ commentId: added.data.id,+ content: 'Updated progress note',+ });++ const updatedDetail = await caller.detail({ id: task.data.identifier });+ const updatedComment = updatedDetail.data.activities?.find((a) => a.id === added.data.id);+ expect(updatedComment?.content).toBe('Updated progress note');+ expect(updatedComment?.agentId).toBe(testAgentId);++ await caller.deleteComment({ commentId: added.data.id });++ const deletedDetail = await caller.detail({ id: task.data.identifier });+ expect(deletedDetail.data.activities?.some((a) => a.id === added.data.id)).toBe(false);+ });});describe('review config', () => {diff --git a/src/server/routers/lambda/task.ts b/src/server/routers/lambda/task.tsindex c5ffc863aef..e30b3ba5838 100644--- a/src/server/routers/lambda/task.ts+++ b/src/server/routers/lambda/task.ts@@ -60,6 +60,7 @@ const updateSchema = z.object({heartbeatTimeout: z.number().min(1).nullable().optional(),instruction: z.string().optional(),name: z.string().optional(),+ parentTaskId: z.string().nullable().optional(),priority: z.number().min(0).max(4).optional(),schedulePattern: z.string().nullable().optional(),scheduleTimezone: z.string().nullable().optional(),@@ -113,6 +114,32 @@ async function assertAssigneeAgentBelongsToUser(}}+async function resolveSafeParentTaskId(+ model: TaskModel,+ taskId: string,+ parentTaskId: string | null,+): Promise<string | null> {+ if (parentTaskId === null) return null;++ const parent = await resolveOrThrow(model, parentTaskId);+ if (parent.id === taskId) {+ throw new TRPCError({+ code: 'BAD_REQUEST',+ message: 'Task cannot be parented to itself',+ });+ }++ const descendants = await model.findAllDescendants(taskId);+ if (descendants.some((task) => task.id === parent.id)) {+ throw new TRPCError({+ code: 'BAD_REQUEST',+ message: 'Task cannot be parented to its own descendant',+ });+ }++ return parent.id;+}+export const taskRouter = router({reorderSubtasks: taskProcedure.input(@@ -170,6 +197,7 @@ export const taskRouter = router({addComment: taskProcedure.input(z.object({+ authorAgentId: z.string().optional(),briefId: z.string().optional(),content: z.string().min(1),id: z.string(),@@ -180,8 +208,10 @@ export const taskRouter = router({try {const model = ctx.taskModel;const task = await resolveOrThrow(model, input.id);+ await assertAssigneeAgentBelongsToUser(ctx.agentModel, input.authorAgentId);const comment = await model.addComment({- authorUserId: ctx.userId,+ authorAgentId: input.authorAgentId,+ authorUserId: input.authorAgentId ? undefined : ctx.userId,briefId: input.briefId,content: input.content,taskId: task.id,@@ -945,12 +975,18 @@ export const taskRouter = router({}),update: taskProcedure.input(idInput.merge(updateSchema)).mutation(async ({ input, ctx }) => {- const { id, ...data } = input;+ const { id, parentTaskId, ...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);+ const resolvedParentTaskId =+ parentTaskId === undefined+ ? undefined+ : await resolveSafeParentTaskId(model, resolved.id, parentTaskId);+ const updateData =+ parentTaskId === undefined ? data : { ...data, parentTaskId: resolvedParentTaskId };+ const task = await model.update(resolved.id, updateData);if (!task) throw new TRPCError({ code: 'NOT_FOUND', message: 'Task not found' });return { data: task, message: 'Task updated', success: true };} catch (error) {diff --git a/src/server/services/toolExecution/serverRuntimes/__tests__/task.test.ts b/src/server/services/toolExecution/serverRuntimes/__tests__/task.test.tsindex 26cf7657763..070c73175fe 100644--- a/src/server/services/toolExecution/serverRuntimes/__tests__/task.test.ts+++ b/src/server/services/toolExecution/serverRuntimes/__tests__/task.test.ts@@ -8,6 +8,54 @@ vi.mock('@/server/routers/lambda/task', () => ({}));describe('createTaskRuntime', () => {+ describe('task comments', () => {+ it('adds a comment to the current task with agent attribution', async () => {+ const taskCaller = {+ addComment: vi.fn().mockResolvedValue({ data: { id: 'comment-1' } }),+ };+ const runtime = createTaskRuntime({+ agentModel: { existsById: vi.fn() } as any,+ agentId: 'agt-manager',+ taskCaller: taskCaller as any,+ taskId: 'T-1',+ taskModel: {} as any,+ taskService: {} as any,+ });++ const result = await runtime.addTaskComment({ content: 'Keep the original parent.' });++ expect(result.success).toBe(true);+ expect(taskCaller.addComment).toHaveBeenCalledWith({+ authorAgentId: 'agt-manager',+ content: 'Keep the original parent.',+ id: 'T-1',+ });+ expect(result.content).toBe('Comment added to task T-1.');+ });++ it('updates and deletes comments by commentId', async () => {+ const taskCaller = {+ deleteComment: vi.fn().mockResolvedValue({ success: true }),+ updateComment: vi.fn().mockResolvedValue({ success: true }),+ };+ const runtime = createTaskRuntime({+ agentModel: { existsById: vi.fn() } as any,+ taskCaller: taskCaller as any,+ taskModel: {} as any,+ taskService: {} as any,+ });++ await runtime.updateTaskComment({ commentId: 'comment-1', content: 'Updated' });+ await runtime.deleteTaskComment({ commentId: 'comment-1' });++ expect(taskCaller.updateComment).toHaveBeenCalledWith({+ commentId: 'comment-1',+ content: 'Updated',+ });+ expect(taskCaller.deleteComment).toHaveBeenCalledWith({ commentId: 'comment-1' });+ });+ });+describe('normalizeListTasksParams', () => {it('defaults to top-level unfinished tasks for the current agent', () => {const result = normalizeListTasksParams({}, { currentAgentId: 'agt-1' });@@ -266,7 +314,7 @@ describe('createTaskRuntime', () => {update: vi.fn().mockResolvedValue({}),};const taskService = {} as any;- const taskCaller = {} as any;+ const taskCaller = { update: vi.fn().mockResolvedValue({}) } as any;return { agentModel, taskCaller, taskModel, taskService };};@@ -290,6 +338,7 @@ describe('createTaskRuntime', () => {expect(result.success).toBe(false);expect(result.content).toBe('Assignee agent not found: agt-other-user');expect(deps.taskModel.update).not.toHaveBeenCalled();+ expect(deps.taskCaller.update).not.toHaveBeenCalled();});it('allows clearing assigneeAgentId without ownership lookup', async () => {@@ -310,7 +359,55 @@ describe('createTaskRuntime', () => {expect(result.success).toBe(true);expect(deps.agentModel.existsById).not.toHaveBeenCalled();- expect(deps.taskModel.update).toHaveBeenCalledWith('task-1', { assigneeAgentId: null });+ expect(deps.taskCaller.update).toHaveBeenCalledWith({+ assigneeAgentId: null,+ id: 'task-1',+ });+ expect(deps.taskModel.update).not.toHaveBeenCalled();+ });++ it('delegates parentIdentifier to router update for resolution and safety validation', 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({+ identifier: 'T-1',+ parentIdentifier: 'T-43',+ });++ expect(result.success).toBe(true);+ expect(deps.taskCaller.update).toHaveBeenCalledWith({ id: 'task-1', parentTaskId: 'T-43' });+ expect(deps.taskModel.update).not.toHaveBeenCalled();+ expect(result.content).toContain('parent β T-43');+ });++ it('passes null parentIdentifier through to move a task to the top level', 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({+ identifier: 'T-1',+ parentIdentifier: null,+ });++ expect(result.success).toBe(true);+ expect(deps.taskCaller.update).toHaveBeenCalledWith({ id: 'task-1', parentTaskId: null });+ expect(deps.taskModel.update).not.toHaveBeenCalled();+ expect(result.content).toContain('parent cleared');});});diff --git a/src/server/services/toolExecution/serverRuntimes/task.ts b/src/server/services/toolExecution/serverRuntimes/task.tsindex afa65456a36..5a02d27f58e 100644--- a/src/server/services/toolExecution/serverRuntimes/task.ts+++ b/src/server/services/toolExecution/serverRuntimes/task.ts@@ -98,6 +98,33 @@ export const createTaskRuntime = ({};return {+ addTaskComment: async (args: { content: string; identifier?: string }) => {+ const id = args.identifier?.trim() || taskId;+ if (!id) {+ return {+ content: 'No task identifier provided and no current task context.',+ success: false,+ };+ }++ try {+ const result = await taskCaller.addComment({+ authorAgentId: agentId,+ content: args.content,+ id,+ });++ return {+ content: `Comment added to task ${id}.`,+ success: true,+ state: { commentId: result.data.id, identifier: id, success: true },+ };+ } catch (error) {+ const message = error instanceof Error ? error.message : 'Failed to add task comment';+ return { content: `Failed to add task comment: ${message}`, success: false };+ }+ },+createTask: async (args: CreateTaskArgs) => {const result = await createTaskImpl(args);const { identifier: _identifier, ...rest } = result;@@ -156,6 +183,20 @@ export const createTaskRuntime = ({};},+ deleteTaskComment: async (args: { commentId: string }) => {+ try {+ await taskCaller.deleteComment({ commentId: args.commentId });+ return {+ content: `Comment ${args.commentId} deleted.`,+ success: true,+ state: { commentId: args.commentId, success: true },+ };+ } catch (error) {+ const message = error instanceof Error ? error.message : 'Failed to delete task comment';+ return { content: `Failed to delete task comment: ${message}`, success: false };+ }+ },+editTask: async (args: {addDependencies?: string[];assigneeAgentId?: string | null;@@ -163,13 +204,21 @@ export const createTaskRuntime = ({identifier: string;instruction?: string;name?: string;+ parentIdentifier?: string | null;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 updateData: {+ assigneeAgentId?: string | null;+ description?: string;+ instruction?: string;+ name?: string;+ parentTaskId?: string | null;+ priority?: number;+ } = {};const changes: string[] = [];const ops: Promise<unknown>[] = [];@@ -194,13 +243,18 @@ export const createTaskRuntime = ({updateData.description = args.description;changes.push('description updated');}+ if (args.parentIdentifier !== undefined) {+ const parentIdentifier = args.parentIdentifier?.trim() || null;+ updateData.parentTaskId = parentIdentifier;+ changes.push(parentIdentifier ? `parent β ${parentIdentifier}` : 'parent cleared');+ }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));+ ops.push(taskCaller.update({ id: task.id, ...updateData }));}const applyDeps = async (@@ -344,6 +398,20 @@ export const createTaskRuntime = ({};},+ updateTaskComment: async (args: { commentId: string; content: string }) => {+ try {+ await taskCaller.updateComment({ commentId: args.commentId, content: args.content });+ return {+ content: `Comment ${args.commentId} updated.`,+ success: true,+ state: { commentId: args.commentId, success: true },+ };+ } catch (error) {+ const message = error instanceof Error ? error.message : 'Failed to update task comment';+ return { content: `Failed to update task comment: ${message}`, success: false };+ }+ },+updateTaskStatus: async (args: { error?: string; identifier?: string; status: TaskStatus }) => {const id = args.identifier || taskId;if (!id) {diff --git a/src/services/__tests__/task.test.ts b/src/services/__tests__/task.test.tsindex 1b770ab8198..155f261d146 100644--- a/src/services/__tests__/task.test.ts+++ b/src/services/__tests__/task.test.ts@@ -17,6 +17,7 @@ vi.mock('@/libs/trpc/client', () => ({clearAll: { mutate: vi.fn() },create: { mutate: vi.fn() },delete: { mutate: vi.fn() },+ deleteComment: { mutate: vi.fn() },deleteTopic: { mutate: vi.fn() },detail: { query: vi.fn() },find: { query: vi.fn() },@@ -38,6 +39,7 @@ vi.mock('@/libs/trpc/client', () => ({runReview: { mutate: vi.fn() },unpinDocument: { mutate: vi.fn() },update: { mutate: vi.fn() },+ updateComment: { mutate: vi.fn() },updateCheckpoint: { mutate: vi.fn() },updateConfig: { mutate: vi.fn() },updateReview: { mutate: vi.fn() },@@ -118,14 +120,33 @@ describe('TaskService', () => {});it('addComment should pass all params', async () => {- await taskService.addComment('T-1', 'Great work', { topicId: 'tpc_1' });+ await taskService.addComment('T-1', 'Great work', {+ authorAgentId: 'agt_1',+ topicId: 'tpc_1',+ });expect(lambdaClient.task.addComment.mutate).toHaveBeenCalledWith({+ authorAgentId: 'agt_1',content: 'Great work',id: 'T-1',topicId: 'tpc_1',});});+ it('updateComment should pass commentId and content', async () => {+ await taskService.updateComment('comment_1', 'Updated');+ expect(lambdaClient.task.updateComment.mutate).toHaveBeenCalledWith({+ commentId: 'comment_1',+ content: 'Updated',+ });+ });++ it('deleteComment should pass commentId', async () => {+ await taskService.deleteComment('comment_1');+ expect(lambdaClient.task.deleteComment.mutate).toHaveBeenCalledWith({+ commentId: 'comment_1',+ });+ });+it('addDependency should default type to blocks', async () => {await taskService.addDependency('T-1', 'T-2');expect(lambdaClient.task.addDependency.mutate).toHaveBeenCalledWith({diff --git a/src/services/task.ts b/src/services/task.tsindex 00923c0918b..7ed0e0e9fa9 100644--- a/src/services/task.ts+++ b/src/services/task.ts@@ -74,6 +74,7 @@ class TaskService {heartbeatTimeout?: number | null;instruction?: string;name?: string;+ parentTaskId?: string | null;priority?: number;// schedulePattern: cron expression for scheduled automation (e.g. '0 9 * * *')schedulePattern?: string | null;@@ -96,8 +97,11 @@ class TaskService {runReadySubtasks = async (id: string) => lambdaClient.task.runReadySubtasks.mutate({ id });- addComment = async (id: string, content: string, opts?: { briefId?: string; topicId?: string }) =>- lambdaClient.task.addComment.mutate({ content, id, ...opts });+ addComment = async (+ id: string,+ content: string,+ opts?: { authorAgentId?: string; briefId?: string; topicId?: string },+ ) => lambdaClient.task.addComment.mutate({ content, id, ...opts });deleteComment = async (commentId: string) =>lambdaClient.task.deleteComment.mutate({ commentId });diff --git a/src/store/task/slices/detail/action.test.ts b/src/store/task/slices/detail/action.test.tsindex c1c1059a77f..e3fa8cf0969 100644--- a/src/store/task/slices/detail/action.test.ts+++ b/src/store/task/slices/detail/action.test.ts@@ -181,6 +181,35 @@ describe('TaskDetailSliceAction', () => {expect(message.error).not.toHaveBeenCalled();});+ it('should refresh list and affected details when reparenting', async () => {+ const { mutate } = await import('@/libs/swr');+ useTaskStore.setState({+ activeTaskId: 'T-sub',+ taskDetailMap: {+ 'T-parent': {+ identifier: 'T-parent',+ instruction: 'Parent',+ status: 'backlog',+ subtasks: [{ assignee: null, identifier: 'T-sub', name: 'Sub', status: 'backlog' }],+ },+ 'T-sub': { identifier: 'T-sub', instruction: 'Sub', status: 'backlog' },+ },+ });++ const refreshTaskList = vi.fn().mockResolvedValue(undefined);+ useTaskStore.setState({ refreshTaskList } as any);+ vi.mocked(taskService.update).mockResolvedValue({ success: true } as any);++ await useTaskStore.getState().updateTask('T-sub', { parentTaskId: 'T-new-parent' });++ expect(taskService.update).toHaveBeenCalledWith('T-sub', { parentTaskId: 'T-new-parent' });+ expect(useTaskStore.getState().taskDetailMap['T-sub']).not.toHaveProperty('parentTaskId');+ expect(refreshTaskList).toHaveBeenCalled();+ expect(mutate).toHaveBeenCalledWith(['fetchTaskDetail', 'T-sub']);+ expect(mutate).toHaveBeenCalledWith(['fetchTaskDetail', 'T-parent']);+ expect(mutate).toHaveBeenCalledWith(['fetchTaskDetail', 'T-new-parent']);+ });+it('should refresh the parent that was patched even if activeTaskId changes mid-flight', async () => {const { mutate } = await import('@/libs/swr');useTaskStore.setState({diff --git a/src/store/task/slices/detail/action.ts b/src/store/task/slices/detail/action.tsindex d8abe19d4d1..9b87c0be80d 100644--- a/src/store/task/slices/detail/action.ts+++ b/src/store/task/slices/detail/action.ts@@ -25,6 +25,7 @@ export interface TaskUpdatePayload {description?: string;instruction?: string;name?: string;+ parentTaskId?: string | null;priority?: number;}@@ -64,10 +65,11 @@ export class TaskDetailSliceActionImpl {addComment = async (taskId: string,content: string,- opts?: { briefId?: string; topicId?: string },- ): Promise<void> => {- await taskService.addComment(taskId, content, opts);+ opts?: { authorAgentId?: string; briefId?: string; topicId?: string },+ ): Promise<Awaited<ReturnType<typeof taskService.addComment>>> => {+ const result = await taskService.addComment(taskId, content, opts);await this.internal_refreshTaskDetail(taskId);+ return result;};deleteComment = async (commentId: string, taskId?: string): Promise<void> => {@@ -225,8 +227,10 @@ export class TaskDetailSliceActionImpl {updateTask = async (id: string, data: TaskUpdatePayload): Promise<void> => {const { assigneeAgentId, ...rest } = data;+ const optimisticRest = { ...rest };+ delete optimisticRest.parentTaskId;const optimistic: Partial<TaskDetailData> = {- ...rest,+ ...optimisticRest,...(assigneeAgentId !== undefined ? { agentId: assigneeAgentId } : {}),};@@ -238,6 +242,7 @@ export class TaskDetailSliceActionImpl {const refreshPatchedTargets = async (): Promise<void> => {const targets = new Set<string>([id]);if (patchedParentId) targets.add(patchedParentId);+ if (data.parentTaskId) targets.add(data.parentTaskId);if (snapshotActiveTaskId) targets.add(snapshotActiveTaskId);await Promise.all(Array.from(targets).map((target) => this.internal_refreshTaskDetail(target)),@@ -262,7 +267,7 @@ export class TaskDetailSliceActionImpl {throw error;}- if (assigneeAgentId !== undefined) {+ if (assigneeAgentId !== undefined || data.parentTaskId !== undefined) {await Promise.all([this.#get().refreshTaskList(), refreshPatchedTargets()]).catch(() => {});}};