🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
🐛 fix(task): move an unfiled task tree into a project together (#23214)
YuTengjing2654a8477e67
diff --git a/apps/server/src/routers/lambda/task/index.procedures.test.ts b/apps/server/src/routers/lambda/task/index.procedures.test.tsindex 522b8c0b340..80e764f83bd 100644--- a/apps/server/src/routers/lambda/task/index.procedures.test.ts+++ b/apps/server/src/routers/lambda/task/index.procedures.test.ts@@ -57,6 +57,7 @@ function expected(): Array<['groupList', 'query', 12],['heartbeat', 'mutation', 13],['list', 'query', 12],+ ['moveTreeToProject', 'mutation', 13],['pinDocument', 'mutation', 13],['previewSubtaskLayers', 'query', 12],['releaseTaskLock', 'mutation', 13],diff --git a/apps/server/src/routers/lambda/task/update.ts b/apps/server/src/routers/lambda/task/update.tsindex 2a67018ead0..66a5b9cfbb0 100644--- a/apps/server/src/routers/lambda/task/update.ts+++ b/apps/server/src/routers/lambda/task/update.ts@@ -2,6 +2,7 @@ import { TASK_STATUSES } from '@lobechat/builtin-tool-task';import { TRPCError } from '@trpc/server';import { z } from 'zod';+import { TaskTreeProjectMoveError } from '@/database/models/task';import { TaskTakeOverError } from '@/database/repositories/taskSubtree';import type { LobeChatDatabase } from '@/database/type';import { assertAgentUsableBy } from '@/database/utils/agent-access';@@ -9,7 +10,11 @@ import { router } from '@/libs/trpc/lambda';import { publishResourceEvent } from '@/server/services/resourceEvents';import { TaskService } from '@/server/services/task';import { notifyAssignedBestEffort } from '@/server/services/task/assignmentNotification';-import { resolveTaskPatchInvariants } from '@/server/services/task/patchValidation';+import {+ assertProjectReadable,+ projectMoveRefused,+ resolveTaskPatchInvariants,+} from '@/server/services/task/patchValidation';import {schedulePatternSchema,scheduleTimezoneSchema,@@ -161,6 +166,53 @@ export const updateRouter = router({});}}),+ /**+ * File a root task without a project, with all its subtasks, under a project.+ * `update` moves one row and refuses to split a task from its subtasks, so a+ * task tree could otherwise never enter a project; see+ * `TaskModel.moveUnfiledTreeToProject` for which trees can move.+ */+ moveTreeToProject: taskProcedureWrite+ .input(idInput.extend({ projectId: z.string().trim().min(1) }))+ .mutation(async ({ input, ctx }) => {+ try {+ const resolved = await resolveTaskOrThrow(ctx.taskModel, input.id);+ await assertProjectReadable(+ {+ serverDB: ctx.serverDB,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId ?? undefined,+ },+ input.projectId,+ );+ // Same edit-lock contract as `update`.+ if (ctx.workspaceId) {+ const blockedBy = await ctx.editLockService.getBlockingHolder('task', resolved.id);+ if (blockedBy) {+ throw new TRPCError({+ cause: { data: { code: 'DocumentLocked' } },+ code: 'CONFLICT',+ message: 'Task is being edited by another user',+ });+ }+ }++ const task = await ctx.taskModel.moveUnfiledTreeToProject(resolved.id, input.projectId);+ if (!task) throw new TRPCError({ code: 'NOT_FOUND', message: 'Task not found' });+ return { data: task, message: 'Task tree moved', success: true };+ } catch (error) {+ if (error instanceof TaskTreeProjectMoveError) {+ throw projectMoveRefused(error.reason, error.message);+ }+ if (error instanceof TRPCError) throw error;+ console.error('[task:moveTreeToProject]', error);+ throw new TRPCError({+ cause: error,+ code: 'INTERNAL_SERVER_ERROR',+ message: 'Failed to move task tree',+ });+ }+ }),updateVisibility: taskProcedureWrite.input(idInput.merge(diff --git a/apps/server/src/services/task/patchValidation.test.ts b/apps/server/src/services/task/patchValidation.test.tsindex 8ea0973804f..fcef201fa21 100644--- a/apps/server/src/services/task/patchValidation.test.ts+++ b/apps/server/src/services/task/patchValidation.test.ts@@ -302,6 +302,7 @@ describe('resolveTaskPatchInvariants project', () => {await expect(resolveTaskPatchInvariants(context, { data: { projectId }, id: 'task-1' }),).rejects.toMatchObject({+ cause: { data: { projectMoveRefusal: 'has_parent' } },code: 'BAD_REQUEST',message: 'Subtask must belong to the same project as its parent',});@@ -340,7 +341,11 @@ describe('resolveTaskPatchInvariants project', () => {taskModel.hasSubtaskOutsideProject.mockResolvedValue(true);await expect(resolveTaskPatchInvariants(context, { data: { projectId: 'project-2' }, id: 'task-1' }),- ).rejects.toMatchObject({ code: 'BAD_REQUEST', message: expect.stringContaining('subtasks') });+ ).rejects.toMatchObject({+ cause: { data: { projectMoveRefusal: 'split_subtasks' } },+ code: 'BAD_REQUEST',+ message: expect.stringContaining('subtasks'),+ });expect(taskModel.hasSubtaskOutsideProject).toHaveBeenCalledWith('task-1', 'project-2');});@@ -350,6 +355,7 @@ describe('resolveTaskPatchInvariants project', () => {await expect(resolveTaskPatchInvariants(context, { data: { projectId: 'project-2' }, id: 'task-1' }),).rejects.toMatchObject({+ cause: { data: { projectMoveRefusal: 'external_dependency' } },code: 'BAD_REQUEST',message: expect.stringContaining('dependencies cannot cross project boundaries'),});diff --git a/apps/server/src/services/task/patchValidation.ts b/apps/server/src/services/task/patchValidation.tsindex f319706de7e..99f8d952627 100644--- a/apps/server/src/services/task/patchValidation.ts+++ b/apps/server/src/services/task/patchValidation.ts@@ -1,4 +1,4 @@-import type { TaskContext } from '@lobechat/types';+import type { TaskContext, TaskProjectMoveRefusal } from '@lobechat/types';import { TRPCError } from '@trpc/server';import type { AgentModel } from '@/database/models/agent';@@ -84,13 +84,23 @@ export async function assertAssigneeAgentBelongsToUser(* same bar `createTask` applies, and the same NOT_FOUND: another workspace's or* member's private project is indistinguishable from one that does not exist.*/-async function assertProjectReadable(ctx: TaskPatchInvariantContext, projectId: string) {+export async function assertProjectReadable(+ ctx: Pick<TaskPatchInvariantContext, 'serverDB' | 'userId' | 'workspaceId'>,+ projectId: string,+) {const project = await new ProjectModel(ctx.serverDB, ctx.userId, ctx.workspaceId).findById(projectId,);if (!project) throw new TRPCError({ code: 'NOT_FOUND', message: 'Project not found' });}+/**+ * A refused project move, carrying the reason as `errorData.projectMoveRefusal`+ * so the client can name what blocks it.+ */+export const projectMoveRefused = (reason: TaskProjectMoveRefusal, message: string) =>+ new TRPCError({ cause: { data: { projectMoveRefusal: reason } }, code: 'BAD_REQUEST', message });+/*** Moving a task leaves its subtasks and dependencies where they are, and neither* link may cross a project boundary (`createTask`, `addDependency` and reparenting@@ -107,25 +117,25 @@ async function assertProjectMoveKeepsLinks(if (!parentChanges && task.parentTaskId) {const parent = await model.findById(task.parentTaskId);if (parent && parent.projectId !== projectId) {- throw new TRPCError({- code: 'BAD_REQUEST',- message: 'Subtask must belong to the same project as its parent',- });+ throw projectMoveRefused(+ 'has_parent',+ 'Subtask must belong to the same project as its parent',+ );}}if (await model.hasSubtaskOutsideProject(task.id, projectId)) {- throw new TRPCError({- code: 'BAD_REQUEST',- message: 'Task has subtasks in its current project. Move or detach them first',- });+ throw projectMoveRefused(+ 'split_subtasks',+ 'Task has subtasks in its current project. Move or detach them first',+ );}if (await model.hasDependencyOutsideProject(task.id, projectId)) {- throw new TRPCError({- code: 'BAD_REQUEST',- message: 'Task dependencies cannot cross project boundaries. Remove them first',- });+ throw projectMoveRefused(+ 'external_dependency',+ 'Task dependencies cannot cross project boundaries. Remove them first',+ );}}diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex f7bd049987f..1762588f94b 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -2947,7 +2947,14 @@"taskProject.inheritedFromParent": "A subtask stays in its parent's project","taskProject.label": "Project","taskProject.loadFailed": "Failed to load projects",- "taskProject.moveRefused": "Can't move this task while its parent, subtasks or dependencies stay in the current project. Move or detach them first.",+ "taskProject.moveFailed": "Can't move this task to the project.",+ "taskProject.moveRefusedDependency": "Tasks here depend on tasks outside this task tree. Remove those dependencies first.",+ "taskProject.moveRefusedFiledSubtask": "Some subtasks already belong to a project, so the task tree can't move together.",+ "taskProject.moveRefusedHasParent": "A subtask stays in its parent's project. Move the top-level task instead.",+ "taskProject.moveRefusedSplitSubtasks": "This task's subtasks can't be left behind. Only a task tree without a project can move into one together.",+ "taskProject.moveTree.content": "This task and all of its subtasks ({{count}}) will move to “{{project}}”.",+ "taskProject.moveTree.ok": "Move all",+ "taskProject.moveTree.title": "Move with subtasks?","taskProject.noMatch": "No matching project","taskProject.none": "No project","taskProject.searchPlaceholder": "Search projects…",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex 1bd9bb13073..e41db3077a1 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -2947,7 +2947,14 @@"taskProject.inheritedFromParent": "子任务归属于父任务所在的项目","taskProject.label": "项目","taskProject.loadFailed": "项目加载失败",- "taskProject.moveRefused": "父任务、子任务或依赖仍在当前项目中,无法移动此任务。请先移动或解除它们。",+ "taskProject.moveFailed": "无法将此任务移到该项目。",+ "taskProject.moveRefusedDependency": "此任务树中的任务依赖树外的任务,请先解除这些依赖。",+ "taskProject.moveRefusedFiledSubtask": "部分子任务已属于某个项目,无法整组移动。",+ "taskProject.moveRefusedHasParent": "子任务跟随父任务所在的项目,请移动顶层任务。",+ "taskProject.moveRefusedSplitSubtasks": "子任务不能留在原处。只有没有项目的任务树才能整组移入项目。",+ "taskProject.moveTree.content": "此任务及其全部子任务({{count}} 个)将移到「{{project}}」。",+ "taskProject.moveTree.ok": "全部移动",+ "taskProject.moveTree.title": "连同子任务一起移动?","taskProject.noMatch": "未找到匹配的项目","taskProject.none": "无项目","taskProject.searchPlaceholder": "搜索项目…",diff --git a/packages/database/src/models/__tests__/task.surface.test.ts b/packages/database/src/models/__tests__/task.surface.test.tsindex 220dc49f8d2..b18c93df70f 100644--- a/packages/database/src/models/__tests__/task.surface.test.ts+++ b/packages/database/src/models/__tests__/task.surface.test.ts@@ -37,6 +37,7 @@ describe('TaskModel public surface', () => {it('keeps the module exports', () => {expect(Object.keys(taskModule).sort()).toEqual(['TaskModel',+ 'TaskTreeProjectMoveError','isTaskIdentifierUniqueViolation','taskActivityActor',]);@@ -86,6 +87,7 @@ describe('TaskModel public surface', () => {'list','lockForStatusChange','lockForUpdate',+ 'moveUnfiledTreeToProject','pinDocument','removeDependency','reorder',diff --git a/packages/database/src/models/task/index.ts b/packages/database/src/models/task/index.tsindex 49c0e1609ff..fc2ddfdf5bb 100644--- a/packages/database/src/models/task/index.ts+++ b/packages/database/src/models/task/index.ts@@ -47,6 +47,7 @@ import {} from './utils';export type { InterruptedRunningTopic, OrphanedRunningTopic } from './scheduling';+export { TaskTreeProjectMoveError } from './tree';export { isTaskIdentifierUniqueViolation, taskActivityActor } from './utils';export class TaskModel {@@ -307,6 +308,14 @@ export class TaskModel {return tree.hasSubtaskOutsideProject(this.ctx, taskId, projectId);}+ /**+ * File an unfiled root task and all its descendants under `projectId` at once.+ * Throws `TaskTreeProjectMoveError` when the tree cannot move as a whole.+ */+ async moveUnfiledTreeToProject(rootId: string, projectId: string): Promise<TaskItem | null> {+ return tree.moveUnfiledTreeToProject(this.ctx, rootId, projectId);+ }+async getTaskTree(rootTaskId: string): Promise<TaskItem[]> {return tree.getTaskTree(this.ctx, rootTaskId);}diff --git a/packages/database/src/models/task/tree.test.ts b/packages/database/src/models/task/tree.test.tsindex ec13ee31d87..d5d0ee212f9 100644--- a/packages/database/src/models/task/tree.test.ts+++ b/packages/database/src/models/task/tree.test.ts@@ -5,7 +5,7 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { getTestDB } from '../../core/getTestDB';import { projects, users, workspaceMembers, workspaces } from '../../schemas';import type { LobeChatDatabase } from '../../type';-import { TaskModel } from './index';+import { TaskModel, TaskTreeProjectMoveError } from './index';const serverDB: LobeChatDatabase = await getTestDB();@@ -88,3 +88,105 @@ describe('TaskModel.hasSubtaskOutsideProject', () => {expect(await outsider.hasSubtaskOutsideProject(parent.id, target)).toBe(false);});});++describe('TaskModel.moveUnfiledTreeToProject', () => {+ const refusal = (promise: Promise<unknown>) =>+ promise.then(+ () => 'moved',+ (error: unknown) => (error instanceof TaskTreeProjectMoveError ? error.reason : error),+ );++ it('files an unfiled root and every descendant under the project', async () => {+ const model = new TaskModel(serverDB, ownerId, workspaceId);+ const target = await projectIn('task-tree-move-a');+ const root = await model.create({ instruction: 'root' });+ const child = await model.create({ instruction: 'child', parentTaskId: root.id });+ const grandchild = await model.create({ instruction: 'grandchild', parentTaskId: child.id });+ // A dependency inside the tree moves with it.+ await model.addDependency(grandchild.id, child.id);++ const moved = await model.moveUnfiledTreeToProject(root.id, target);++ expect(moved?.projectId).toBe(target);+ const rows = await model.findByIds([root.id, child.id, grandchild.id]);+ expect(rows.map((row) => row.projectId)).toEqual([target, target, target]);+ });++ it("moves another member's private subtask the caller cannot read", async () => {+ const owner = new TaskModel(serverDB, ownerId, workspaceId);+ const member = new TaskModel(serverDB, memberId, workspaceId);+ const target = await projectIn('task-tree-move-b');+ const root = await owner.create({ instruction: 'root', visibility: 'public' });+ const hidden = await member.create({+ instruction: 'hidden child',+ parentTaskId: root.id,+ visibility: 'private',+ });++ await owner.moveUnfiledTreeToProject(root.id, target);++ expect((await member.findById(hidden.id))?.projectId).toBe(target);+ });++ it('leaves a trashed subtask behind', async () => {+ const model = new TaskModel(serverDB, ownerId, workspaceId);+ const target = await projectIn('task-tree-move-c');+ const root = await model.create({ instruction: 'root' });+ const trashed = await model.create({ instruction: 'trashed', parentTaskId: root.id });+ await model.update(trashed.id, { deletedAt: new Date(), isDeleted: true });++ expect(await refusal(model.moveUnfiledTreeToProject(root.id, target))).toBe('moved');+ });++ it('refuses a subtask, a filed task and a tree with a filed descendant', async () => {+ const model = new TaskModel(serverDB, ownerId, workspaceId);+ const filed = await projectIn('task-tree-move-d');+ const target = await projectIn('task-tree-move-e');++ const root = await model.create({ instruction: 'root' });+ const child = await model.create({ instruction: 'child', parentTaskId: root.id });+ expect(await refusal(model.moveUnfiledTreeToProject(child.id, target))).toBe('has_parent');++ const filedRoot = await model.create({ instruction: 'filed root', projectId: filed });+ expect(await refusal(model.moveUnfiledTreeToProject(filedRoot.id, target))).toBe('filed_task');++ // Bypass the create-time rule to reach a state an older write left behind.+ await model.update(child.id, { projectId: filed });+ expect(await refusal(model.moveUnfiledTreeToProject(root.id, target))).toBe('filed_subtask');+ expect((await model.findById(root.id))?.projectId).toBeNull();+ });++ it('refuses a dependency reaching a live task outside the tree, in either direction', async () => {+ const model = new TaskModel(serverDB, ownerId, workspaceId);+ const target = await projectIn('task-tree-move-f');+ const root = await model.create({ instruction: 'root' });+ const child = await model.create({ instruction: 'child', parentTaskId: root.id });+ const outsider = await model.create({ instruction: 'outsider' });++ await model.addDependency(outsider.id, child.id);+ expect(await refusal(model.moveUnfiledTreeToProject(root.id, target))).toBe(+ 'external_dependency',+ );+ expect((await model.findById(child.id))?.projectId).toBeNull();++ // A trashed outsider no longer blocks the move.+ await model.update(outsider.id, { deletedAt: new Date(), isDeleted: true });+ const blocker = await model.create({ instruction: 'blocker' });+ await model.addDependency(root.id, blocker.id);+ expect(await refusal(model.moveUnfiledTreeToProject(root.id, target))).toBe(+ 'external_dependency',+ );+ await model.update(blocker.id, { deletedAt: new Date(), isDeleted: true });+ expect(await refusal(model.moveUnfiledTreeToProject(root.id, target))).toBe('moved');+ });++ it('returns null for a root the caller cannot see', async () => {+ const owner = new TaskModel(serverDB, ownerId, workspaceId);+ const member = new TaskModel(serverDB, memberId, workspaceId);+ const target = await projectIn('task-tree-move-g');+ const root = await owner.create({ instruction: 'root', visibility: 'private' });++ expect(await member.moveUnfiledTreeToProject(root.id, target)).toBeNull();+ expect((await owner.findById(root.id))?.projectId).toBeNull();+ });+});diff --git a/packages/database/src/models/task/tree.ts b/packages/database/src/models/task/tree.tsindex f771c675f92..e5ccc6cda8c 100644--- a/packages/database/src/models/task/tree.ts+++ b/packages/database/src/models/task/tree.ts@@ -1,5 +1,6 @@-import type { TaskItem } from '@lobechat/types';-import { and, eq, inArray, isNotNull, ne, sql } from 'drizzle-orm';+import type { TaskItem, TaskProjectMoveRefusal } from '@lobechat/types';+import { and, eq, inArray, isNotNull, ne, notInArray, or, sql } from 'drizzle-orm';+import { alias } from 'drizzle-orm/pg-core';import {taskActivities,@@ -358,3 +359,115 @@ export const deleteTasksByIds = async (return result.length;};++/** Why `moveUnfiledTreeToProject` refused to move a task tree. */+export class TaskTreeProjectMoveError extends Error {+ constructor(readonly reason: TaskProjectMoveRefusal) {+ super(`Task tree cannot move to the project: ${reason}`);+ this.name = 'TaskTreeProjectMoveError';+ }+}++/**+ * File a root task that has no project, together with every descendant, under+ * `projectId` in one transaction.+ *+ * A subtask must share its parent's project and a dependency must stay inside+ * one project, while a plain project patch moves only the one row. So a root+ * with subtasks could never enter a project: moving the root splits it from its+ * subtasks, and moving a subtask splits it from its root. Moving the whole tree+ * at once keeps both rules.+ *+ * Only an unfiled tree moves: every task in it must have no project, so this+ * never pulls a task out of a project it was deliberately filed under. The+ * subtree is collected visibility-blind (`seqOwnership`) and without trashed+ * rows, like `hasSubtaskOutsideProject`: another member's private subtask is+ * hidden from the caller but must follow its parent, while a trashed one no+ * longer counts for either rule. Every row is locked before the checks+ * so a concurrent reparent or dependency cannot slip in between check and write.+ *+ * Returns the updated root, or `null` when the caller cannot see the root.+ */+export const moveUnfiledTreeToProject = async (+ ctx: TaskModelContext,+ rootId: string,+ projectId: string,+): Promise<TaskItem | null> =>+ ctx.db.transaction(async (tx) => {+ const [root] = await tx+ .select({ id: tasks.id, parentTaskId: tasks.parentTaskId, projectId: tasks.projectId })+ .from(tasks)+ .where(and(eq(tasks.id, rootId), taskOwnership(ctx)))+ .for('update')+ .limit(1);+ if (!root) return null;+ if (root.parentTaskId) throw new TaskTreeProjectMoveError('has_parent');+ if (root.projectId !== null) throw new TaskTreeProjectMoveError('filed_task');++ const treeIds = [root.id];+ // Guards against a corrupt parent cycle, which would otherwise loop forever.+ const seen = new Set(treeIds);+ let frontier = [root.id];+ while (frontier.length > 0) {+ const children = await tx+ .select({ id: tasks.id, projectId: tasks.projectId })+ .from(tasks)+ .where(+ and(+ inArray(tasks.parentTaskId, frontier),+ seqOwnership(ctx),+ notTrashed(tasks.isDeleted),+ ),+ )+ .for('update');+ if (children.some((child) => child.projectId !== null)) {+ throw new TaskTreeProjectMoveError('filed_subtask');+ }+ frontier = children.map((child) => child.id).filter((id) => !seen.has(id));+ for (const id of frontier) seen.add(id);+ treeIds.push(...frontier);+ }++ // A dependency inside the tree moves with it; one reaching a live task+ // outside the tree would end up crossing into another project.+ const outside = alias(tasks, 'outside_task');+ const [externalLink] = await tx+ .select({ id: taskDependencies.id })+ .from(taskDependencies)+ .innerJoin(+ outside,+ or(+ and(+ inArray(taskDependencies.taskId, treeIds),+ eq(outside.id, taskDependencies.dependsOnId),+ ),+ and(+ inArray(taskDependencies.dependsOnId, treeIds),+ eq(outside.id, taskDependencies.taskId),+ ),+ ),+ )+ .where(+ and(+ notInArray(outside.id, treeIds),+ notTrashed(outside.isDeleted),+ sql`${outside.projectId} IS DISTINCT FROM ${projectId}`,+ ),+ )+ .limit(1);+ if (externalLink) throw new TaskTreeProjectMoveError('external_dependency');++ const stamp = new Date();+ const [updated] = await tx+ .update(tasks)+ .set({ projectId, updatedAt: stamp })+ .where(and(eq(tasks.id, root.id), taskOwnership(ctx)))+ .returning();+ if (treeIds.length > 1) {+ await tx+ .update(tasks)+ .set({ projectId, updatedAt: stamp })+ .where(and(inArray(tasks.id, treeIds.slice(1)), seqOwnership(ctx)));+ }+ return updated ?? null;+ });diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex 3be1b39d740..95ac71cb0f8 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -4501,8 +4501,19 @@ export default {'taskProject.inheritedFromParent': "A subtask stays in its parent's project",'taskProject.label': 'Project','taskProject.loadFailed': 'Failed to load projects',- 'taskProject.moveRefused':- "Can't move this task while its parent, subtasks or dependencies stay in the current project. Move or detach them first.",+ 'taskProject.moveFailed': "Can't move this task to the project.",+ 'taskProject.moveRefusedDependency':+ 'Tasks here depend on tasks outside this task tree. Remove those dependencies first.',+ 'taskProject.moveRefusedFiledSubtask':+ "Some subtasks already belong to a project, so the task tree can't move together.",+ 'taskProject.moveRefusedHasParent':+ "A subtask stays in its parent's project. Move the top-level task instead.",+ 'taskProject.moveRefusedSplitSubtasks':+ "This task's subtasks can't be left behind. Only a task tree without a project can move into one together.",+ 'taskProject.moveTree.content':+ 'This task and all of its subtasks ({{count}}) will move to “{{project}}”.',+ 'taskProject.moveTree.ok': 'Move all',+ 'taskProject.moveTree.title': 'Move with subtasks?','taskProject.noMatch': 'No matching project','taskProject.none': 'No project','taskProject.searchPlaceholder': 'Search projects…',diff --git a/packages/types/src/task/index.ts b/packages/types/src/task/index.tsindex bca65a294f4..67a68d812ee 100644--- a/packages/types/src/task/index.ts+++ b/packages/types/src/task/index.ts@@ -449,6 +449,23 @@ export interface TaskDetailSubtaskRunningTopic {operationId?: string | null;}+/**+ * Why the server refused to move a task into or out of a project. Sent as+ * `errorData.projectMoveRefusal` on the BAD_REQUEST, so the client can say what+ * blocks the move instead of one generic message.+ */+export type TaskProjectMoveRefusal =+ /** A dependency would link tasks in different projects. */+ | 'external_dependency'+ /** A subtask of the tree already belongs to a project. */+ | 'filed_subtask'+ /** The task already belongs to a project, so its tree cannot move as a whole. */+ | 'filed_task'+ /** The task is a subtask; it shares its parent's project. */+ | 'has_parent'+ /** Moving only this task would split it from its subtasks. */+ | 'split_subtasks';+export interface TaskDetailSubtask {/** ISO time the subtask was archived; null when it is not archived. */archivedAt?: string | null;diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskProperties.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskProperties.tsxindex 7590c24bfbd..5fa7b7eff3e 100644--- a/src/features/AgentTasks/AgentTaskDetail/TaskProperties.tsx+++ b/src/features/AgentTasks/AgentTaskDetail/TaskProperties.tsx@@ -75,6 +75,7 @@ const TaskProperties = memo(() => {const setTaskLabels = useTaskStore((s) => s.setTaskLabels);const projectId = useTaskStore(taskDetailSelectors.activeTaskProjectId);const hasParent = !!useTaskStore(taskDetailSelectors.activeTaskParent);+ const subtaskCount = useTaskStore(taskDetailSelectors.activeTaskSubtaskCount);// The picker renders nothing while the Projects lab is off, which would leave// the group's title standing over an empty row.const enableProjects = useUserStore(labPreferSelectors.enableProjects);@@ -252,6 +253,7 @@ const TaskProperties = memo(() => {<ProjectSelectorfullWidthdisabledReason={hasParent ? t('taskProject.inheritedFromParent') : undefined}+ subtaskCount={subtaskCount}taskIdentifier={taskId}value={projectId}>diff --git a/src/features/AgentTasks/features/ProjectSelector.test.tsx b/src/features/AgentTasks/features/ProjectSelector.test.tsxindex b21a1a810db..d0eff2c77cc 100644--- a/src/features/AgentTasks/features/ProjectSelector.test.tsx+++ b/src/features/AgentTasks/features/ProjectSelector.test.tsx@@ -10,6 +10,8 @@ import TaskProjectValue from './TaskProjectValue';const state = vi.hoisted(() => ({allowed: true,+ confirmModal: vi.fn(),+ moveTaskTreeToProject: vi.fn(),enabled: true,projects: undefined as { avatar?: string; id: string; name: string }[] | undefined,revalidate: vi.fn(),@@ -19,6 +21,7 @@ const state = vi.hoisted(() => ({vi.mock('@lobehub/ui', async (importOriginal) => ({...(await importOriginal<object>()),+ confirmModal: state.confirmModal,Popover: ({children,content,@@ -97,7 +100,8 @@ vi.mock('@/store/project', () => ({}));vi.mock('@/store/task', () => ({- useTaskStore: (selector: (s: unknown) => unknown) => selector({ updateTask: state.updateTask }),+ useTaskStore: (selector: (s: unknown) => unknown) =>+ selector({ moveTaskTreeToProject: state.moveTaskTreeToProject, updateTask: state.updateTask }),}));vi.mock('@/store/user', () => ({@@ -138,6 +142,8 @@ beforeEach(() => {];state.revalidate.mockClear();state.sync = { error: undefined, isHydrated: true, isValidating: false };+ state.confirmModal.mockReset();+ state.moveTaskTreeToProject.mockReset();state.updateTask.mockReset();state.updateTask.mockResolvedValue(undefined);});@@ -238,6 +244,49 @@ describe('ProjectSelector', () => {expect(state.updateTask).toHaveBeenLastCalledWith('T-1', { projectId: null });});+ it('confirms before filing a task with subtasks, then moves the whole tree', async () => {+ render(+ <ProjectSelector subtaskCount={44} taskIdentifier="T-1" value={null}>+ <button data-testid="trigger">row</button>+ </ProjectSelector>,+ );+ open();+ fireEvent.click(screen.getByText('Apollo'));++ expect(state.updateTask).not.toHaveBeenCalled();+ expect(state.confirmModal).toHaveBeenCalledTimes(1);+ const [options] = state.confirmModal.mock.calls[0];+ expect(options.title).toBe('taskProject.moveTree.title');+ expect(state.moveTaskTreeToProject).not.toHaveBeenCalled();++ await options.onOk();+ expect(state.moveTaskTreeToProject).toHaveBeenCalledWith('T-1', 'p1');+ });++ it('files a task with no visible subtasks as a tree, with no confirmation', () => {+ const { rerender } = render(+ <ProjectSelector subtaskCount={0} taskIdentifier="T-1" value={null}>+ <button data-testid="trigger">row</button>+ </ProjectSelector>,+ );+ open();+ fireEvent.click(screen.getByText('Apollo'));+ // Other members' private subtasks are invisible yet must move along.+ expect(state.moveTaskTreeToProject).toHaveBeenCalledWith('T-1', 'p1');+ expect(state.updateTask).not.toHaveBeenCalled();++ // A filed tree cannot move as a whole; the plain save gets the refusal.+ rerender(+ <ProjectSelector subtaskCount={3} taskIdentifier="T-1" value="p1">+ <button data-testid="trigger">row</button>+ </ProjectSelector>,+ );+ open();+ fireEvent.click(screen.getByText('Website Redesign'));+ expect(state.updateTask).toHaveBeenLastCalledWith('T-1', { projectId: 'p2' });+ expect(state.confirmModal).not.toHaveBeenCalled();+ });+it('does not write when the current project is picked again', () => {render(<ProjectSelector taskIdentifier="T-1" value="p1">diff --git a/src/features/AgentTasks/features/ProjectSelector.tsx b/src/features/AgentTasks/features/ProjectSelector.tsxindex 4d05e7f7c7b..1a23209d9f2 100644--- a/src/features/AgentTasks/features/ProjectSelector.tsx+++ b/src/features/AgentTasks/features/ProjectSelector.tsx@@ -1,4 +1,4 @@-import { Button, cssVar, Flexbox, Icon, Popover, Text, Tooltip } from '@lobehub/ui';+import { Button, confirmModal, cssVar, Flexbox, Icon, Popover, Text, Tooltip } from '@lobehub/ui';import { cssVar as sxVar } from '@lobehub/ui/stylex/cssVar.stylex';import * as stylex from '@stylexjs/stylex';import { CheckIcon, FolderXIcon } from 'lucide-react';@@ -58,6 +58,12 @@ interface ProjectSelectorProps {fullWidth?: boolean;/** Reports the pick instead of saving it, for a composer holding it in a draft. */onChange?: (projectId: string | null) => void;+ /**+ * Visible subtasks the saved task has, at every depth. A task without a+ * project enters one together with its subtasks, after a confirmation when+ * this is above 0.+ */+ subtaskCount?: number;/** The task a pick is saved to when there is no `onChange`. */taskIdentifier?: string;value?: string | null;@@ -69,11 +75,12 @@ interface ProjectSelectorProps {* Projects lab is off, so no host can offer a feature the user has not enabled.*/const ProjectSelector = memo<ProjectSelectorProps>(- ({ children, disabledReason, fullWidth, onChange, taskIdentifier, value }) => {+ ({ children, disabledReason, fullWidth, onChange, subtaskCount = 0, taskIdentifier, value }) => {const { t } = useTranslation('chat');const enabled = useUserStore(labPreferSelectors.enableProjects);const { allowed: canEdit, reason } = usePermission('create_content');const updateTask = useTaskStore((s) => s.updateTask);+ const moveTaskTreeToProject = useTaskStore((s) => s.moveTaskTreeToProject);const [open, setOpen] = useState(false);const [search, setSearch] = useState('');@@ -135,8 +142,32 @@ const ProjectSelector = memo<ProjectSelectorProps>(onChange(projectId);return;}+ if (!taskIdentifier) return;+ // A subtask must share its parent's project, so a task without a project+ // enters one together with its subtasks. That includes subtasks the+ // caller cannot see (other members' private ones), so the tree move runs+ // even when `subtaskCount` is 0; only the confirmation needs a count.+ if (option.kind === 'project' && !value) {+ const move = async () => {+ await moveTaskTreeToProject(taskIdentifier, option.project.id);+ };+ if (subtaskCount === 0) {+ void move();+ return;+ }+ confirmModal({+ content: t('taskProject.moveTree.content', {+ count: subtaskCount,+ project: option.project.name,+ }),+ okText: t('taskProject.moveTree.ok'),+ onOk: move,+ title: t('taskProject.moveTree.title'),+ });+ return;+ }// A failed save is rolled back and toasted by the store.- if (taskIdentifier) void updateTask(taskIdentifier, { projectId }).catch(() => {});+ void updateTask(taskIdentifier, { projectId }).catch(() => {});};const handleSearchKeyDown = (event: KeyboardEvent<HTMLInputElement>) => {diff --git a/src/services/task.ts b/src/services/task.tsindex be4de90244b..16e9dbe642f 100644--- a/src/services/task.ts+++ b/src/services/task.ts@@ -156,6 +156,10 @@ class TaskService {options?: { takeOwnership?: boolean },) => lambdaClient.task.updateVisibility.mutate({ id, visibility, ...options });+ /** File a task without a project, with all its subtasks, under `projectId`. */+ moveTreeToProject = async (id: string, projectId: string) =>+ lambdaClient.task.moveTreeToProject.mutate({ id, projectId });+update = async (id: string,data: {diff --git a/src/store/task/selectors/detailSelectors.test.ts b/src/store/task/selectors/detailSelectors.test.tsindex b7aeb8d4914..e4226ac10a1 100644--- a/src/store/task/selectors/detailSelectors.test.ts+++ b/src/store/task/selectors/detailSelectors.test.ts@@ -127,6 +127,33 @@ describe('taskDetailSelectors', () => {expect(taskDetailSelectors.activeTaskSubtasks(state)).toHaveLength(1);});+ it('counts subtasks at every depth', () => {+ const nested = createState({+ activeTaskId: 'T-1',+ taskDetailMap: {+ 'T-1': {+ ...mockDetail,+ subtasks: [+ {+ children: [+ {+ children: [{ identifier: 'T-4', status: 'backlog' }],+ identifier: 'T-3',+ status: 'backlog',+ },+ ],+ identifier: 'T-2',+ status: 'backlog',+ },+ { identifier: 'T-5', status: 'backlog' },+ ],+ },+ },+ });+ expect(taskDetailSelectors.activeTaskSubtaskCount(nested)).toBe(4);+ expect(taskDetailSelectors.activeTaskSubtaskCount(createState())).toBe(0);+ });+it('should return empty array when no subtasks', () => {expect(taskDetailSelectors.activeTaskSubtasks(createState())).toEqual([]);});diff --git a/src/store/task/selectors/detailSelectors.ts b/src/store/task/selectors/detailSelectors.tsindex 10262b3bb58..53e7c6844b0 100644--- a/src/store/task/selectors/detailSelectors.ts+++ b/src/store/task/selectors/detailSelectors.ts@@ -102,6 +102,13 @@ const activeTaskRuntimeConfig =const activeTaskSubtasks = (s: TaskStoreState) => activeTaskDetail(s)?.subtasks ?? [];+type SubtaskNode = NonNullable<TaskDetailData['subtasks']>[number];+const countSubtasks = (nodes: SubtaskNode[] = []): number =>+ nodes.reduce((total, node) => total + 1 + countSubtasks(node.children), 0);++/** Subtasks of the active task at every depth that the caller can see. */+const activeTaskSubtaskCount = (s: TaskStoreState) => countSubtasks(activeTaskDetail(s)?.subtasks);+const activeTaskDependencies = (s: TaskStoreState) => activeTaskDetail(s)?.dependencies ?? [];const activeTaskParent = (s: TaskStoreState) => activeTaskDetail(s)?.parent;@@ -210,6 +217,7 @@ export const taskDetailSelectors = {activeTaskSchedulePattern,activeTaskScheduleTimezone,activeTaskStatus,+ activeTaskSubtaskCount,activeTaskSubtasks,activeTaskTopicCount,activeTaskVerifyConfig,diff --git a/src/store/task/slices/detail/action.project.test.ts b/src/store/task/slices/detail/action.project.test.tsindex e14da566856..3cb105bca8d 100644--- a/src/store/task/slices/detail/action.project.test.ts+++ b/src/store/task/slices/detail/action.project.test.ts@@ -16,6 +16,7 @@ vi.mock('@/services/task', () => ({getDetail: vi.fn(),groupList: vi.fn(),list: vi.fn(),+ moveTreeToProject: vi.fn(),update: vi.fn(),},}));@@ -161,6 +162,24 @@ describe('updateTask projectId', () => {});});+ it('names the reason the server gave, and clears the failed save state', async () => {+ seed();+ const refused = Object.assign(new Error('Task has subtasks in its current project'), {+ data: { code: 'BAD_REQUEST', errorData: { projectMoveRefusal: 'split_subtasks' } },+ });+ vi.mocked(taskService.update).mockRejectedValue(refused);++ await state()+ .updateTask('T-1', { projectId: 'p2' })+ .catch(() => {});++ expect(saveToast).toHaveBeenCalledWith(refused, {+ hideCause: true,+ title: expect.stringContaining("subtasks can't be left behind"),+ });+ expect(state().taskSaveStatusMap['T-1']).toBe('idle');+ });+it('keeps the server cause and retry for any other failed save', async () => {seed();const failed = Object.assign(new Error('boom'), { data: { code: 'INTERNAL_SERVER_ERROR' } });@@ -230,3 +249,43 @@ describe('a project-scoped collection remembers its project', () => {await waitFor(() => expect(state().taskGroupListMap[queryKey]?.projectId).toBe('p1'));});});++describe('moveTaskTreeToProject', () => {+ it('moves the tree on the server and refreshes the lists and the detail', async () => {+ seed();+ vi.mocked(taskService.moveTreeToProject).mockResolvedValue({ success: true } as any);++ expect(await state().moveTaskTreeToProject('T-1', 'p2')).toBe(true);++ expect(taskService.moveTreeToProject).toHaveBeenCalledWith('T-1', 'p2');+ expect(taskDetailRefreshes('T-1').length).toBeGreaterThan(0);+ expect(saveToast).not.toHaveBeenCalled();+ });++ it('explains a refused move without a retry and leaves no failed state', async () => {+ seed();+ const refused = Object.assign(new Error('Task tree cannot move'), {+ data: { code: 'BAD_REQUEST', errorData: { projectMoveRefusal: 'external_dependency' } },+ });+ vi.mocked(taskService.moveTreeToProject).mockRejectedValue(refused);++ expect(await state().moveTaskTreeToProject('T-1', 'p2')).toBe(false);++ expect(saveToast).toHaveBeenCalledWith(refused, {+ hideCause: true,+ title: expect.stringContaining('Remove those dependencies first'),+ });+ expect(state().taskSaveStatusMap['T-1']).toBe('idle');+ });++ it('offers a retry for any other failure', async () => {+ seed();+ const failed = Object.assign(new Error('boom'), { data: { code: 'INTERNAL_SERVER_ERROR' } });+ vi.mocked(taskService.moveTreeToProject).mockRejectedValue(failed);++ expect(await state().moveTaskTreeToProject('T-1', 'p2')).toBe(false);++ expect(saveToast).toHaveBeenCalledWith(failed, { retry: expect.any(Function) });+ expect(state().taskSaveStatusMap['T-1']).toBe('failed');+ });+});diff --git a/src/store/task/slices/detail/action.ts b/src/store/task/slices/detail/action.tsindex 42abb616cea..9cef7f9997e 100644--- a/src/store/task/slices/detail/action.ts+++ b/src/store/task/slices/detail/action.ts@@ -11,7 +11,6 @@ import { t } from 'i18next';import { cacheScope, createReplicaSlice, recordLens, revalidateReplica } from '@/libs/replica';import { subscribeCacheScope } from '@/libs/replica/cacheScopeEvents';import { useClientDataSWR } from '@/libs/swr';-import { normalizeAsyncError } from '@/libs/swr/normalizeError';import { taskService } from '@/services/task';import { workService } from '@/services/work';import { goalGraphResource } from '@/store/goal/projection';@@ -33,6 +32,7 @@ import {buildOptimisticPropertyActivity,} from './optimisticActivity';import { taskDetailResource } from './projection';+import { projectMoveRefusalTitle } from './projectMoveRefusal';import type { TaskDetailDispatch } from './reducer';import { findSubtaskParentId, taskDetailReducer } from './reducer';@@ -698,13 +698,13 @@ export class TaskDetailSliceActionImpl {...options,source: 'external',}));- // A refused project move repeats on retry until its links are moved, and the- // server's reason is English-only, so the toast says what to do instead.- if (data.projectId !== undefined && normalizeAsyncError(error).code === 'BAD_REQUEST') {- saveToast(error, {- hideCause: true,- title: t('taskProject.moveRefused', { ns: 'chat' }),- });+ // A refused project move has nothing unsaved: the rollback refetch above+ // already shows the server's value, so the header must not stay on+ // "failed". The toast names what blocks the move, with no retry.+ const refusal = data.projectId !== undefined ? projectMoveRefusalTitle(error) : undefined;+ if (refusal) {+ saveToast(error, { hideCause: true, title: refusal });+ this.#get().internal_setTaskSaveStatus(id, 'idle');return;}saveToast(error, { retry });@@ -740,6 +740,43 @@ export class TaskDetailSliceActionImpl {}};+ /**+ * File a task without a project, together with all its subtasks, under+ * `projectId`. `updateTask` moves one row, which the server refuses for a task+ * with subtasks; this moves the whole tree in one write. No optimistic patch:+ * the subtasks are spread over lists and cached details, so a refetch shows+ * the result instead.+ */+ moveTaskTreeToProject = async (id: string, projectId: string): Promise<boolean> => {+ id = this.#get().taskRefIndex[id] ?? id;+ const moved = await runMutation(this.#set, this.#get, {+ mutate: async () => {+ await taskService.moveTreeToProject(id, projectId);+ return true;+ },+ name: 'moveTaskTreeToProject',+ onError: (error) => {+ const refusal = projectMoveRefusalTitle(error);+ if (refusal) {+ saveToast(error, { hideCause: true, title: refusal });+ this.#get().internal_setTaskSaveStatus(id, 'idle');+ return;+ }+ saveToast(error, {+ retry: () => void this.#get().moveTaskTreeToProject(id, projectId),+ });+ },+ rethrow: false,+ setStatus: (status) => this.#get().internal_setTaskSaveStatus(id, status),+ });+ if (!moved) return false;++ await Promise.all([this.#get().refreshTaskList(), this.internal_refreshTaskDetail(id)]).catch(+ () => {},+ );+ return true;+ };+useFetchTaskDetail = (taskRef?: string) => {const scope = cacheScope.use();const knownId = useTaskStore((state) => cachedTaskId(taskRef, state.taskRefIndex));diff --git a/src/store/task/slices/detail/projectMoveRefusal.ts b/src/store/task/slices/detail/projectMoveRefusal.tsnew file mode 100644index 00000000000..3880d34d914--- /dev/null+++ b/src/store/task/slices/detail/projectMoveRefusal.ts@@ -0,0 +1,31 @@+import type { TaskProjectMoveRefusal } from '@lobechat/types';+import { t } from 'i18next';++import { normalizeAsyncError } from '@/libs/swr/normalizeError';++const REFUSAL_KEYS = {+ external_dependency: 'taskProject.moveRefusedDependency',+ filed_subtask: 'taskProject.moveRefusedFiledSubtask',+ filed_task: 'taskProject.moveRefusedSplitSubtasks',+ has_parent: 'taskProject.moveRefusedHasParent',+ split_subtasks: 'taskProject.moveRefusedSplitSubtasks',+} as const satisfies Record<TaskProjectMoveRefusal, string>;++/**+ * The toast title for a project move the server refused, or `undefined` for any+ * other failure. A refusal repeats on retry until its links change, and the+ * server's message is English-only, so the title names what blocks the move.+ * The reason arrives as `errorData.projectMoveRefusal` (see `projectMoveRefused`+ * on the server); a refusal without one falls back to a generic title.+ */+export const projectMoveRefusalTitle = (error: unknown): string | undefined => {+ if (normalizeAsyncError(error).code !== 'BAD_REQUEST') return undefined;+ const reason = (error as { data?: { errorData?: { projectMoveRefusal?: string } } })?.data+ ?.errorData?.projectMoveRefusal;+ // An unknown reason (a newer server) still gets the generic title.+ const key =+ reason && Object.hasOwn(REFUSAL_KEYS, reason)+ ? REFUSAL_KEYS[reason as TaskProjectMoveRefusal]+ : 'taskProject.moveFailed';+ return t(key, { ns: 'chat' });+};