🤯 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): multi-select the task list with batch actions for hundreds of tasks (#22055)
Rdmclin2207331f152a0
diff --git a/apps/server/src/routers/lambda/task/batch.ts b/apps/server/src/routers/lambda/task/batch.tsnew file mode 100644index 00000000000..9952315d75e--- /dev/null+++ b/apps/server/src/routers/lambda/task/batch.ts@@ -0,0 +1,75 @@+import { TRPCError } from '@trpc/server';+import { z } from 'zod';++import type { LobeChatDatabase } from '@/database/type';+import { router } from '@/libs/trpc/lambda';+import { TaskBatchService } from '@/server/services/task/batch';+import { TASK_BATCH_MAX_IDS, TASK_BATCH_STATUSES } from '@/server/services/task/batchLimits';++import { taskProcedureWrite } from './procedures';++const idsInput = z.object({+ ids: z.array(z.string().trim().min(1)).min(1).max(TASK_BATCH_MAX_IDS),+});++const batchService = (ctx: {+ serverDB: LobeChatDatabase;+ userId: string;+ workspaceId?: string | null;+}) => new TaskBatchService(ctx.serverDB, ctx.userId, ctx.workspaceId ?? undefined);++const rethrow = (scope: string, message: string) => (error: unknown) => {+ if (error instanceof TRPCError) throw error;+ console.error(`[task:${scope}]`, error);+ throw new TRPCError({ cause: error, code: 'INTERNAL_SERVER_ERROR', message });+};++/**+ * Multi-select actions of the task list. One request carries the whole+ * selection (up to {@link TASK_BATCH_MAX_IDS} raw task ids) and answers with a+ * per-task outcome: `updated`, `skipped` with a reason, or `failed`.+ */+export const batchRouter = router({+ batchArchive: taskProcedureWrite+ .input(idsInput.extend({ archived: z.boolean() }))+ .mutation(({ ctx, input }) =>+ batchService(ctx)+ .archive(input.ids, input.archived)+ .catch(rethrow('batchArchive', 'Failed to archive tasks')),+ ),++ batchDelete: taskProcedureWrite+ .input(idsInput)+ .mutation(({ ctx, input }) =>+ batchService(ctx).delete(input.ids).catch(rethrow('batchDelete', 'Failed to delete tasks')),+ ),++ batchUpdate: taskProcedureWrite+ .input(+ idsInput.extend({+ assigneeAgentId: z.string().nullish(),+ assigneeUserId: z.string().nullish(),+ priority: z.number().int().min(0).max(4).optional(),+ }),+ )+ .mutation(async ({ ctx, input }) => {+ const { ids, ...patch } = input;+ const { result } = await batchService(ctx)+ // A person made the change; batch actions are user-only (no agent tool).+ .updateFields(ids, patch, { agentId: ctx.actingAgentId ?? null, userId: ctx.userId })+ .catch(rethrow('batchUpdate', 'Failed to update tasks'));+ return result;+ }),++ batchUpdateStatus: taskProcedureWrite+ .input(idsInput.extend({ status: z.enum(TASK_BATCH_STATUSES) }))+ .mutation(async ({ ctx, input }) => {+ const { result } = await batchService(ctx)+ .updateStatus(input.ids, input.status, {+ agentId: ctx.actingAgentId ?? null,+ userId: ctx.userId,+ })+ .catch(rethrow('batchUpdateStatus', 'Failed to update task status'));+ return result;+ }),+});diff --git a/apps/server/src/routers/lambda/task/index.procedures.test.ts b/apps/server/src/routers/lambda/task/index.procedures.test.tsindex 4ad22ac4bcd..7f8ec22b1af 100644--- a/apps/server/src/routers/lambda/task/index.procedures.test.ts+++ b/apps/server/src/routers/lambda/task/index.procedures.test.ts@@ -30,6 +30,10 @@ function expected(): Array<['addDependency', 'mutation', 13],['analyzeIntent', 'mutation', 13],['archive', 'mutation', 13],+ ['batchArchive', 'mutation', 13],+ ['batchDelete', 'mutation', 13],+ ['batchUpdate', 'mutation', 13],+ ['batchUpdateStatus', 'mutation', 13],['cancelTopic', 'mutation', 13],['clearAll', 'mutation', 12],['copyTaskToWorkspace', 'mutation', 13],diff --git a/apps/server/src/routers/lambda/task/index.ts b/apps/server/src/routers/lambda/task/index.tsindex 2c26ae80e09..9d5f4e806d5 100644--- a/apps/server/src/routers/lambda/task/index.ts+++ b/apps/server/src/routers/lambda/task/index.ts@@ -1,5 +1,6 @@import { mergeRouters } from '@/libs/trpc/lambda';+import { batchRouter } from './batch';import { commentsRouter } from './comments';import { executionRouter } from './execution';import { lifecycleRouter } from './lifecycle';@@ -9,6 +10,7 @@ import { reviewRouter } from './review';import { updateRouter } from './update';export const taskRouter = mergeRouters(+ batchRouter,lifecycleRouter,relationsRouter,commentsRouter,diff --git a/apps/server/src/services/task/archiveGuard.integration.test.ts b/apps/server/src/services/task/archiveGuard.integration.test.tsindex 93aaca08d5f..bb82b54773f 100644--- a/apps/server/src/services/task/archiveGuard.integration.test.ts+++ b/apps/server/src/services/task/archiveGuard.integration.test.ts@@ -9,7 +9,11 @@ import { TaskModel } from '@/database/models/task';import { TaskArchiveModel } from '@/database/models/taskArchive';import { goals, tasks, users } from '@/database/schemas';-import { assertNotInOpenGoal, writeKeepingArchivedIdle } from './archiveGuard';+import {+ assertNotInOpenGoal,+ findTasksInOpenGoals,+ writeKeepingArchivedIdle,+} from './archiveGuard';const userId = 'archive-guard-integration-user';@@ -112,4 +116,49 @@ describe('writeKeepingArchivedIdle (real PostgreSQL)', () => {await expect(assertNotInOpenGoal(db, { userId }, loose)).resolves.toBeUndefined();});});++ describe('findTasksInOpenGoals', () => {+ it('agrees with assertNotInOpenGoal for carriers, descendants, finished and closed-goal tasks', async () => {+ const model = new TaskModel(db, userId);+ const carrier = await model.create({ instruction: 'Open goal carrier' });+ await new GoalModel(db, userId).create({+ subjectId: carrier.id,+ subjectType: 'task',+ title: 'Open goal',+ });+ const child = await model.create({ instruction: 'Child', parentTaskId: carrier.id });+ const grandchild = await model.create({ instruction: 'Grandchild', parentTaskId: child.id });+ const closedCarrier = await model.create({ instruction: 'Closed goal carrier' });+ const closed = await new GoalModel(db, userId).create({+ subjectId: closedCarrier.id,+ subjectType: 'task',+ title: 'Closed goal',+ });+ await db.update(goals).set({ status: 'achieved' }).where(eq(goals.id, closed.id));+ const loose = await model.create({ instruction: 'Loose task' });+ const finished = {+ ...(await model.create({ instruction: 'Finished' })),+ status: 'completed',+ };+ await new GoalModel(db, userId).create({+ subjectId: finished.id,+ subjectType: 'task',+ title: 'Open goal on finished task',+ });++ const all = [carrier, child, grandchild, closedCarrier, loose, finished];+ const blocked = await findTasksInOpenGoals(db, { userId }, all);++ expect([...blocked].sort()).toEqual([carrier.id, child.id, grandchild.id].sort());+ // Same answer as the single-task guard, task by task.+ for (const task of all) {+ const single = await assertNotInOpenGoal(db, { userId }, task).then(+ () => false,+ () => true,+ );+ expect(single).toBe(blocked.has(task.id));+ }+ expect(await findTasksInOpenGoals(db, { userId }, [])).toEqual(new Set());+ });+ });});diff --git a/apps/server/src/services/task/archiveGuard.ts b/apps/server/src/services/task/archiveGuard.tsindex f29b297d6b3..1724a3af70d 100644--- a/apps/server/src/services/task/archiveGuard.ts+++ b/apps/server/src/services/task/archiveGuard.ts@@ -88,3 +88,24 @@ export const assertNotInOpenGoal = async (});}};++/**+ * Bulk form of {@link assertNotInOpenGoal}: the ids among `tasks` that an open+ * Goal still owns, resolved in a fixed number of queries however many tasks+ * are passed. Finished tasks are never blocked, exactly as for one task.+ */+export const findTasksInOpenGoals = async (+ db: LobeChatDatabase,+ scope: { userId: string; workspaceId?: string },+ tasks: { id: string; status: string }[],+): Promise<Set<string>> => {+ const unfinished = tasks.filter((task) => !FINISHED_TASK_STATUSES.has(task.status));+ if (unfinished.length === 0) return new Set();++ const owners = await new GoalGraphModel(db, scope.userId, scope.workspaceId).findGoalsByTaskIds(+ unfinished.map((task) => task.id),+ );+ return new Set(+ [...owners].filter(([, goal]) => !TERMINAL_GOAL_STATUSES.has(goal.status)).map(([id]) => id),+ );+};diff --git a/apps/server/src/services/task/batch.integration.test.ts b/apps/server/src/services/task/batch.integration.test.tsnew file mode 100644index 00000000000..35ec9429d60--- /dev/null+++ b/apps/server/src/services/task/batch.integration.test.ts@@ -0,0 +1,359 @@+// @vitest-environment node+import { type LobeChatDatabase } from '@lobechat/database';+import { getTestDB } from '@lobechat/database/test-utils';+import {+ applyTaskReposSelection,+ readTaskExecutionConfig,+ toTaskExecutionConfigPatch,+} from '@lobechat/types';+import { and, eq, inArray } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { GoalModel } from '@/database/models/goal';+import { TaskModel } from '@/database/models/task';+import { TaskTopicModel } from '@/database/models/taskTopic';+import { agents, taskActivities, tasks, users } from '@/database/schemas';+import { TaskRunnerService } from '@/server/services/taskRunner';++import { TaskBatchService } from './batch';++vi.mock('@/server/utils/scheduleAfterResponse', () => ({ after: vi.fn() }));++const userId = 'task-batch-integration-user';+const otherUserId = 'task-batch-integration-other';++// Module-level, like the database model tests: the first call migrates a+// fresh database, which can outlast a hook timeout on a loaded CI shard.+const db: LobeChatDatabase = await getTestDB();++const activitiesOf = (ids: string[], type: string) =>+ db+ .select()+ .from(taskActivities)+ .where(and(inArray(taskActivities.taskId, ids), eq(taskActivities.type, type)));++describe('TaskBatchService (real PostgreSQL)', () => {+ let model: TaskModel;+ let service: TaskBatchService;++ beforeEach(async () => {+ await db.delete(users).where(inArray(users.id, [userId, otherUserId]));+ await db.insert(users).values([{ id: userId }, { id: otherUserId }]);+ model = new TaskModel(db, userId);+ service = new TaskBatchService(db, userId);+ });++ afterEach(async () => {+ await db.delete(users).where(inArray(users.id, [userId, otherUserId]));+ });++ const createTasks = async (count: number, data: Record<string, unknown> = {}) => {+ const created = [];+ for (let i = 0; i < count; i++) {+ created.push(await model.create({ instruction: `Task ${i}`, ...data }));+ }+ return created;+ };++ describe('updateFields', () => {+ it('sets priority on the whole selection and logs one activity per changed task', async () => {+ const [a, b, c] = await createTasks(3);+ await model.update(c.id, { priority: 2 });+ const foreign = await new TaskModel(db, otherUserId).create({ instruction: 'Not mine' });++ const { result } = await service.updateFields(+ [a.id, b.id, c.id, foreign.id, 'task_missing'],+ { priority: 2 },+ { userId },+ );++ expect(result.updated.sort()).toEqual([a.id, b.id].sort());+ expect(result.skipped).toEqual(+ expect.arrayContaining([+ { id: c.id, reason: 'unchanged' },+ { id: foreign.id, reason: 'notFound' },+ { id: 'task_missing', reason: 'notFound' },+ ]),+ );+ expect((await model.findById(a.id))?.priority).toBe(2);+ expect((await new TaskModel(db, otherUserId).findById(foreign.id))?.priority).toBe(0);++ const logged = await activitiesOf([a.id, b.id, c.id], 'priority');+ expect(logged.map((row) => row.taskId).sort()).toEqual([a.id, b.id].sort());+ expect(logged[0].payload).toMatchObject({ from: 0, to: 2 });+ });++ it('reassigns tasks in one statement and drops only the previous agent repo selection', async () => {+ await db.insert(agents).values([+ { id: 'agt_batch_a', slug: 'agt_batch_a', userId },+ { id: 'agt_batch_b', slug: 'agt_batch_b', userId },+ ]);+ const withRepos = await createTasks(2, { assigneeAgentId: 'agt_batch_a' });+ for (const task of withRepos) {+ await model.updateTaskConfig(task.id, {+ checkpoint: { onAgentRequest: true },+ execution: toTaskExecutionConfigPatch(+ applyTaskReposSelection(undefined, ['lobehub/lobehub']),+ ),+ });+ }+ const [unassigned] = await createTasks(1, {+ config: { checkpoint: { onAgentRequest: false } },+ });+ const ids = [...withRepos.map((task) => task.id), unassigned.id];++ const { result } = await service.updateFields(+ ids,+ { assigneeAgentId: 'agt_batch_b' },+ { userId },+ );++ expect(result.updated.sort()).toEqual([...ids].sort());+ for (const task of withRepos) {+ const stored = await model.findById(task.id);+ expect(stored?.assigneeAgentId).toBe('agt_batch_b');+ expect(readTaskExecutionConfig(stored?.config as Record<string, unknown>)).toBeUndefined();+ // Only the repo selection goes; the rest of the config stays.+ expect((stored?.config as any).checkpoint).toEqual({ onAgentRequest: true });+ }+ const other = await model.findById(unassigned.id);+ expect(other?.assigneeAgentId).toBe('agt_batch_b');+ expect(other?.config).toEqual({ checkpoint: { onAgentRequest: false } });+ expect(await activitiesOf(ids, 'assignee_agent')).toHaveLength(3);+ });++ it('assigns a member and leaves running tasks alone', async () => {+ const [idle, running] = await createTasks(2);+ await model.update(running.id, { status: 'running' });++ const { result } = await service.updateFields(+ [idle.id, running.id],+ { assigneeUserId: userId },+ { userId },+ );++ expect(result.updated).toEqual([idle.id]);+ expect(result.skipped).toEqual([{ id: running.id, reason: 'running' }]);+ expect((await model.findById(idle.id))?.assigneeUserId).toBe(userId);+ expect((await model.findById(running.id))?.assigneeUserId).toBeNull();+ expect(await activitiesOf([idle.id], 'assignee_user')).toHaveLength(1);+ });++ it('rejects an empty patch', async () => {+ const [task] = await createTasks(1);+ await expect(service.updateFields([task.id], {}, { userId })).rejects.toMatchObject({+ code: 'BAD_REQUEST',+ });+ });++ it('updates hundreds of tasks in one call', async () => {+ const many = await createTasks(300);+ const ids = many.map((task) => task.id);++ const { result } = await service.updateFields(ids, { priority: 1 }, { userId });++ expect(result.updated).toHaveLength(300);+ const stored = await db.select().from(tasks).where(inArray(tasks.id, ids));+ expect(stored.every((task) => task.priority === 1)).toBe(true);+ expect(await activitiesOf(ids, 'priority')).toHaveLength(300);+ });+ });++ describe('updateStatus', () => {+ it('moves the selection to one status, stamps completion and logs transitions', async () => {+ const [a, b, done] = await createTasks(3);+ await model.update(done.id, { status: 'completed' });++ const { result } = await service.updateStatus([a.id, b.id, done.id], 'completed', {+ userId,+ });++ expect(result.updated.sort()).toEqual([a.id, b.id].sort());+ expect(result.skipped).toEqual([{ id: done.id, reason: 'unchanged' }]);+ const stored = await model.findById(a.id);+ expect(stored?.status).toBe('completed');+ expect(stored?.completedAt).toBeInstanceOf(Date);++ const logged = await activitiesOf([a.id, b.id, done.id], 'status');+ expect(logged).toHaveLength(2);+ expect(logged[0].payload).toMatchObject({ from: 'backlog', to: 'completed' });+ });++ it('pauses a parent whose checkpoint asks to review completed subtasks', async () => {+ const parent = await model.create({ instruction: 'Parent' });+ const [child] = await createTasks(1, { parentTaskId: parent.id });+ await model.updateCheckpointConfig(parent.id, { tasks: { afterIds: [child.identifier] } });+ await model.update(parent.id, { status: 'running' });++ await service.updateStatus([child.id], 'completed', { userId });++ expect((await model.findById(parent.id))?.status).toBe('paused');+ });++ it('keeps a committed completion when its follow-ups fail, and reports it', async () => {+ const [task] = await createTasks(1);+ const spy = vi+ .spyOn(TaskRunnerService.prototype, 'cascadeOnCompletionMany')+ .mockRejectedValueOnce(new Error('dependency discovery failed'));+ vi.spyOn(console, 'error').mockImplementation(() => {});++ const { result } = await service.updateStatus([task.id], 'completed', { userId });++ expect(spy).toHaveBeenCalled();+ expect(result.updated).toEqual([task.id]);+ expect(result.failed).toEqual([]);+ expect(result.followUpFailed).toBe(true);+ expect((await model.findById(task.id))?.status).toBe('completed');+ spy.mockRestore();+ });++ it('does not pause a parent that was finished after the snapshot', async () => {+ const parent = await model.create({ instruction: 'Parent' });+ const [child] = await createTasks(1, { parentTaskId: parent.id });+ await model.updateCheckpointConfig(parent.id, { tasks: { afterIds: [child.identifier] } });+ await model.update(parent.id, { status: 'running' });+ // Another request cancels the parent between the snapshot and the pause.+ const original = TaskModel.prototype.findByIds;+ const spy = vi.spyOn(TaskModel.prototype, 'findByIds').mockImplementation(async function (+ this: TaskModel,+ ids: string[],+ ) {+ const rows = await original.call(this, ids);+ if (ids.includes(parent.id)) {+ await new TaskModel(db, userId).update(parent.id, { status: 'canceled' });+ }+ return rows;+ });++ await service.updateStatus([child.id], 'completed', { userId });+ spy.mockRestore();++ expect((await model.findById(parent.id))?.status).toBe('canceled');+ });++ it('leaves a task whose run is still starting alone instead of stopping it blind', async () => {+ const [starting, stale, idle] = await createTasks(3);+ // Just dispatched: running, no recorded topic / operation yet.+ await model.update(starting.id, { startedAt: new Date(), status: 'running' });+ // A start that died long ago: past the grace window, safe to stop.+ await model.update(stale.id, {+ startedAt: new Date(Date.now() - 10 * 60 * 1000),+ status: 'running',+ });++ const { result } = await service.updateStatus([starting.id, stale.id, idle.id], 'paused', {+ userId,+ });++ expect(result.updated.sort()).toEqual([stale.id, idle.id].sort());+ expect(result.skipped).toEqual([{ id: starting.id, reason: 'running' }]);+ expect((await model.findById(starting.id))?.status).toBe('running');+ });++ it('skips a task that started running after the interrupt pass', async () => {+ const [task] = await createTasks(1);+ const original = TaskTopicModel.prototype.findRunningByTaskIds;+ const spy = vi+ .spyOn(TaskTopicModel.prototype, 'findRunningByTaskIds')+ .mockImplementationOnce(async function (this: TaskTopicModel, ids: string[]) {+ const topics = await original.call(this, ids);+ // A run starts right after the snapshot was checked.+ await new TaskModel(db, userId).update(task.id, {+ startedAt: new Date(),+ status: 'running',+ });+ return topics;+ });++ const { result } = await service.updateStatus([task.id], 'completed', { userId });+ spy.mockRestore();++ expect(result.updated).toEqual([]);+ expect(result.skipped).toEqual([{ id: task.id, reason: 'running' }]);+ expect((await model.findById(task.id))?.status).toBe('running');+ });++ it('does not re-open a parent completed in the same batch', async () => {+ const parent = await model.create({ instruction: 'Parent' });+ const [child] = await createTasks(1, { parentTaskId: parent.id });+ await model.updateCheckpointConfig(parent.id, { tasks: { afterIds: [child.identifier] } });++ await service.updateStatus([parent.id, child.id], 'completed', { userId });++ expect((await model.findById(parent.id))?.status).toBe('completed');+ });++ it('skips an archived task the status would make live instead of failing the batch', async () => {+ const [plain, archived] = await createTasks(2);+ await model.update(archived.id, {+ automationMode: 'schedule',+ schedulePattern: '0 9 * * *',+ status: 'paused',+ });+ await db.update(tasks).set({ archivedAt: new Date() }).where(eq(tasks.id, archived.id));++ const { result } = await service.updateStatus([plain.id, archived.id], 'backlog', {+ userId,+ });++ expect(result.updated).toEqual([]);+ expect(result.skipped).toEqual(+ expect.arrayContaining([+ { id: plain.id, reason: 'unchanged' },+ { id: archived.id, reason: 'invalid' },+ ]),+ );+ expect((await model.findById(archived.id))?.status).toBe('paused');+ });+ });++ describe('archive', () => {+ it('archives idle tasks, skips running ones, and restores them again', async () => {+ const [idle, running] = await createTasks(2);+ await model.update(running.id, { status: 'running' });++ const archived = await service.archive([idle.id, running.id], true);+ expect(archived.updated).toEqual([idle.id]);+ expect(archived.skipped).toEqual([{ id: running.id, reason: 'running' }]);+ expect((await model.findById(idle.id))?.archivedAt).toBeInstanceOf(Date);++ const again = await service.archive([idle.id], true);+ expect(again.skipped).toEqual([{ id: idle.id, reason: 'unchanged' }]);++ const restored = await service.archive([idle.id, running.id], false);+ expect(restored.updated).toEqual([idle.id]);+ expect((await model.findById(idle.id))?.archivedAt).toBeNull();+ });+ });++ describe('archive (goals)', () => {+ it('skips tasks an open goal still owns and archives the rest', async () => {+ const [carrier, loose] = await createTasks(2);+ await new GoalModel(db, userId).create({+ subjectId: carrier.id,+ subjectType: 'task',+ title: 'Open goal',+ });++ const result = await service.archive([carrier.id, loose.id], true);++ expect(result.updated).toEqual([loose.id]);+ expect(result.skipped).toEqual([{ id: carrier.id, reason: 'inGoal' }]);+ expect((await model.findById(carrier.id))?.archivedAt).toBeNull();+ });+ });++ describe('delete', () => {+ it('deletes idle tasks in one pass and reports missing ones', async () => {+ const [a, b] = await createTasks(2);+ const keep = (await createTasks(1))[0];++ const result = await service.delete([a.id, b.id, 'task_missing']);++ expect(result.updated.sort()).toEqual([a.id, b.id].sort());+ expect(result.skipped).toEqual([{ id: 'task_missing', reason: 'notFound' }]);+ expect(await model.findById(a.id)).toBeNull();+ expect(await model.findById(keep.id)).not.toBeNull();+ });+ });+});diff --git a/apps/server/src/services/task/batch.ts b/apps/server/src/services/task/batch.tsnew file mode 100644index 00000000000..e0da99df92a--- /dev/null+++ b/apps/server/src/services/task/batch.ts@@ -0,0 +1,613 @@+import type { TaskItem } from '@lobechat/types';+import { TRPCError } from '@trpc/server';+import pMap from 'p-map';++import { AgentModel } from '@/database/models/agent';+import { taskActivityActor, TaskModel } from '@/database/models/task';+import { withStaleReposCleared } from '@/database/models/task/utils';+import { TaskArchiveModel } from '@/database/models/taskArchive';+import { TaskTopicModel } from '@/database/models/taskTopic';+import { TopicModel } from '@/database/models/topic';+import type { LobeChatDatabase } from '@/database/type';+import { EditLockService } from '@/server/services/editLock';++import { AiAgentService } from '../aiAgent';+import { TaskRunnerService } from '../taskRunner';+import { assertArchivedTaskStaysIdle, findTasksInOpenGoals } from './archiveGuard';+import { notifyAssignedBestEffort } from './assignmentNotification';+import type { TaskBatchStatus } from './batchLimits';+import { isTaskRunStarting, TaskService } from './index';+import { assertAssigneeAgentBelongsToUser } from './patchValidation';+import { interruptTaskOperation } from './utils';++const FINISHED_STATUSES = new Set(['canceled', 'completed']);++/** Remote operation interrupts / per-task fallbacks issued by one batch. */+const BATCH_SIDE_EFFECT_CONCURRENCY = 5;+/** Cheap per-task checks (Redis edit lock, goal ownership). */+const BATCH_CHECK_CONCURRENCY = 20;++export type TaskBatchSkipReason =+ /** A workspace bulk delete only removes tasks the caller created. */+ | 'forbidden'+ /** The task is part of an open goal and cannot be archived. */+ | 'inGoal'+ /** Another member is editing the task. */+ | 'locked'+ /** Not found, or not visible to the caller. */+ | 'notFound'+ /** Running, or its schedule / heartbeat can still fire. */+ | 'running'+ /** Already in the requested state. */+ | 'unchanged'+ /** The change would break a visibility or archive invariant. */+ | 'invalid';++export interface TaskBatchResult {+ failed: { error: string; id: string }[];+ /**+ * The status change committed, but its completion follow-ups (parent+ * checkpoint pause, starting unlocked dependents) failed afterwards. The+ * tasks are completed; the caller should say the follow-ups did not run.+ */+ followUpFailed?: boolean;+ skipped: { id: string; reason: TaskBatchSkipReason }[];+ /** Ids (as stored, not the caller's refs) that the batch changed. */+ updated: string[];+}++export interface TaskBatchFieldsPatch {+ assigneeAgentId?: string | null;+ assigneeUserId?: string | null;+ priority?: number;+}++type Actor = { agentId?: string | null; userId?: string | null };++const errorMessage = (error: unknown) => (error instanceof Error ? error.message : 'Unknown error');++/**+ * Bulk task edits for the list's multi-select actions. Each method takes the+ * whole selection in one request and writes it with set-based statements and+ * one activity INSERT, instead of the client fanning out one request (and one+ * transaction, and one list refresh) per task.+ *+ * Every invariant the single-task write paths enforce is still applied — per+ * task, against a snapshot read in one query. A task that fails a check is+ * reported as skipped rather than aborting the whole batch, so a selection of+ * hundreds still lands everything it legitimately can.+ */+export class TaskBatchService {+ private readonly db: LobeChatDatabase;+ private readonly userId: string;+ private readonly workspaceId?: string;+ private readonly taskModel: TaskModel;++ constructor(db: LobeChatDatabase, userId: string, workspaceId?: string) {+ this.db = db;+ this.userId = userId;+ this.workspaceId = workspaceId;+ this.taskModel = new TaskModel(db, userId, workspaceId);+ }++ /**+ * Load the selection in one query. Ids the caller cannot see come back as+ * `notFound`, the same answer the single-task paths give.+ */+ private async loadSelection(ids: string[]) {+ const unique = [...new Set(ids)];+ const tasks = await this.taskModel.findByIds(unique);+ const found = new Set(tasks.map((task) => task.id));+ const result: TaskBatchResult = {+ failed: [],+ skipped: unique.filter((id) => !found.has(id)).map((id) => ({ id, reason: 'notFound' })),+ updated: [],+ };+ return { result, tasks };+ }++ /** Drop tasks another workspace member is editing (inert in personal mode). */+ private async withoutEditLocked(tasks: TaskItem[], result: TaskBatchResult) {+ if (!this.workspaceId || tasks.length === 0) return tasks;+ const editLock = new EditLockService(this.userId);+ const blocked = await pMap(+ tasks,+ async (task) => !!(await editLock.getBlockingHolder('task', task.id)),+ { concurrency: BATCH_CHECK_CONCURRENCY },+ );+ return tasks.filter((task, index) => {+ if (!blocked[index]) return true;+ result.skipped.push({ id: task.id, reason: 'locked' });+ return false;+ });+ }++ /**+ * Set priority and / or assignees on many tasks. The assignees are validated+ * once for the whole batch; per-task visibility rules and "running tasks keep+ * their assignee" are applied to each row.+ */+ async updateFields(+ ids: string[],+ patch: TaskBatchFieldsPatch,+ actor: Actor,+ ): Promise<{ result: TaskBatchResult; tasks: TaskItem[] }> {+ const { assigneeAgentId, assigneeUserId, priority } = patch;+ const changesAssignee = assigneeAgentId !== undefined || assigneeUserId !== undefined;+ if (!changesAssignee && priority === undefined) {+ throw new TRPCError({ code: 'BAD_REQUEST', message: 'Nothing to update' });+ }++ const taskService = new TaskService(this.db, this.userId, this.workspaceId);+ // Selection-independent checks: a bad assignee fails the request outright,+ // exactly like the single-task update.+ await assertAssigneeAgentBelongsToUser(+ this.db,+ { userId: this.userId, workspaceId: this.workspaceId },+ assigneeAgentId,+ );+ await taskService.assertAssigneeUserAssignable(assigneeUserId);+ const agentVisibility = assigneeAgentId+ ? await new AgentModel(this.db, this.userId, this.workspaceId).getAgentVisibility(+ assigneeAgentId,+ )+ : null;++ const { result, tasks } = await this.loadSelection(ids);+ const candidates = (await this.withoutEditLocked(tasks, result)).filter((task) => {+ // A running task's assignee is the agent doing the work; the row picker+ // is disabled for it, and so is the batch.+ if (changesAssignee && task.status === 'running') {+ result.skipped.push({ id: task.id, reason: 'running' });+ return false;+ }+ try {+ if (assigneeAgentId)+ taskService.assertAgentVisibilityCompat(task.visibility, agentVisibility);+ taskService.assertAssigneeUserVisibilityCompat(+ task.visibility,+ assigneeUserId,+ task.createdByUserId,+ );+ } catch {+ result.skipped.push({ id: task.id, reason: 'invalid' });+ return false;+ }+ return true;+ });++ const data: TaskBatchFieldsPatch = {};+ if (assigneeAgentId !== undefined) data.assigneeAgentId = assigneeAgentId;+ if (assigneeUserId !== undefined) data.assigneeUserId = assigneeUserId;+ if (priority !== undefined) data.priority = priority;++ const updatedTasks = await this.db.transaction(async (tx) => {+ const model = new TaskModel(tx, this.userId, this.workspaceId);+ // Serialize with a concurrent member removal, like the single-task+ // assignee write: the member row stays locked until this commit.+ if (assigneeUserId) {+ await new TaskService(tx, this.userId, this.workspaceId).assertAssigneeUserAssignableLocked(+ tx,+ assigneeUserId,+ );+ }+ // Decide and describe each row from its locked state, so the activity+ // log never names a transition a concurrent edit already superseded.+ const lockedRows = await model.lockForBulkEdit(candidates.map((task) => task.id));+ const lockedIds = new Set(lockedRows.map((row) => row.id));+ for (const task of candidates) {+ if (!lockedIds.has(task.id)) result.skipped.push({ id: task.id, reason: 'notFound' });+ }+ // The snapshot checks above are re-applied to the locked rows: a task+ // that started running or turned private since then is left alone.+ const locked = lockedRows.filter((row) => {+ if (changesAssignee && row.status === 'running') {+ result.skipped.push({ id: row.id, reason: 'running' });+ return false;+ }+ try {+ if (assigneeAgentId)+ taskService.assertAgentVisibilityCompat(row.visibility, agentVisibility);+ taskService.assertAssigneeUserVisibilityCompat(+ row.visibility,+ assigneeUserId,+ row.createdByUserId,+ );+ } catch {+ result.skipped.push({ id: row.id, reason: 'invalid' });+ return false;+ }+ return true;+ });++ const changing = locked.filter(+ (row) =>+ (data.assigneeAgentId !== undefined && row.assigneeAgentId !== data.assigneeAgentId) ||+ (data.assigneeUserId !== undefined && row.assigneeUserId !== data.assigneeUserId) ||+ (data.priority !== undefined && (row.priority ?? null) !== data.priority),+ );+ const changingIds = new Set(changing.map((row) => row.id));+ for (const row of locked) {+ if (!changingIds.has(row.id)) result.skipped.push({ id: row.id, reason: 'unchanged' });+ }++ // Moving a task off an agent drops that agent's cloud-repo selection+ // (`withStaleReposCleared`). The cleared config is computed from each+ // locked row and written by the same single UPDATE as the shared patch,+ // so a large reassignment is one statement, not one write per task.+ const configById = new Map<string, unknown>();+ for (const row of changing) {+ const rowData = withStaleReposCleared(row, data);+ if (rowData !== data) configById.set(row.id, rowData.config);+ }+ const written = await model.updateFieldsForIds(+ changing.map((row) => row.id),+ data,+ configById,+ );++ const { actorKind, ...actorColumns } = taskActivityActor(actor);+ const after = new Map(written.map((task) => [task.id, task]));+ await model.addActivities(+ changing.flatMap((before) => {+ const updated = after.get(before.id);+ if (!updated) return [];+ const base = { ...actorColumns, taskId: before.id, visibility: before.visibility };+ const rows = [];+ if (before.assigneeAgentId !== updated.assigneeAgentId) {+ rows.push({+ ...base,+ payload: { actorKind, fromId: before.assigneeAgentId, toId: updated.assigneeAgentId },+ type: 'assignee_agent' as const,+ });+ }+ if (before.assigneeUserId !== updated.assigneeUserId) {+ rows.push({+ ...base,+ payload: { actorKind, fromId: before.assigneeUserId, toId: updated.assigneeUserId },+ type: 'assignee_user' as const,+ });+ }+ if ((before.priority ?? null) !== (updated.priority ?? null)) {+ rows.push({+ ...base,+ payload: { actorKind, from: before.priority ?? null, to: updated.priority ?? null },+ type: 'priority' as const,+ });+ }+ return rows;+ }),+ );++ return changing+ .filter((row) => after.has(row.id))+ .map((row) => ({ before: row, task: after.get(row.id)! }));+ });++ result.updated = updatedTasks.map(({ task }) => task.id);+ const scope = { userId: this.userId, workspaceId: this.workspaceId };+ for (const { before, task } of updatedTasks) {+ // Only an actual assignee change notifies (self-assignment stays silent).+ if (task.assigneeUserId !== before.assigneeUserId) notifyAssignedBestEffort(scope, task);+ }+ return { result, tasks: updatedTasks.map(({ task }) => task) };+ }++ /**+ * Move many tasks to one status in a single transaction. Mirrors+ * `updateStatusCascade`: interrupt live runs first, then cancel their topics,+ * write every status and log every transition together, and run completion+ * side effects (checkpoints, dependency unlocks) once for the whole set.+ */+ async updateStatus(+ ids: string[],+ status: TaskBatchStatus,+ actor: Actor,+ ): Promise<{ result: TaskBatchResult; tasks: TaskItem[] }> {+ const { result, tasks } = await this.loadSelection(ids);+ const candidates = (await this.withoutEditLocked(tasks, result)).filter((task) => {+ if (task.status === status) {+ result.skipped.push({ id: task.id, reason: 'unchanged' });+ return false;+ }+ try {+ assertArchivedTaskStaysIdle(task, { status });+ } catch {+ result.skipped.push({ id: task.id, reason: 'invalid' });+ return false;+ }+ return true;+ });++ const taskTopicModel = new TaskTopicModel(this.db, this.userId, this.workspaceId);+ const aiAgentService = new AiAgentService(this.db, this.userId, {+ workspaceId: this.workspaceId,+ });++ // Leaving `running` stops the run first. A task whose run cannot be+ // interrupted is left as it is (and reported), never shown as stopped+ // while it is still executing.+ const allRunningTopics = await taskTopicModel.findRunningByTaskIds(+ candidates.map((task) => task.id),+ );+ // A run still starting (dispatched, operation not recorded yet) has+ // nothing to interrupt; stopping its task now would leave the agent+ // running under a task shown as stopped. Skip it, as `deleteTask` does.+ const starting = new Set(+ candidates+ .filter((task) =>+ isTaskRunStarting(+ task,+ allRunningTopics.filter((topic) => topic.taskId === task.id),+ ),+ )+ .map((task) => task.id),+ );+ for (const id of starting) result.skipped.push({ id, reason: 'running' });+ const runningTopics = allRunningTopics.filter((topic) => !starting.has(topic.taskId));+ const interruptFailed = new Set<string>();+ const failedOperations = new Set<string>();+ await pMap(+ runningTopics.filter((topic) => topic.operationId),+ async (topic) => {+ try {+ await interruptTaskOperation(aiAgentService, topic.operationId!);+ } catch (error) {+ failedOperations.add(topic.operationId!);+ if (!interruptFailed.has(topic.taskId)) {+ interruptFailed.add(topic.taskId);+ result.failed.push({ error: errorMessage(error), id: topic.taskId });+ }+ }+ },+ { concurrency: BATCH_SIDE_EFFECT_CONCURRENCY },+ );+ // A task with several runs may have had some of them stopped before one+ // failed: record those as canceled so a stopped operation is never left+ // looking live (same as `updateStatusCascade`).+ for (const topic of runningTopics) {+ if (!interruptFailed.has(topic.taskId) || !topic.topicId) continue;+ if (topic.operationId && failedOperations.has(topic.operationId)) continue;+ await taskTopicModel.cancelIfRunning(topic.taskId, topic.topicId).catch(() => undefined);+ }+ const targetIds = candidates+ .filter((task) => !interruptFailed.has(task.id) && !starting.has(task.id))+ .map((task) => task.id);+ const wasRunning = new Set(+ candidates.filter((task) => task.status === 'running').map((task) => task.id),+ );++ const extra =+ status === 'completed' || status === 'canceled' ? { completedAt: new Date() } : undefined;+ let updatedTasks: TaskItem[] = [];+ let canceledTopics: Awaited<ReturnType<TaskTopicModel['cancelRunningByTaskIds']>> = [];+ await this.db.transaction(async (tx) => {+ const model = new TaskModel(tx, this.userId, this.workspaceId);+ const locked = await model.lockForBulkEdit(targetIds);+ // Same rule `writeKeepingArchivedIdle` applies to one row, checked per+ // locked row: a task archived since the snapshot is skipped, not allowed+ // to come out of this write live, and not allowed to fail the batch.+ const changing = locked.filter((row) => {+ if (row.status === status) {+ result.skipped.push({ id: row.id, reason: 'unchanged' });+ return false;+ }+ // Started a run after the interrupt pass above: that run was never+ // stopped, so this task is left to it rather than shown as stopped.+ if (row.status === 'running' && !wasRunning.has(row.id)) {+ result.skipped.push({ id: row.id, reason: 'running' });+ return false;+ }+ try {+ assertArchivedTaskStaysIdle(row, { status });+ } catch {+ result.skipped.push({ id: row.id, reason: 'invalid' });+ return false;+ }+ return true;+ });+ const changingIds = changing.map((row) => row.id);++ canceledTopics = await new TaskTopicModel(+ tx,+ this.userId,+ this.workspaceId,+ ).cancelRunningByTaskIds(changingIds);+ updatedTasks = await model.updateStatusForIds(changingIds, status, extra);++ const { actorKind, ...actorColumns } = taskActivityActor(actor);+ await model.addActivities(+ changing.map((before) => ({+ ...actorColumns,+ payload: { actorKind, from: before.status, to: status },+ taskId: before.id,+ type: 'status' as const,+ visibility: before.visibility,+ })),+ );+ });+ result.updated = updatedTasks.map((task) => task.id);++ // Best-effort: stop operations that only showed up inside the transaction.+ const interrupted = new Set(runningTopics.map((topic) => topic.operationId));+ await pMap(+ canceledTopics.filter((topic) => topic.operationId && !interrupted.has(topic.operationId)),+ (topic) =>+ aiAgentService.interruptTask({ operationId: topic.operationId! }).catch(() => undefined),+ { concurrency: BATCH_SIDE_EFFECT_CONCURRENCY },+ );++ // Post-commit: the tasks are completed whatever happens here, so a failure++ // must not turn the whole request into an error the client would retry —++ // a retry finds every row `unchanged` and changes nothing. Report it++ // instead. (Re-running the follow-ups automatically on a later retry is++ // deliberately avoided: it would start agent runs on dependents a person++ // may have parked in the backlog on purpose.)++ if (status === 'completed' && updatedTasks.length > 0) {+ try {+ await this.afterCompletion(updatedTasks);+ } catch (error) {+ console.error('[TaskBatchService.updateStatus] completion follow-ups failed', error);++ result.followUpFailed = true;+ }+ }++ return { result, tasks: updatedTasks };+ }++ /** Checkpoint pauses and dependency unlocks for a set of just-completed tasks. */+ private async afterCompletion(completed: TaskItem[]) {+ const parentIds = [+ ...new Set(completed.map((task) => task.parentTaskId).filter((id): id is string => !!id)),+ ];+ const parents = new Map(+ (await this.taskModel.findByIds(parentIds)).map((parent) => [parent.id, parent]),+ );+ const toPause = new Map<string, string>();+ for (const task of completed) {+ const parent = task.parentTaskId ? parents.get(task.parentTaskId) : undefined;+ if (!parent || toPause.has(parent.id)) continue;+ // A checkpoint pauses work in progress. A parent that is already closed+ // — typically completed in this same batch — must not be re-opened.+ if (FINISHED_STATUSES.has(parent.status)) continue;+ if (this.taskModel.shouldPauseAfterComplete(parent, task))+ toPause.set(parent.id, parent.status);+ }+ // One compare-and-set for every parent, on the status just inspected: a+ // parent another request finished or canceled since the snapshot is left+ // alone.+ await this.taskModel.updateStatusIfCurrentForIds(+ [...toPause].map(([id, status]) => ({ id, status })),+ 'paused',+ );++ const runner = new TaskRunnerService(this.db, this.userId, this.workspaceId);+ await runner.cascadeOnCompletionMany(completed.map((task) => task.id));+ }++ /**+ * Archive or restore many tasks. Archiving keeps the single-task guards:+ * tasks in an open goal are refused, and the not-running / no-live-automation+ * rule is part of the one UPDATE, so a run starting concurrently still wins.+ */+ async archive(ids: string[], archived: boolean): Promise<TaskBatchResult> {+ const { result, tasks } = await this.loadSelection(ids);+ const archiveModel = new TaskArchiveModel(this.db, this.userId, this.workspaceId);++ const candidates = tasks.filter((task) => {+ if (!!task.archivedAt === archived) {+ result.skipped.push({ id: task.id, reason: 'unchanged' });+ return false;+ }+ return true;+ });++ if (!archived) {+ const restored = await archiveModel.unarchiveMany(candidates.map((task) => task.id));+ result.updated = restored.map((task) => task.id);+ return result;+ }++ // One bulk lookup for the whole selection, not one goal probe per task.+ const inGoal = await findTasksInOpenGoals(+ this.db,+ { userId: this.userId, workspaceId: this.workspaceId },+ candidates,+ );+ const eligible = candidates.filter((task) => {+ if (!inGoal.has(task.id)) return true;+ result.skipped.push({ id: task.id, reason: 'inGoal' });+ return false;+ });++ const archivedRows = await archiveModel.archiveMany(eligible.map((task) => task.id));+ const done = new Set(archivedRows.map((task) => task.id));+ for (const task of eligible) {+ if (!done.has(task.id)) result.skipped.push({ id: task.id, reason: 'running' });+ }+ result.updated = [...done];+ return result;+ }++ /**+ * Delete many tasks. Idle tasks go in one transaction (row locks, linked+ * topics, status-guarded delete); tasks with a live run take the single-task+ * path, which interrupts the run before removing the row.+ */+ async delete(ids: string[]): Promise<TaskBatchResult> {+ const { result, tasks: visible } = await this.loadSelection(ids);+ // Workspace bulk actions only affect caller-created content (the+ // `clearAll` rule, docs/usage/workspace-permissions): deleting a teammate's+ // task stays a deliberate one-at-a-time action.+ const tasks = visible.filter((task) => {+ if (!this.workspaceId || task.createdByUserId === this.userId) return true;+ result.skipped.push({ id: task.id, reason: 'forbidden' });+ return false;+ });+ const taskTopicModel = new TaskTopicModel(this.db, this.userId, this.workspaceId);+ const running = await taskTopicModel.findRunningByTaskIds(tasks.map((task) => task.id));+ const busy = new Set([+ ...running.map((topic) => topic.taskId),+ ...tasks.filter((task) => task.status === 'running').map((task) => task.id),+ ]);++ const idle = tasks.filter((task) => !busy.has(task.id));+ const deletedIdle = await this.db.transaction(async (tx) => {+ const model = new TaskModel(tx, this.userId, this.workspaceId);+ const txTopics = new TaskTopicModel(tx, this.userId, this.workspaceId);+ // The row lock is the one a run takes to record its topic: anything that+ // started after the snapshot is visible now and is left for the+ // single-task path below.+ const locked = await model.lockForStatusChange(idle.map((task) => task.id));+ const startedMeanwhile = new Set(+ (await txTopics.findRunningByTaskIds(locked.map((row) => row.id))).map(+ (topic) => topic.taskId,+ ),+ );+ const deletable = locked.filter(+ (row) => row.status !== 'running' && !startedMeanwhile.has(row.id),+ );+ const deletableIds = new Set(deletable.map((row) => row.id));+ for (const row of locked) {+ if (!deletableIds.has(row.id)) busy.add(row.id);+ }++ const topicIds = (await txTopics.findByTaskIds(deletable.map((row) => row.id)))+ .map((topic) => topic.topicId)+ .filter((topicId): topicId is string => !!topicId);+ const deleted = await model.deleteIfStatusForIds(deletable);+ if (topicIds.length > 0) {+ // Same cascade as the single delete: linked topics (including ones in+ // the recycle bin) go with the task instead of lingering as orphans.+ await new TopicModel(tx, this.userId, this.workspaceId).batchDeleteIncludingTrashed(+ topicIds,+ );+ }+ return deleted;+ });+ result.updated.push(...deletedIdle);++ const taskService = new TaskService(this.db, this.userId, this.workspaceId);+ await pMap(+ tasks.filter((task) => busy.has(task.id)),+ async (task) => {+ try {+ await taskService.deleteTask(task.id);+ result.updated.push(task.id);+ } catch (error) {+ result.failed.push({ error: errorMessage(error), id: task.id });+ }+ },+ { concurrency: BATCH_SIDE_EFFECT_CONCURRENCY },+ );++ return result;+ }+}diff --git a/apps/server/src/services/task/batchLimits.ts b/apps/server/src/services/task/batchLimits.tsnew file mode 100644index 00000000000..93405064eb7--- /dev/null+++ b/apps/server/src/services/task/batchLimits.ts@@ -0,0 +1,12 @@+/**+ * Batch contract shared by the router and the service. Kept free of imports:+ * the router module is reachable from the service's own import graph, so the+ * schema must not wait on the service module to finish evaluating.+ */++/** Upper bound of ids one batch request may carry. */+export const TASK_BATCH_MAX_IDS = 500;++/** Statuses a person can move many tasks to at once (see `USER_SELECTABLE_STATUSES`). */+export const TASK_BATCH_STATUSES = ['backlog', 'paused', 'completed', 'canceled'] as const;+export type TaskBatchStatus = (typeof TASK_BATCH_STATUSES)[number];diff --git a/apps/server/src/services/task/index.ts b/apps/server/src/services/task/index.tsindex 800564b03a5..412b81c5e94 100644--- a/apps/server/src/services/task/index.ts+++ b/apps/server/src/services/task/index.ts@@ -38,6 +38,26 @@ const SUBTASK_KICKOFF_CONCURRENCY = 5;/** How long after a run starts a task may have no recorded operation yet. */const TASK_RUN_STARTING_GRACE_MS = 2 * 60 * 1000;+/**+ * The runner marks a task `running` before it dispatches the agent and records+ * the topic / operation only after dispatch returns. Inside that window there+ * is nothing to interrupt yet, so a write that stops the task would orphan the+ * run about to start. Past the grace window a missing operation means the+ * start died.+ */+export const isTaskRunStarting = (+ task: { startedAt?: Date | string | null; status: string },+ runningTopics: { operationId?: string | null }[],+ now = Date.now(),+): boolean => {+ if (task.status !== 'running') return false;+ const startedAt = task.startedAt ? new Date(task.startedAt).getTime() : 0;+ return (+ now - startedAt < TASK_RUN_STARTING_GRACE_MS &&+ (runningTopics.length === 0 || runningTopics.some((topic) => !topic.operationId))+ );+};+export interface CreateTaskInput {assigneeAgentId?: string;assigneeUserId?: string;@@ -339,12 +359,7 @@ export class TaskService {// that window finds nothing to interrupt and would orphan the run it is// about to start. Past the grace window a missing operation means the// start died, and deletion goes ahead.- const startedAt = task.startedAt ? new Date(task.startedAt).getTime() : 0;- const isStarting =- task.status === 'running' &&- Date.now() - startedAt < TASK_RUN_STARTING_GRACE_MS &&- (runningTopics.length === 0 || runningTopics.some((topic) => !topic.operationId));- if (isStarting) {+ if (isTaskRunStarting(task, runningTopics)) {throw new TRPCError({code: 'CONFLICT',message: 'This task is still starting its run. Try deleting it again in a moment.',@@ -599,6 +614,18 @@ export class TaskService {await this.assertAssigneeUserAssignableWithDatabase(this.db, assigneeUserId);}+ /**+ * {@link assertAssigneeUserAssignable} inside the caller's transaction,+ * locking the member row until it commits — for bulk writes that assign+ * many tasks in one transaction.+ */+ async assertAssigneeUserAssignableLocked(+ tx: LobeChatDatabase,+ assigneeUserId: string,+ ): Promise<void> {+ await this.assertAssigneeUserAssignableWithDatabase(tx, assigneeUserId, true);+ }+private async assertAssigneeUserAssignableWithDatabase(db: LobeChatDatabase,assigneeUserId?: string | null,diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex 31572484908..bb715b671a2 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -2608,6 +2608,49 @@"taskList.assigneeSelector.agentGroup": "Agents","taskList.assigneeSelector.workspaceMemberGroup": "Workspace members","taskList.breadcrumb.task": "Task",+ "taskList.bulk.actions": "Actions",+ "taskList.bulk.archive": "Archive",+ "taskList.bulk.assignAgent": "Assign to agent…",+ "taskList.bulk.assignToMe": "Assign to me",+ "taskList.bulk.changeStatus": "Change status…",+ "taskList.bulk.clear": "Clear selection",+ "taskList.bulk.copied_one": "Copied {{count}} task ID",+ "taskList.bulk.copied_other": "Copied {{count}} task IDs",+ "taskList.bulk.copyIds": "Copy task IDs",+ "taskList.bulk.count_one": "{{count}} task",+ "taskList.bulk.count_other": "{{count}} tasks",+ "taskList.bulk.delete": "Delete…",+ "taskList.bulk.deleteConfirm.content": "Deleted tasks and their comments and runs cannot be recovered; their subtasks stay as top-level tasks. Running tasks are stopped first.",+ "taskList.bulk.deleteConfirm.ok": "Delete",+ "taskList.bulk.deleteConfirm.title_one": "Delete {{count}} task?",+ "taskList.bulk.deleteConfirm.title_other": "Delete {{count}} tasks?",+ "taskList.bulk.followUpFailed.desc": "The tasks were completed, but checkpoint pauses and dependent tasks could not be processed. Check the affected parent and dependent tasks.",+ "taskList.bulk.followUpFailed.title": "Completion follow-ups did not run",+ "taskList.bulk.noResults": "No matching actions",+ "taskList.bulk.progress": "Updating {{done}} / {{total}}…",+ "taskList.bulk.refreshFailed.desc": "The changes were saved, but the list could not refresh and may show outdated tasks.",+ "taskList.bulk.refreshFailed.retry": "Refresh",+ "taskList.bulk.refreshFailed.title": "List not refreshed",+ "taskList.bulk.result.deleted_one": "{{count}} task deleted",+ "taskList.bulk.result.deleted_other": "{{count}} tasks deleted",+ "taskList.bulk.result.error": "The batch action failed. Try again.",+ "taskList.bulk.result.failed_one": "{{count}} failed",+ "taskList.bulk.result.failed_other": "{{count}} failed",+ "taskList.bulk.result.skipped_one": "{{count}} skipped",+ "taskList.bulk.result.skipped_other": "{{count}} skipped",+ "taskList.bulk.result.updated_one": "{{count}} task updated",+ "taskList.bulk.result.updated_other": "{{count}} tasks updated",+ "taskList.bulk.search.agent": "Assign to agent…",+ "taskList.bulk.search.placeholder": "Type a command…",+ "taskList.bulk.search.priority": "Set priority…",+ "taskList.bulk.search.status": "Change status…",+ "taskList.bulk.selectTask": "Select {{task}}",+ "taskList.bulk.selected_one": "{{count}} selected",+ "taskList.bulk.selected_other": "{{count}} selected",+ "taskList.bulk.setPriority": "Set priority…",+ "taskList.bulk.unarchive": "Unarchive",+ "taskList.bulk.unassignAgent": "No agent",+ "taskList.bulk.unassignMember": "Unassign member","taskList.completedTasks.all": "All","taskList.completedTasks.day": "Past day","taskList.completedTasks.month": "Past month",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex a36de061b7e..9e9105d9f84 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -2608,6 +2608,49 @@"taskList.assigneeSelector.agentGroup": "助理","taskList.assigneeSelector.workspaceMemberGroup": "工作区成员","taskList.breadcrumb.task": "任务",+ "taskList.bulk.actions": "操作",+ "taskList.bulk.archive": "归档",+ "taskList.bulk.assignAgent": "指派给助理…",+ "taskList.bulk.assignToMe": "指派给我",+ "taskList.bulk.changeStatus": "修改状态…",+ "taskList.bulk.clear": "取消选择",+ "taskList.bulk.copied_one": "已复制 {{count}} 个任务 ID",+ "taskList.bulk.copied_other": "已复制 {{count}} 个任务 ID",+ "taskList.bulk.copyIds": "复制任务 ID",+ "taskList.bulk.count_one": "{{count}} 个任务",+ "taskList.bulk.count_other": "{{count}} 个任务",+ "taskList.bulk.delete": "删除…",+ "taskList.bulk.deleteConfirm.content": "删除后,任务及其评论和运行记录无法恢复,子任务会保留为顶层任务。运行中的任务会先被停止。",+ "taskList.bulk.deleteConfirm.ok": "删除",+ "taskList.bulk.deleteConfirm.title_one": "删除 {{count}} 个任务?",+ "taskList.bulk.deleteConfirm.title_other": "删除 {{count}} 个任务?",+ "taskList.bulk.followUpFailed.desc": "任务已标记完成,但检查点暂停和依赖任务没有处理成功,请检查相关的父任务和依赖任务。",+ "taskList.bulk.followUpFailed.title": "完成后的后续处理未执行",+ "taskList.bulk.noResults": "没有匹配的操作",+ "taskList.bulk.progress": "正在处理 {{done}} / {{total}}…",+ "taskList.bulk.refreshFailed.desc": "修改已保存,但列表刷新失败,当前显示的可能是旧数据。",+ "taskList.bulk.refreshFailed.retry": "刷新",+ "taskList.bulk.refreshFailed.title": "列表未刷新",+ "taskList.bulk.result.deleted_one": "已删除 {{count}} 个任务",+ "taskList.bulk.result.deleted_other": "已删除 {{count}} 个任务",+ "taskList.bulk.result.error": "批量操作失败,请重试。",+ "taskList.bulk.result.failed_one": "{{count}} 个失败",+ "taskList.bulk.result.failed_other": "{{count}} 个失败",+ "taskList.bulk.result.skipped_one": "{{count}} 个跳过",+ "taskList.bulk.result.skipped_other": "{{count}} 个跳过",+ "taskList.bulk.result.updated_one": "已更新 {{count}} 个任务",+ "taskList.bulk.result.updated_other": "已更新 {{count}} 个任务",+ "taskList.bulk.search.agent": "指派给助理…",+ "taskList.bulk.search.placeholder": "输入命令…",+ "taskList.bulk.search.priority": "设置优先级…",+ "taskList.bulk.search.status": "修改状态…",+ "taskList.bulk.selectTask": "选择 {{task}}",+ "taskList.bulk.selected_one": "已选择 {{count}} 项",+ "taskList.bulk.selected_other": "已选择 {{count}} 项",+ "taskList.bulk.setPriority": "设置优先级…",+ "taskList.bulk.unarchive": "取消归档",+ "taskList.bulk.unassignAgent": "不指派助理",+ "taskList.bulk.unassignMember": "取消指派成员","taskList.completedTasks.all": "全部","taskList.completedTasks.day": "过去一天","taskList.completedTasks.month": "过去一个月",diff --git a/packages/database/src/models/__tests__/task.bulk.test.ts b/packages/database/src/models/__tests__/task.bulk.test.tsnew file mode 100644index 00000000000..124d5c41414--- /dev/null+++ b/packages/database/src/models/__tests__/task.bulk.test.ts@@ -0,0 +1,121 @@+// @vitest-environment node+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../core/getTestDB';+import { users } from '../../schemas';+import type { LobeChatDatabase } from '../../type';+import { TaskModel } from '../task';+import { TaskArchiveModel } from '../taskArchive';+import { TaskTopicModel } from '../taskTopic';++const serverDB: LobeChatDatabase = await getTestDB();++const userId = 'task-bulk-model-test-user-id';+const otherUserId = 'task-bulk-model-test-other-user-id';++beforeEach(async () => {+ await serverDB.delete(users);+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);+});++afterEach(async () => {+ await serverDB.delete(users);+});++/** Bulk writers used by the task list's batch actions. */+describe('task bulk model methods', () => {+ const setup = async () => {+ const mine = new TaskModel(serverDB, userId);+ const theirs = new TaskModel(serverDB, otherUserId);+ const a = await mine.create({ instruction: 'A' });+ const b = await mine.create({ instruction: 'B' });+ const foreign = await theirs.create({ instruction: 'Foreign' });+ return { a, b, foreign, mine, theirs };+ };++ it('updateFieldsForIds writes every owned row and never another user’s', async () => {+ const { a, b, foreign, mine, theirs } = await setup();++ const updated = await mine.updateFieldsForIds([a.id, b.id, foreign.id], { priority: 1 });++ expect(updated.map((task) => task.id).sort()).toEqual([a.id, b.id].sort());+ expect((await mine.findById(b.id))?.priority).toBe(1);+ expect((await theirs.findById(foreign.id))?.priority).toBe(0);+ expect(await mine.updateFieldsForIds([], { priority: 1 })).toEqual([]);+ });++ it('lockForBulkEdit returns only owned rows with the columns a bulk edit decides on', async () => {+ const { a, foreign, mine } = await setup();++ const locked = await serverDB.transaction((tx) =>+ new TaskModel(tx, userId).lockForBulkEdit([a.id, foreign.id]),+ );++ expect(locked).toHaveLength(1);+ expect(locked[0]).toMatchObject({+ archivedAt: null,+ createdByUserId: userId,+ id: a.id,+ status: 'backlog',+ visibility: (await mine.findById(a.id))?.visibility,+ });+ });++ it('deleteIfStatusForIds deletes only rows still in the expected status', async () => {+ const { a, b, foreign, mine, theirs } = await setup();+ await mine.update(b.id, { status: 'running' });++ const deleted = await mine.deleteIfStatusForIds([+ { id: a.id, status: 'backlog' },+ { id: b.id, status: 'backlog' },+ { id: foreign.id, status: 'backlog' },+ ]);++ expect(deleted).toEqual([a.id]);+ expect(await mine.findById(b.id)).not.toBeNull();+ expect(await theirs.findById(foreign.id)).not.toBeNull();+ expect(await mine.deleteIfStatusForIds([])).toEqual([]);+ });++ it('archiveMany / unarchiveMany apply the guard per row and stay in scope', async () => {+ const { a, b, foreign, mine, theirs } = await setup();+ await mine.update(b.id, { status: 'running' });+ const archive = new TaskArchiveModel(serverDB, userId);++ const archived = await archive.archiveMany([a.id, b.id, foreign.id]);+ expect(archived.map((task) => task.id)).toEqual([a.id]);+ expect((await theirs.findById(foreign.id))?.archivedAt).toBeNull();++ const restored = await archive.unarchiveMany([a.id, foreign.id]);+ expect(restored.map((task) => task.id)).toEqual([a.id]);+ expect(await archive.archiveMany([])).toEqual([]);+ });++ it('findByTaskIds lists topic links of owned tasks only', async () => {+ const { a, foreign } = await setup();+ const topics = new TaskTopicModel(serverDB, userId);++ expect(await topics.findByTaskIds([])).toEqual([]);+ expect(await topics.findByTaskIds([a.id, foreign.id])).toEqual([]);+ });++ it('updateStatusIfCurrentForIds moves only rows still in the inspected status', async () => {+ const { a, b, foreign, mine, theirs } = await setup();+ await mine.update(b.id, { status: 'completed' });++ const updated = await mine.updateStatusIfCurrentForIds(+ [+ { id: a.id, status: 'backlog' },+ { id: b.id, status: 'running' },+ { id: foreign.id, status: 'backlog' },+ ],+ 'paused',+ );++ expect(updated).toEqual([a.id]);+ expect((await mine.findById(a.id))?.status).toBe('paused');+ expect((await mine.findById(b.id))?.status).toBe('completed');+ expect((await theirs.findById(foreign.id))?.status).toBe('backlog');+ expect(await mine.updateStatusIfCurrentForIds([], 'paused')).toEqual([]);+ });+});diff --git a/packages/database/src/models/__tests__/taskTopic.test.ts b/packages/database/src/models/__tests__/taskTopic.test.tsindex f54776ec893..f0d6943ea89 100644--- a/packages/database/src/models/__tests__/taskTopic.test.ts+++ b/packages/database/src/models/__tests__/taskTopic.test.ts@@ -206,6 +206,8 @@ describe('TaskTopicModel', () => {const outside = await topicModel.findByTaskId(taskOutside.id);expect(outside[0]!.status).toBe('running');+ // The set-based topic write only touches the canceled runs' topics.+ expect((await getTopic('tpc_bulk_outside')).completedAt).toBeNull();});it('returns an empty list for an empty id set', async () => {diff --git a/packages/database/src/models/goalGraph.ts b/packages/database/src/models/goalGraph.tsindex 4e784c3e896..f231a8ed001 100644--- a/packages/database/src/models/goalGraph.ts+++ b/packages/database/src/models/goalGraph.ts@@ -568,6 +568,92 @@ export class GoalGraphModel {return nearest ? { id: nearest.id, title: nearest.title } : undefined;};+ /**+ * {@link findGoalByTaskId} for many tasks in two queries, with the same+ * nearest-ancestor rule and the goal's status — for bulk task writes that+ * must not probe each task on its own. Tasks without a goal are absent.+ */+ findGoalsByTaskIds = async (+ taskIds: string[],+ ): Promise<Map<string, { id: string; status: string; title: string }>> => {+ const result = new Map<string, { id: string; status: string; title: string }>();+ if (taskIds.length === 0) return result;++ const chain = await this.db.execute<{ depth: number; id: string; root: string }>(sql`+ WITH RECURSIVE chain(root, id, depth, visited) AS (+ SELECT ${tasks.id}, ${tasks.id}, 0, ARRAY[${tasks.id}] FROM ${tasks}+ WHERE ${tasks.id} IN (${sql.join(+ taskIds.map((id) => sql`${id}`),+ sql`, `,+ )})+ UNION ALL+ SELECT chain.root, ${tasks.parentTaskId}, chain.depth + 1, chain.visited || ${tasks.parentTaskId}+ FROM ${tasks} JOIN chain ON ${tasks.id} = chain.id+ WHERE ${tasks.parentTaskId} IS NOT NULL+ AND NOT (${tasks.parentTaskId} = ANY(chain.visited))+ )+ SELECT root, id, depth FROM chain+ `);+ // ancestor id → every selected root it sits above, with its distance.+ const rootsOf = new Map<string, { depth: number; root: string }[]>();+ for (const row of chain.rows) {+ const list = rootsOf.get(row.id) ?? [];+ list.push({ depth: Number(row.depth), root: row.root });+ rootsOf.set(row.id, list);+ }+ const chainIds = [...rootsOf.keys()];+ if (chainIds.length === 0) return result;++ const rows = await this.db+ .select({+ carrierTaskId: goals.subjectId,+ createdAt: goals.createdAt,+ id: goals.id,+ nodeTaskId: goalNodes.taskId,+ status: goals.status,+ subjectType: goals.subjectType,+ title: goals.title,+ })+ .from(goals)+ .leftJoin(goalNodes, and(eq(goalNodes.goalId, goals.id), inArray(goalNodes.taskId, chainIds)))+ .where(+ and(+ this.ownership(),+ or(+ inArray(goalNodes.taskId, chainIds),+ and(eq(goals.subjectType, 'task'), inArray(goals.subjectId, chainIds)),+ ),+ ),+ );++ const best = new Map<+ string,+ { createdAt: number; depth: number; row: (typeof rows)[number] }+ >();+ const consider = (anchorId: string | null, row: (typeof rows)[number]) => {+ if (!anchorId) return;+ for (const { depth, root } of rootsOf.get(anchorId) ?? []) {+ const createdAt = new Date(row.createdAt).getTime();+ const current = best.get(root);+ if (+ !current ||+ depth < current.depth ||+ (depth === current.depth && createdAt > current.createdAt)+ ) {+ best.set(root, { createdAt, depth, row });+ }+ }+ };+ for (const row of rows) {+ consider(row.nodeTaskId, row);+ if (row.subjectType === 'task') consider(row.carrierTaskId, row);+ }+ for (const [root, { row }] of best) {+ result.set(root, { id: row.id, status: row.status, title: row.title });+ }+ return result;+ };+createNode = async (goalId: string, input: CreateNodeInput) =>this.db.transaction(async (tx) => {if (!(await this.ownedGoal(goalId, tx))) return undefined;diff --git a/packages/database/src/models/task/index.ts b/packages/database/src/models/task/index.tsindex 4724a537578..ac31a4775b4 100644--- a/packages/database/src/models/task/index.ts+++ b/packages/database/src/models/task/index.ts@@ -212,6 +212,10 @@ export class TaskModel {return rows.deleteIfStatus(this.ctx, id, status);}+ async deleteIfStatusForIds(expected: { id: string; status: string }[]): Promise<string[]> {+ return rows.deleteIfStatusForIds(this.ctx, expected);+ }+async deleteAll(options?: { restrictToCreator?: boolean }): Promise<number> {return rows.deleteAll(this.ctx, options);}@@ -296,6 +300,13 @@ export class TaskModel {return rows.updateStatusIfCurrent(this.ctx, id, currentStatus, status, extra);}+ async updateStatusIfCurrentForIds(+ expected: { id: string; status: string }[],+ status: string,+ ): Promise<string[]> {+ return rows.updateStatusIfCurrentForIds(this.ctx, expected, status);+ }+async completeIfCompletionRequested(id: string, operationId: string): Promise<TaskItem | null> {return rows.completeIfCompletionRequested(this.ctx, id, operationId);}@@ -316,6 +327,18 @@ export class TaskModel {return rows.updateStatusForIds(this.ctx, ids, status, extra);}+ async lockForBulkEdit(ids: string[]) {+ return rows.lockForBulkEdit(this.ctx, ids);+ }++ async updateFieldsForIds(+ ids: string[],+ data: Parameters<typeof rows.updateFieldsForIds>[2],+ configById?: ReadonlyMap<string, unknown>,+ ): Promise<TaskItem[]> {+ return rows.updateFieldsForIds(this.ctx, ids, data, configById);+ }+// ========== Config ==========/**diff --git a/packages/database/src/models/task/rows.ts b/packages/database/src/models/task/rows.tsindex 3e1701df74e..8899863ba5a 100644--- a/packages/database/src/models/task/rows.ts+++ b/packages/database/src/models/task/rows.ts@@ -223,6 +223,24 @@ export const deleteIfStatus = async (return deleted.length > 0;};+/**+ * Bulk counterpart of {@link deleteIfStatus}: delete each task only while it+ * still has the status the caller locked and decided on. Returns the ids that+ * were actually removed.+ */+export const deleteIfStatusForIds = async (+ ctx: TaskModelContext,+ expected: { id: string; status: string }[],+): Promise<string[]> => {+ if (expected.length === 0) return [];+ const matches = expected.map(({ id, status }) => and(eq(tasks.id, id), eq(tasks.status, status)));+ const deleted = await ctx.db+ .delete(tasks)+ .where(and(or(...matches), taskOwnership(ctx)))+ .returning({ id: tasks.id });+ return deleted.map(({ id }) => id);+};+/** See {@link delete}: bulk task deletion likewise leaves Work artifacts intact. */export const deleteAll = async (ctx: TaskModelContext,@@ -271,6 +289,28 @@ export const updateStatusIfCurrent = async (return task ?? null;};+/**+ * Bulk {@link updateStatusIfCurrent}: move each task to `status` only while it+ * still has the status the caller inspected, in one statement. Returns the ids+ * that were actually updated.+ */+export const updateStatusIfCurrentForIds = async (+ ctx: TaskModelContext,+ expected: { id: string; status: string }[],+ status: string,+): Promise<string[]> => {+ if (expected.length === 0) return [];+ const matches = expected.map(({ id, status: current }) =>+ and(eq(tasks.id, id), eq(tasks.status, current)),+ );+ const updated = await ctx.db+ .update(tasks)+ .set({ status, updatedAt: new Date() })+ .where(and(or(...matches), taskOwnership(ctx)))+ .returning({ id: tasks.id });+ return updated.map(({ id }) => id);+};+/** `context.completion.requestedByOperationId` — the run a deferred completion waits for. */const completionRequest = sql`${tasks.context} -> 'completion' ->> 'requestedByOperationId'`;const withoutCompletionRequest = sql`jsonb_set(${tasks.context}, '{completion,requestedByOperationId}', 'null'::jsonb)`;@@ -366,6 +406,67 @@ export const updateStatusForIds = async (.returning();};+/**+ * Lock a set of tasks for a bulk field edit and return what the edit needs to+ * decide and describe each row: the values it is about to replace (for the+ * activity diff and the stale-repo rule) and the visibility its activity row+ * inherits.+ */+export const lockForBulkEdit = async (ctx: TaskModelContext, ids: string[]) => {+ if (ids.length === 0) return [];+ return ctx.db+ .select({+ archivedAt: tasks.archivedAt,+ assigneeAgentId: tasks.assigneeAgentId,+ assigneeUserId: tasks.assigneeUserId,+ automationMode: tasks.automationMode,+ config: tasks.config,+ createdByUserId: tasks.createdByUserId,+ heartbeatInterval: tasks.heartbeatInterval,+ id: tasks.id,+ priority: tasks.priority,+ schedulePattern: tasks.schedulePattern,+ status: tasks.status,+ visibility: tasks.visibility,+ })+ .from(tasks)+ .where(and(inArray(tasks.id, ids), taskOwnership(ctx)))+ .for('update');+};++/**+ * Write the same plain-column patch to many tasks in one statement. Callers+ * own the invariants (and the assignee repo-selection rule, see+ * `withStaleReposCleared`) — this is only the set-based write.+ *+ * `configById` replaces the `config` column of just those rows, in the same+ * statement (a `CASE` on the id), for rows whose patch has to rewrite their+ * own config; every other row keeps its config untouched.+ */+export const updateFieldsForIds = async (+ ctx: TaskModelContext,+ ids: string[],+ data: Partial<Pick<NewTask, 'assigneeAgentId' | 'assigneeUserId' | 'priority'>>,+ configById?: ReadonlyMap<string, unknown>,+): Promise<TaskItem[]> => {+ if (ids.length === 0) return [];+ const configCases = configById ? [...configById].filter(([id]) => ids.includes(id)) : [];+ const config =+ configCases.length > 0+ ? sql`CASE ${tasks.id} ${sql.join(+ configCases.map(+ ([id, value]) => sql`WHEN ${id} THEN ${JSON.stringify(value ?? null)}::jsonb`,+ ),+ sql` `,+ )} ELSE ${tasks.config} END`+ : undefined;+ return ctx.db+ .update(tasks)+ .set({ ...data, ...(config && { config }), updatedAt: new Date() })+ .where(and(inArray(tasks.id, ids), taskOwnership(ctx)))+ .returning();+};+export const updateHeartbeat = async (ctx: TaskModelContext, id: string): Promise<void> => {await ctx.db.update(tasks)diff --git a/packages/database/src/models/taskArchive.ts b/packages/database/src/models/taskArchive.tsindex 4686b44643e..ebeec89b8eb 100644--- a/packages/database/src/models/taskArchive.ts+++ b/packages/database/src/models/taskArchive.ts@@ -1,4 +1,4 @@-import { and, eq, inArray, ne, sql } from 'drizzle-orm';+import { and, inArray, ne, sql } from 'drizzle-orm';import { tasks } from '../schemas/task';import type { LobeChatDatabase } from '../type';@@ -43,12 +43,22 @@ export class TaskArchiveModel {* task is finished") can't archive a task that was reopened since.*/async archive(id: string, options: { onlyStatuses?: string[] } = {}) {- const [task] = await this.db+ const [task] = await this.archiveMany([id], options);+ return task ?? null;+ }++ /**+ * {@link archive} for many tasks in one guarded statement. Returns only the+ * rows that were archived; a missing or blocked task is simply absent.+ */+ async archiveMany(ids: string[], options: { onlyStatuses?: string[] } = {}) {+ if (ids.length === 0) return [];+ return this.db.update(tasks).set({ archivedAt: sql`COALESCE(${tasks.archivedAt}, now())`, updatedAt: new Date() }).where(and(- eq(tasks.id, id),+ inArray(tasks.id, ids),this.ownership(),ne(tasks.status, 'running'),options.onlyStatuses ? inArray(tasks.status, options.onlyStatuses) : undefined,@@ -58,16 +68,21 @@ export class TaskArchiveModel {),).returning();- return task ?? null;}/** Restore an archived task. Always allowed: it never hides work. */async unarchive(id: string) {- const [task] = await this.db+ const [task] = await this.unarchiveMany([id]);+ return task ?? null;+ }++ /** {@link unarchive} for many tasks in one statement. */+ async unarchiveMany(ids: string[]) {+ if (ids.length === 0) return [];+ return this.db.update(tasks).set({ archivedAt: null, updatedAt: new Date() })- .where(and(eq(tasks.id, id), this.ownership()))+ .where(and(inArray(tasks.id, ids), this.ownership())).returning();- return task ?? null;}}diff --git a/packages/database/src/models/taskTopic.ts b/packages/database/src/models/taskTopic.tsindex 9d95bfef011..e9d5a22f59f 100644--- a/packages/database/src/models/taskTopic.ts+++ b/packages/database/src/models/taskTopic.ts@@ -150,8 +150,22 @@ export class TaskTopicModel {).returning();- for (const topic of canceled) {- if (topic.topicId) await this.markTopicEnded(topic.topicId, 'canceled');+ // One statement for every ended topic: callers run this inside a+ // transaction holding task row locks, so a per-topic loop would stretch+ // those locks over hundreds of sequential writes in a large batch.+ const topicIds = canceled+ .map((topic) => topic.topicId)+ .filter((topicId): topicId is string => !!topicId);+ if (topicIds.length > 0) {+ await this.db+ .update(topics)+ .set({ completedAt: new Date() })+ .where(+ and(+ inArray(topics.id, topicIds),+ buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, topics),+ ),+ );}return canceled;@@ -385,6 +399,15 @@ export class TaskTopicModel {.orderBy(desc(taskTopics.seq));}+ async findByTaskIds(taskIds: string[]): Promise<TaskTopicItem[]> {+ if (taskIds.length === 0) return [];++ return this.db+ .select()+ .from(taskTopics)+ .where(and(inArray(taskTopics.taskId, taskIds), this.ownership()));+ }+async findRunningByTaskIds(taskIds: string[]): Promise<TaskTopicItem[]> {if (taskIds.length === 0) return [];diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex ae15c80ea3d..148088c03f0 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -3073,6 +3073,52 @@ export default {'taskList.archived': 'Archived','taskList.visibility.all': 'All','taskList.visibility.label': 'Visibility',+ 'taskList.bulk.actions': 'Actions',+ 'taskList.bulk.archive': 'Archive',+ 'taskList.bulk.assignAgent': 'Assign to agent…',+ 'taskList.bulk.assignToMe': 'Assign to me',+ 'taskList.bulk.changeStatus': 'Change status…',+ 'taskList.bulk.clear': 'Clear selection',+ 'taskList.bulk.copied_one': 'Copied {{count}} task ID',+ 'taskList.bulk.copied_other': 'Copied {{count}} task IDs',+ 'taskList.bulk.copyIds': 'Copy task IDs',+ 'taskList.bulk.count_one': '{{count}} task',+ 'taskList.bulk.count_other': '{{count}} tasks',+ 'taskList.bulk.delete': 'Delete…',+ 'taskList.bulk.deleteConfirm.content':+ 'Deleted tasks and their comments and runs cannot be recovered; their subtasks stay as top-level tasks. Running tasks are stopped first.',+ 'taskList.bulk.deleteConfirm.ok': 'Delete',+ 'taskList.bulk.deleteConfirm.title_one': 'Delete {{count}} task?',+ 'taskList.bulk.deleteConfirm.title_other': 'Delete {{count}} tasks?',+ 'taskList.bulk.followUpFailed.desc':+ 'The tasks were completed, but checkpoint pauses and dependent tasks could not be processed. Check the affected parent and dependent tasks.',+ 'taskList.bulk.followUpFailed.title': 'Completion follow-ups did not run',+ 'taskList.bulk.noResults': 'No matching actions',+ 'taskList.bulk.progress': 'Updating {{done}} / {{total}}…',+ 'taskList.bulk.refreshFailed.desc':+ 'The changes were saved, but the list could not refresh and may show outdated tasks.',+ 'taskList.bulk.refreshFailed.retry': 'Refresh',+ 'taskList.bulk.refreshFailed.title': 'List not refreshed',+ 'taskList.bulk.result.deleted_one': '{{count}} task deleted',+ 'taskList.bulk.result.deleted_other': '{{count}} tasks deleted',+ 'taskList.bulk.result.error': 'The batch action failed. Try again.',+ 'taskList.bulk.result.failed_one': '{{count}} failed',+ 'taskList.bulk.result.failed_other': '{{count}} failed',+ 'taskList.bulk.result.skipped_one': '{{count}} skipped',+ 'taskList.bulk.result.skipped_other': '{{count}} skipped',+ 'taskList.bulk.result.updated_one': '{{count}} task updated',+ 'taskList.bulk.result.updated_other': '{{count}} tasks updated',+ 'taskList.bulk.search.agent': 'Assign to agent…',+ 'taskList.bulk.search.placeholder': 'Type a command…',+ 'taskList.bulk.search.priority': 'Set priority…',+ 'taskList.bulk.search.status': 'Change status…',+ 'taskList.bulk.selectTask': 'Select {{task}}',+ 'taskList.bulk.selected_one': '{{count}} selected',+ 'taskList.bulk.selected_other': '{{count}} selected',+ 'taskList.bulk.setPriority': 'Set priority…',+ 'taskList.bulk.unarchive': 'Unarchive',+ 'taskList.bulk.unassignAgent': 'No agent',+ 'taskList.bulk.unassignMember': 'Unassign member','taskList.breadcrumb.task': 'Task','taskList.empty': 'No tasks yet','taskList.emptyHero.greeting': 'What should we tackle today?',diff --git a/src/features/AgentTasks/AgentTaskList/AgentTasksPage.tsx b/src/features/AgentTasks/AgentTaskList/AgentTasksPage.tsxindex e50431c3bf3..87a7473d83b 100644--- a/src/features/AgentTasks/AgentTaskList/AgentTasksPage.tsx+++ b/src/features/AgentTasks/AgentTaskList/AgentTasksPage.tsx@@ -544,6 +544,13 @@ const AgentTasksPage = memo<AgentTasksPageProps>(({ agentId, headerActions, proj): t('taskList.scheduled.empty')}+ selectionScope={[+ collection,+ isMineCollection ? myTaskScope : '',+ collectionPage,+ agentId ?? '',+ projectId ?? '',+ ].join(':')}onRetry={() => collectionSWR.mutate()}/>{(collectionTasksTotal > COLLECTION_PAGE_SIZE || collectionPage > 1) && (diff --git a/src/features/AgentTasks/AgentTaskList/TaskList.tsx b/src/features/AgentTasks/AgentTaskList/TaskList.tsxindex 8a47b840de8..ba25c7a5ce9 100644--- a/src/features/AgentTasks/AgentTaskList/TaskList.tsx+++ b/src/features/AgentTasks/AgentTaskList/TaskList.tsx@@ -13,7 +13,7 @@ import {} from '@lobehub/ui';import { ClipboardCheckIcon } from 'lucide-react';import type { ReactNode } from 'react';-import { memo, useCallback, useMemo, useState } from 'react';+import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';import type { Components } from 'react-virtuoso';import { Virtuoso } from 'react-virtuoso';@@ -34,6 +34,11 @@ import {groupTaskItems,isTaskHiddenByCompletedFilter,} from './listViewOptions';+import SelectableTaskRow from './selection/SelectableTaskRow';+import { useTaskSelectionStore } from './selection/store';+import TaskBulkActionBar from './selection/TaskBulkActionBar';+import { isEditableTarget } from './selection/taskSelectionModel';+import { useSelectionScope } from './selection/useSelectionScope';import TaskGroupLabel from './TaskGroupLabel';import TaskItemSkeleton from './TaskItemSkeleton';import type { TaskListGroupEntry, TaskListVirtualItem } from './taskListVirtualModel';@@ -63,6 +68,13 @@ interface TaskListProps {/** Store entry of the list to render (`useFetchTaskList().queryKey`) when `items` is absent. */queryKey?: string;routeScope?: TaskItemRouteScope;+ /**+ * Identity of the collection behind `items` (tab, sub-scope, page, owner).+ * The selection is dropped whenever it changes; without it every items-backed+ * collection shares one scope, and a task present in two of them would stay+ * selected across the switch.+ */+ selectionScope?: string;}/** Row height the window sizes itself by before it has measured real rows. */@@ -224,6 +236,62 @@ const TaskList = memo<TaskListProps>((props) => {});}, []);+ // Selectable rows in display order, collapsed groups included (⌘A selects+ // every task the current view shows, not only the expanded ones). Grey+ // parent-context rows only give a nested child its place; they are not part+ // of the view's result set.+ const selectableIds = useMemo(() => {+ const ids = new Set<string>();+ for (const entry of groupedTaskEntries) {+ const rows =+ entry.subGroups.length > 0 ? entry.subGroups.flatMap((sub) => sub.rows) : entry.rows;+ for (const row of rows) if (!row.isParentContext) ids.add(row.task.id);+ }+ return [...ids];+ }, [groupedTaskEntries]);+ const listRef = useRef<HTMLDivElement>(null);+ const selectableIdsRef = useRef(selectableIds);+ selectableIdsRef.current = selectableIds;+ const getSelectionOrder = useCallback(() => selectableIdsRef.current, []);++ // A selection never outlives the rows it names: prune on every list change,+ // and drop it when this list (or its collection) goes away.+ useEffect(() => {+ useTaskSelectionStore.getState().prune(new Set(selectableIds));+ }, [selectableIds]);+ const selectionScope = props.selectionScope ?? (items ? 'items' : (queryKey ?? ''));+ useSelectionScope(selectionScope);++ useEffect(() => {+ const onKeyDown = (event: KeyboardEvent) => {+ if (event.defaultPrevented || isEditableTarget(event.target)) return;+ // Only when nothing else holds focus, or focus is on the list itself:+ // ⌘A over a side panel's text keeps selecting that text, and Esc inside+ // a drawer or popover stays theirs.+ const target = event.target as Node | null;+ const onList = !!target && !!listRef.current?.contains(target);+ if (target !== document.body && !onList) return;+ const selection = useTaskSelectionStore.getState();+ if (+ event.key.toLowerCase() === 'a' &&+ (event.metaKey || event.ctrlKey) &&+ !event.shiftKey &&+ !event.altKey+ ) {+ if (selectableIdsRef.current.length === 0) return;+ event.preventDefault();+ selection.selectAll(selectableIdsRef.current);+ return;+ }+ if (event.key === 'Escape' && selection.selectedIds.length > 0 && !selection.progress) {+ event.preventDefault();+ selection.clear();+ }+ };+ window.addEventListener('keydown', onKeyDown);+ return () => window.removeEventListener('keydown', onKeyDown);+ }, []);+const virtualItems = useMemo(() =>flattenTaskListEntries(groupedTaskEntries, {@@ -245,13 +313,25 @@ const TaskList = memo<TaskListProps>((props) => {// Matches the 2px row gap the former Block wrapper gave the list.<div style={{ paddingBlock: 1, paddingInline: 2 }}><TaskRowIndent depth={item.row.depth} muted={item.row.isParentContext}>- <AgentTaskItem routeScope={routeScope} task={item.row.task} />+ {item.row.isParentContext ? (+ <AgentTaskItem routeScope={routeScope} task={item.row.task} />+ ) : (+ <SelectableTaskRow+ id={item.row.task.id}+ order={getSelectionOrder}+ label={[item.row.task.identifier, item.row.task.name?.trim()]+ .filter(Boolean)+ .join(' ')}+ >+ <AgentTaskItem routeScope={routeScope} task={item.row.task} />+ </SelectableTaskRow>+ )}</TaskRowIndent>{item.showDivider && <Divider dashed style={{ margin: 0 }} />}</div>);},- [routeScope, toggleCollapsed],+ [getSelectionOrder, routeScope, toggleCollapsed],);const skeleton = (@@ -318,28 +398,31 @@ const TaskList = memo<TaskListProps>((props) => {loading={skeleton}onRetry={onRetry}>- <div ref={anchorRef} style={{ width: '100%' }}>- {scrollParent && (- <Virtuoso- // Footer belongs to the window so it follows the last rendered row- // rather than sitting under an unrendered tail.- components={VIRTUAL_LIST_COMPONENTS}- computeItemKey={(_index, item) => item.key}- customScrollParent={scrollParent}- data={virtualItems}- defaultItemHeight={DEFAULT_ROW_HEIGHT}- increaseViewportBy={{ bottom: 600, top: 600 }}- itemContent={renderItem}- context={{- footer: (- <>- {hiddenFooter}- {truncatedFooter}- </>- ),- }}- />- )}+ <div ref={listRef} style={{ width: '100%' }}>+ <TaskBulkActionBar tasks={tasks} />+ <div ref={anchorRef} style={{ width: '100%' }}>+ {scrollParent && (+ <Virtuoso+ // Footer belongs to the window so it follows the last rendered row+ // rather than sitting under an unrendered tail.+ components={VIRTUAL_LIST_COMPONENTS}+ computeItemKey={(_index, item) => item.key}+ customScrollParent={scrollParent}+ data={virtualItems}+ defaultItemHeight={DEFAULT_ROW_HEIGHT}+ increaseViewportBy={{ bottom: 600, top: 600 }}+ itemContent={renderItem}+ context={{+ footer: (+ <>+ {hiddenFooter}+ {truncatedFooter}+ </>+ ),+ }}+ />+ )}+ </div></div></AsyncBoundary>);diff --git a/src/features/AgentTasks/AgentTaskList/selection/SelectableTaskRow.test.tsx b/src/features/AgentTasks/AgentTaskList/selection/SelectableTaskRow.test.tsxnew file mode 100644index 00000000000..73c5f90822f--- /dev/null+++ b/src/features/AgentTasks/AgentTaskList/selection/SelectableTaskRow.test.tsx@@ -0,0 +1,32 @@+import { render, screen } from '@testing-library/react';+import { afterEach, describe, expect, it, vi } from 'vitest';++import SelectableTaskRow from './SelectableTaskRow';+import { useTaskSelectionStore } from './store';++vi.mock('react-i18next', () => ({+ useTranslation: () => ({+ t: (key: string, options?: { task?: string }) =>+ key === 'taskList.bulk.selectTask' ? `Select ${options?.task}` : key,+ }),+}));++afterEach(() => useTaskSelectionStore.getState().clear());++describe('SelectableTaskRow', () => {+ it('names each checkbox after its task for assistive technology', () => {+ render(+ <>+ <SelectableTaskRow id="t1" label="T-1 Fix login" order={() => ['t1', 't2']}>+ <div>row 1</div>+ </SelectableTaskRow>+ <SelectableTaskRow id="t2" label="T-2 Ship docs" order={() => ['t1', 't2']}>+ <div>row 2</div>+ </SelectableTaskRow>+ </>,+ );++ expect(screen.getByRole('checkbox', { name: 'Select T-1 Fix login' })).toBeTruthy();+ expect(screen.getByRole('checkbox', { name: 'Select T-2 Ship docs' })).toBeTruthy();+ });+});diff --git a/src/features/AgentTasks/AgentTaskList/selection/SelectableTaskRow.tsx b/src/features/AgentTasks/AgentTaskList/selection/SelectableTaskRow.tsxnew file mode 100644index 00000000000..afc815ac6c0--- /dev/null+++ b/src/features/AgentTasks/AgentTaskList/selection/SelectableTaskRow.tsx@@ -0,0 +1,107 @@+'use client';++import { Checkbox } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import type { MouseEvent, ReactNode } from 'react';+import { memo, useCallback, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { useTaskSelectionStore } from './store';++const styles = stylex.create({+ check: {+ insetBlockStart: '50%',+ insetInlineStart: 6,+ opacity: 0,+ position: 'absolute',+ transform: 'translateY(-50%)',+ transition: 'opacity 0.12s',+ zIndex: 1,+ },+ checkVisible: {+ opacity: 1,+ },+ row: {+ borderRadius: cssVar.borderRadius,+ // Gutter for the checkbox, so it never sits on the priority icon or gets+ // clipped by the panel edge.+ paddingInlineStart: 20,+ position: 'relative',+ },+ selected: {+ backgroundColor: cssVar.colorPrimaryBg,+ },+});++interface SelectableTaskRowProps {+ children: ReactNode;+ id: string;+ /** Names the row's checkbox for assistive technology, e.g. "T-12 Fix login". */+ label: string;+ /** Selectable ids of the list, top to bottom — the Shift+click range. */+ order: () => readonly string[];+}++/**+ * Selection chrome around a task row: a checkbox in the gutter (on hover, or+ * always once anything is selected), ⌘/Ctrl+click to toggle and Shift+click to+ * select a range. A plain click keeps opening the task.+ */+const SelectableTaskRow = memo<SelectableTaskRowProps>(({ children, id, label, order }) => {+ const selected = useTaskSelectionStore((s) => s.selectedIds.includes(id));+ const selecting = useTaskSelectionStore((s) => s.selectedIds.length > 0);+ const frozen = useTaskSelectionStore((s) => !!s.progress);+ const { t } = useTranslation('chat');+ const [hovered, setHovered] = useState(false);++ const handleClickCapture = useCallback(+ (event: MouseEvent) => {+ const { selectRange, toggle } = useTaskSelectionStore.getState();+ if (event.shiftKey) selectRange(order(), id);+ else if (event.metaKey || event.ctrlKey) toggle(id);+ else return;+ event.preventDefault();+ event.stopPropagation();+ },+ [id, order],+ );++ const handleCheck = useCallback(+ (event: MouseEvent) => {+ event.stopPropagation();+ const { selectRange, toggle } = useTaskSelectionStore.getState();+ if (event.shiftKey) selectRange(order(), id);+ else toggle(id);+ },+ [id, order],+ );++ return (+ <div+ {...stylex.props(styles.row, selected && styles.selected)}+ data-selected={selected || undefined}+ onClickCapture={handleClickCapture}+ onMouseEnter={() => setHovered(true)}+ onMouseLeave={() => setHovered(false)}+ >+ <div+ {...stylex.props(styles.check, (selecting || hovered) && styles.checkVisible)}+ data-testid={'task-row-checkbox'}+ onClickCapture={handleCheck}+ >+ <Checkbox+ aria-label={t('taskList.bulk.selectTask', { task: label })}+ checked={selected}+ disabled={frozen}+ size={16}+ />+ </div>+ {children}+ </div>+ );+});++SelectableTaskRow.displayName = 'SelectableTaskRow';++export default SelectableTaskRow;diff --git a/src/features/AgentTasks/AgentTaskList/selection/TaskBulkActionBar.tsx b/src/features/AgentTasks/AgentTaskList/selection/TaskBulkActionBar.tsxnew file mode 100644index 00000000000..e1bd6744062--- /dev/null+++ b/src/features/AgentTasks/AgentTaskList/selection/TaskBulkActionBar.tsx@@ -0,0 +1,110 @@+'use client';++import { ActionIcon, Button, Flexbox, Text } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import { CommandIcon, X } from 'lucide-react';+import { memo, useEffect } from 'react';+import { useTranslation } from 'react-i18next';++import type { TaskListItem } from '@/store/task/slices/list/initialState';++import { useTaskSelectionStore } from './store';+import TaskBulkActionsPanel from './TaskBulkActionsPanel';++const styles = stylex.create({+ bar: {+ backgroundColor: cssVar.colorBgElevated,+ borderColor: cssVar.colorBorderSecondary,+ borderRadius: 999,+ borderStyle: 'solid',+ borderWidth: 1,+ boxShadow: cssVar.boxShadowSecondary,+ paddingBlock: 6,+ paddingInlineEnd: 8,+ paddingInlineStart: 16,+ pointerEvents: 'auto',+ },+ overlay: {+ display: 'flex',+ insetBlockEnd: 24,+ insetInline: 0,+ justifyContent: 'center',+ pointerEvents: 'none',+ position: 'fixed',+ zIndex: 1000,+ },+});++interface TaskBulkActionBarProps {+ /** Every task of the list, to describe the selection (archived, running, …). */+ tasks: TaskListItem[];+}++/**+ * "N selected · ⌘ Actions · ✕" — floats over the list while rows are+ * selected. ⌘/Ctrl+K opens the actions panel instead of the global command+ * menu for as long as there is a selection.+ */+const TaskBulkActionBar = memo<TaskBulkActionBarProps>(({ tasks }) => {+ const { t } = useTranslation('chat');+ const count = useTaskSelectionStore((s) => s.selectedIds.length);+ const panelOpen = useTaskSelectionStore((s) => s.panelOpen);+ const setPanelOpen = useTaskSelectionStore((s) => s.setPanelOpen);+ const clear = useTaskSelectionStore((s) => s.clear);+ const progress = useTaskSelectionStore((s) => s.progress);++ useEffect(() => {+ if (count === 0) return;+ const onKeyDown = (event: KeyboardEvent) => {+ if (event.key.toLowerCase() !== 'k' || !(event.metaKey || event.ctrlKey)) return;+ if (event.shiftKey || event.altKey) return;+ // Capture phase on window runs before the document-level hotkey that+ // opens the global command menu.+ event.preventDefault();+ event.stopImmediatePropagation();+ setPanelOpen(!useTaskSelectionStore.getState().panelOpen);+ };+ window.addEventListener('keydown', onKeyDown, true);+ return () => window.removeEventListener('keydown', onKeyDown, true);+ }, [count, setPanelOpen]);++ if (count === 0) return null;++ return (+ <>+ <div {...stylex.props(styles.overlay)}>+ <Flexbox horizontal align={'center'} gap={8} {...stylex.props(styles.bar)}>+ <Text style={{ marginInlineEnd: 4, whiteSpace: 'nowrap' }} weight={500}>+ {progress+ ? t('taskList.bulk.progress', { done: progress.done, total: progress.total })+ : t('taskList.bulk.selected', { count })}+ </Text>+ <Button+ data-testid={'task-bulk-actions'}+ disabled={!!progress}+ icon={CommandIcon}+ loading={!!progress}+ shape={'round'}+ size={'small'}+ onClick={() => setPanelOpen(true)}+ >+ {t('taskList.bulk.actions')}+ </Button>+ <ActionIcon+ disabled={!!progress}+ icon={X}+ size={'small'}+ title={t('taskList.bulk.clear')}+ onClick={clear}+ />+ </Flexbox>+ </div>+ {panelOpen && <TaskBulkActionsPanel tasks={tasks} onClose={() => setPanelOpen(false)} />}+ </>+ );+});++TaskBulkActionBar.displayName = 'TaskBulkActionBar';++export default TaskBulkActionBar;diff --git a/src/features/AgentTasks/AgentTaskList/selection/TaskBulkActionsPanel.tsx b/src/features/AgentTasks/AgentTaskList/selection/TaskBulkActionsPanel.tsxnew file mode 100644index 00000000000..3851a8d8fed--- /dev/null+++ b/src/features/AgentTasks/AgentTaskList/selection/TaskBulkActionsPanel.tsx@@ -0,0 +1,359 @@+'use client';++import { agentDisplayName, isTaskArchiveBlocked } from '@lobechat/types';+import {+ confirmModal,+ copyToClipboard,+ cssVar,+ Icon,+ stopPropagation,+ Tag,+ toast,+} from '@lobehub/ui';+import { Command } from 'cmdk';+import {+ ArchiveIcon,+ ArchiveRestoreIcon,+ ArrowLeft,+ BarChart3Icon,+ BotIcon,+ CircleDashedIcon,+ CopyIcon,+ Trash2Icon,+ UserRoundCheckIcon,+ UserRoundXIcon,+} from 'lucide-react';+import type { ReactNode } from 'react';+import { memo, useMemo, useState } from 'react';+import { createPortal } from 'react-dom';+import { useTranslation } from 'react-i18next';++import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';+import AgentAvatar from '@/components/AgentAvatar';+import { styles } from '@/features/CommandMenu/styles';+import { useFetchAgentList } from '@/hooks/useFetchAgentList';+import { usePermission } from '@/hooks/usePermission';+import { useHomeStore } from '@/store/home';+import { homeAgentListSelectors } from '@/store/home/selectors';+import type { TaskListItem } from '@/store/task/slices/list/initialState';+import { useUserStore } from '@/store/user';+import { userProfileSelectors } from '@/store/user/selectors';++import { PRIORITY_META } from '../../features/TaskPriorityTag';+import { STATUS_META } from '../../features/taskStatusMeta';+import { hasWorkspaceMemberDirectory } from '../../shared/memberAssigneeMode';+import { useTaskSelectionStore } from './store';+import { type TaskBatchStatus, useTaskBatchActions } from './useTaskBatchActions';++const BATCH_STATUSES: TaskBatchStatus[] = ['backlog', 'paused', 'completed', 'canceled'];+const PRIORITY_LEVELS = [0, 1, 2, 3, 4];++type Page = 'agent' | 'priority' | 'status';++interface TaskBulkActionsPanelProps {+ onClose: () => void;+ tasks: TaskListItem[];+}++const Item = ({+ danger,+ disabled,+ icon,+ label,+ onSelect,+ value,+}: {+ danger?: boolean;+ disabled?: boolean;+ icon: ReactNode;+ label: string;+ onSelect: () => void;+ value: string;+}) => (+ <Command.Item disabled={disabled} value={value} onSelect={onSelect}>+ {icon}+ <div className={styles.itemContent}>+ <div className={styles.itemLabel} style={danger ? { color: cssVar.colorError } : undefined}>+ {label}+ </div>+ </div>+ </Command.Item>+);++/**+ * cmdk panel of the actions that apply to every selected task. Each action is+ * one batch request for the whole selection (see `useTaskBatchActions`).+ */+const TaskBulkActionsPanel = memo<TaskBulkActionsPanelProps>(({ onClose, tasks }) => {+ const { t } = useTranslation('chat');+ const selectedIds = useTaskSelectionStore((s) => s.selectedIds);+ const { run, running } = useTaskBatchActions();+ const { allowed: canEdit } = usePermission('create_content');+ const activeWorkspaceId = useActiveWorkspaceId();+ const userId = useUserStore(userProfileSelectors.userId);+ const [page, setPage] = useState<Page>();+ const [search, setSearch] = useState('');++ useFetchAgentList();+ const allAgents = useHomeStore(homeAgentListSelectors.allAgents);+ const agents = useMemo(() => {+ const seen = new Set<string>();+ return allAgents.filter((item) => {+ if (item.type !== 'agent' || seen.has(item.id)) return false;+ seen.add(item.id);+ return true;+ });+ }, [allAgents]);++ const selectedTasks = useMemo(() => {+ const ids = new Set(selectedIds);+ return tasks.filter((task) => ids.has(task.id));+ }, [selectedIds, tasks]);+ const allArchived = selectedTasks.length > 0 && selectedTasks.every((task) => task.archivedAt);+ const anyArchivable = selectedTasks.some(+ (task) => !task.archivedAt && !isTaskArchiveBlocked(task),+ );++ const disabled = !canEdit || running;+ const goTo = (next?: Page) => {+ setPage(next);+ setSearch('');+ };+ const act = (action: Parameters<typeof run>[0]) => {+ onClose();+ void run(action);+ };++ const confirmDelete = () => {+ onClose();+ confirmModal({+ content: t('taskList.bulk.deleteConfirm.content', { count: selectedIds.length }),+ okButtonProps: { danger: true },+ okText: t('taskList.bulk.deleteConfirm.ok'),+ onOk: () => run({ kind: 'delete' }),+ title: t('taskList.bulk.deleteConfirm.title', { count: selectedIds.length }),+ });+ };++ const copyIds = async () => {+ const identifiers = selectedTasks.map((task) => task.identifier).join('\n');+ await copyToClipboard(identifiers);+ toast.success(t('taskList.bulk.copied', { count: selectedTasks.length }));+ onClose();+ };++ const statusLabel = (status: TaskBatchStatus) =>+ t(`taskDetail.status.${status}` as never, { defaultValue: STATUS_META[status].label });+ const priorityLabel = (level: number) =>+ t(`taskDetail.${PRIORITY_META[level].labelKey}` as never, {+ defaultValue: PRIORITY_META[level].label,+ });++ const placeholder = page+ ? t(`taskList.bulk.search.${page}`)+ : t('taskList.bulk.search.placeholder');++ const panel = (+ <div className={styles.overlay} onClick={onClose}>+ <div onClick={stopPropagation}>+ <Command+ className={styles.commandRoot}+ data-testid={'task-bulk-actions-panel'}+ onKeyDown={(event) => {+ if (event.key === 'Escape') {+ event.preventDefault();+ event.stopPropagation();+ if (page) goTo(undefined);+ else onClose();+ }+ if (event.key === 'Backspace' && !search && page) {+ event.preventDefault();+ goTo(undefined);+ }+ }}+ >+ <div className={styles.contextWrapper}>+ {page && (+ <Tag+ className={styles.backTag}+ icon={<ArrowLeft size={12} />}+ onClick={() => goTo()}+ />+ )}+ <Tag className={styles.contextTag}>+ {t('taskList.bulk.count', { count: selectedIds.length })}+ </Tag>+ </div>+ <div className={styles.inputWrapper}>+ <Command.Input+ autoFocus+ placeholder={placeholder}+ value={search}+ onValueChange={setSearch}+ />+ </div>+ <Command.List>+ <Command.Empty>{t('taskList.bulk.noResults')}</Command.Empty>++ {!page && (+ <Command.Group>+ <Item+ disabled={disabled}+ icon={<Icon className={styles.icon} icon={CircleDashedIcon} />}+ label={t('taskList.bulk.changeStatus')}+ value={'change status'}+ onSelect={() => goTo('status')}+ />+ <Item+ disabled={disabled}+ icon={<Icon className={styles.icon} icon={BarChart3Icon} />}+ label={t('taskList.bulk.setPriority')}+ value={'set priority'}+ onSelect={() => goTo('priority')}+ />+ <Item+ disabled={disabled}+ icon={<Icon className={styles.icon} icon={BotIcon} />}+ label={t('taskList.bulk.assignAgent')}+ value={'assign agent'}+ onSelect={() => goTo('agent')}+ />+ {hasWorkspaceMemberDirectory(activeWorkspaceId) && userId && (+ <>+ <Item+ disabled={disabled}+ icon={<Icon className={styles.icon} icon={UserRoundCheckIcon} />}+ label={t('taskList.bulk.assignToMe')}+ value={'assign to me'}+ onSelect={() => act({ kind: 'update', patch: { assigneeUserId: userId } })}+ />+ <Item+ disabled={disabled}+ icon={<Icon className={styles.icon} icon={UserRoundXIcon} />}+ label={t('taskList.bulk.unassignMember')}+ value={'unassign member'}+ onSelect={() => act({ kind: 'update', patch: { assigneeUserId: null } })}+ />+ </>+ )}+ {allArchived ? (+ <Item+ disabled={disabled}+ icon={<Icon className={styles.icon} icon={ArchiveRestoreIcon} />}+ label={t('taskList.bulk.unarchive')}+ value={'unarchive restore'}+ onSelect={() => act({ archived: false, kind: 'archive' })}+ />+ ) : (+ <Item+ disabled={disabled || !anyArchivable}+ icon={<Icon className={styles.icon} icon={ArchiveIcon} />}+ label={t('taskList.bulk.archive')}+ value={'archive'}+ onSelect={() => act({ archived: true, kind: 'archive' })}+ />+ )}+ <Item+ icon={<Icon className={styles.icon} icon={CopyIcon} />}+ label={t('taskList.bulk.copyIds')}+ value={'copy ids identifiers'}+ onSelect={copyIds}+ />+ <Item+ danger+ disabled={disabled}+ label={t('taskList.bulk.delete')}+ value={'delete remove'}+ icon={+ <Icon className={styles.icon} color={cssVar.colorError} icon={Trash2Icon} />+ }+ onSelect={confirmDelete}+ />+ </Command.Group>+ )}++ {page === 'status' && (+ <Command.Group>+ {BATCH_STATUSES.map((status) => {+ const meta = STATUS_META[status];+ return (+ <Item+ disabled={disabled}+ icon={<Icon className={styles.icon} color={meta.color} icon={meta.icon} />}+ key={status}+ label={statusLabel(status)}+ value={`status ${status} ${statusLabel(status)}`}+ onSelect={() => act({ kind: 'status', status })}+ />+ );+ })}+ </Command.Group>+ )}++ {page === 'priority' && (+ <Command.Group>+ {PRIORITY_LEVELS.map((level) => {+ const PriorityIcon = PRIORITY_META[level].icon;+ return (+ <Item+ disabled={disabled}+ key={level}+ label={priorityLabel(level)}+ value={`priority ${level} ${priorityLabel(level)}`}+ icon={+ <PriorityIcon+ color={level === 1 ? cssVar.orange : cssVar.colorTextSecondary}+ size={16}+ />+ }+ onSelect={() => act({ kind: 'update', patch: { priority: level } })}+ />+ );+ })}+ </Command.Group>+ )}++ {page === 'agent' && (+ <Command.Group>+ <Item+ disabled={disabled}+ icon={<Icon className={styles.icon} icon={UserRoundXIcon} />}+ label={t('taskList.bulk.unassignAgent')}+ value={'unassigned none'}+ onSelect={() => act({ kind: 'update', patch: { assigneeAgentId: null } })}+ />+ {agents.map((agent) => {+ const name = agentDisplayName(agent) ?? agent.id;+ return (+ <Item+ disabled={disabled}+ key={agent.id}+ label={name}+ value={`agent ${agent.id} ${name}`}+ icon={+ <AgentAvatar+ agentId={agent.id}+ avatar={typeof agent.avatar === 'string' ? agent.avatar : undefined}+ name={name}+ shape={'square'}+ size={20}+ />+ }+ onSelect={() => act({ kind: 'update', patch: { assigneeAgentId: agent.id } })}+ />+ );+ })}+ </Command.Group>+ )}+ </Command.List>+ </Command>+ </div>+ </div>+ );++ return createPortal(panel, document.body);+});++TaskBulkActionsPanel.displayName = 'TaskBulkActionsPanel';++export default TaskBulkActionsPanel;diff --git a/src/features/AgentTasks/AgentTaskList/selection/store.test.ts b/src/features/AgentTasks/AgentTaskList/selection/store.test.tsnew file mode 100644index 00000000000..97344f94574--- /dev/null+++ b/src/features/AgentTasks/AgentTaskList/selection/store.test.ts@@ -0,0 +1,41 @@+import { afterEach, describe, expect, it } from 'vitest';++import { useTaskSelectionStore } from './store';++afterEach(() => {+ useTaskSelectionStore.getState().clear();+ useTaskSelectionStore.setState({ progress: undefined });+});++describe('useTaskSelectionStore', () => {+ it('bumps the generation on every clear so a late batch can tell its scope is gone', () => {+ const store = useTaskSelectionStore.getState();+ store.selectAll(['a', 'b']);+ const before = useTaskSelectionStore.getState().generation;++ store.clear();++ const after = useTaskSelectionStore.getState();+ expect(after.selectedIds).toEqual([]);+ expect(after.generation).toBe(before + 1);+ });++ it('keeps the generation while the selection only changes within the list', () => {+ const store = useTaskSelectionStore.getState();+ const before = store.generation;+ store.toggle('a');+ store.selectRange(['a', 'b', 'c'], 'c');+ store.prune(new Set(['a', 'b']));++ const state = useTaskSelectionStore.getState();+ expect(state.selectedIds).toEqual(['a', 'b']);+ expect(state.generation).toBe(before);+ });++ it('does not open the panel while a batch is running', () => {+ const store = useTaskSelectionStore.getState();+ store.setProgress({ done: 0, total: 3 });+ store.setPanelOpen(true);+ expect(useTaskSelectionStore.getState().panelOpen).toBe(false);+ });+});diff --git a/src/features/AgentTasks/AgentTaskList/selection/store.ts b/src/features/AgentTasks/AgentTaskList/selection/store.tsnew file mode 100644index 00000000000..34295d061af--- /dev/null+++ b/src/features/AgentTasks/AgentTaskList/selection/store.ts@@ -0,0 +1,85 @@+import { create } from 'zustand';++import { pruneSelection, selectRange, toggleSelection } from './taskSelectionModel';++interface TaskSelectionState {+ /** Last row clicked without Shift — where the next Shift+click range starts. */+ anchorId?: string;+ /**+ * Bumped by every `clear()` — leaving the list, switching collection, Esc.+ * A batch that finishes after its selection was cleared must not write that+ * selection back into whatever list is on screen now.+ */+ generation: number;+ panelOpen: boolean;+ /** A batch is in flight: `done` of `total` tasks sent so far. */+ progress?: { done: number; total: number };+ selectedIds: readonly string[];+ /**+ * Selectable rows of the list on screen, as last reported by `prune`. A batch+ * only ever writes ids from this set back into the selection, so ids from a+ * list or page that is no longer shown can never become invisibly selected.+ */+ visibleIds: ReadonlySet<string>;+}++interface TaskSelectionActions {+ clear: () => void;+ prune: (visibleIds: ReadonlySet<string>) => void;+ selectAll: (order: readonly string[]) => void;+ selectRange: (order: readonly string[], id: string) => void;+ setPanelOpen: (open: boolean) => void;+ setProgress: (progress?: { done: number; total: number }) => void;+ toggle: (id: string) => void;+}++const EMPTY: readonly string[] = [];+const EMPTY_SET: ReadonlySet<string> = new Set();++/**+ * Multi-select of the task list. One list is on screen at a time, so a single+ * store is enough; `TaskList` clears it when it unmounts or its collection+ * changes.+ */+export const useTaskSelectionStore = create<TaskSelectionState & TaskSelectionActions>((set) => ({+ anchorId: undefined,+ clear: () =>+ set((state) => ({+ anchorId: undefined,+ generation: state.generation + 1,+ panelOpen: false,+ // A batch still in flight belongs to the selection being dropped: the+ // list that comes next must not show its progress or stay frozen by it.+ progress: undefined,+ selectedIds: EMPTY,+ })),+ generation: 0,+ panelOpen: false,+ prune: (visibleIds) =>+ set((state) => {+ const selectedIds = pruneSelection(state.selectedIds, visibleIds);+ if (selectedIds === state.selectedIds) return { visibleIds };+ return { panelOpen: state.panelOpen && selectedIds.length > 0, selectedIds, visibleIds };+ }),+ // While a batch runs the selection is frozen: the batch acts on the ids it+ // snapshotted and writes the outcome back when it ends, so a change made in+ // between would be silently overwritten.+ selectAll: (order) =>+ set((state) => (state.progress ? state : { anchorId: order[0], selectedIds: [...order] })),+ selectRange: (order, id) =>+ set((state) =>+ state.progress+ ? state+ : { selectedIds: selectRange(order, state.selectedIds, state.anchorId, id) },+ ),+ selectedIds: EMPTY,+ setPanelOpen: (panelOpen) => set((state) => ({ panelOpen: panelOpen && !state.progress })),+ setProgress: (progress) => set({ panelOpen: false, progress }),+ toggle: (id) =>+ set((state) =>+ state.progress+ ? state+ : { anchorId: id, selectedIds: toggleSelection(state.selectedIds, id) },+ ),+ visibleIds: EMPTY_SET,+}));diff --git a/src/features/AgentTasks/AgentTaskList/selection/taskSelectionModel.test.ts b/src/features/AgentTasks/AgentTaskList/selection/taskSelectionModel.test.tsnew file mode 100644index 00000000000..549534e61ec--- /dev/null+++ b/src/features/AgentTasks/AgentTaskList/selection/taskSelectionModel.test.ts@@ -0,0 +1,67 @@+import { describe, expect, it } from 'vitest';++import {+ chunkIds,+ isEditableTarget,+ mergeOutcomes,+ pruneSelection,+ selectRange,+ toggleSelection,+} from './taskSelectionModel';++const order = ['a', 'b', 'c', 'd', 'e'];++describe('taskSelectionModel', () => {+ it('toggles an id in and out', () => {+ expect(toggleSelection([], 'a')).toEqual(['a']);+ expect(toggleSelection(['a', 'b'], 'a')).toEqual(['b']);+ });++ it('selects the visible range between the anchor and the clicked row, either direction', () => {+ expect(selectRange(order, [], 'b', 'd')).toEqual(['b', 'c', 'd']);+ expect(selectRange(order, ['a'], 'd', 'b')).toEqual(['a', 'b', 'c', 'd']);+ });++ it('falls back to selecting the clicked row without an anchor', () => {+ expect(selectRange(order, ['a'], undefined, 'c')).toEqual(['a', 'c']);+ expect(selectRange(order, ['a'], 'gone', 'c')).toEqual(['a', 'c']);+ expect(selectRange(order, ['a'], 'a', 'not-in-list')).toEqual(['a']);+ });++ it('prunes ids that left the list and keeps identity when nothing changed', () => {+ const selected = ['a', 'b'];+ expect(pruneSelection(selected, new Set(order))).toBe(selected);+ expect(pruneSelection(['a', 'x'], new Set(order))).toEqual(['a']);+ });++ it('chunks a large selection into request-sized batches', () => {+ const ids = Array.from({ length: 1001 }, (_, i) => `t${i}`);+ expect(chunkIds(ids).map((chunk) => chunk.length)).toEqual([500, 500, 1]);+ expect(chunkIds([])).toEqual([]);+ });++ it('merges per-chunk outcomes', () => {+ expect(+ mergeOutcomes([+ { failed: [], skipped: [{ id: 'b', reason: 'running' }], updated: ['a'] },+ { failed: [{ error: 'x', id: 'd' }], skipped: [], updated: ['c'] },+ ]),+ ).toEqual({+ failed: [{ error: 'x', id: 'd' }],+ followUpFailed: false,+ skipped: [{ id: 'b', reason: 'running' }],+ updated: ['a', 'c'],+ });+ });++ it('treats text fields as editable targets', () => {+ const input = document.createElement('input');+ const div = document.createElement('div');+ const editable = document.createElement('div');+ editable.contentEditable = 'true';+ document.body.append(input, div, editable);+ expect(isEditableTarget(input)).toBe(true);+ expect(isEditableTarget(div)).toBe(false);+ expect(isEditableTarget(null)).toBe(false);+ });+});diff --git a/src/features/AgentTasks/AgentTaskList/selection/taskSelectionModel.ts b/src/features/AgentTasks/AgentTaskList/selection/taskSelectionModel.tsnew file mode 100644index 00000000000..a766ff599e2--- /dev/null+++ b/src/features/AgentTasks/AgentTaskList/selection/taskSelectionModel.ts@@ -0,0 +1,72 @@+/**+ * Pure selection math for the task list's multi-select. `order` is the list's+ * selectable rows top to bottom, so ranges follow what the user sees.+ */++/** Ids one batch request may carry; mirrors the server's `TASK_BATCH_MAX_IDS`. */+export const TASK_BATCH_CHUNK_SIZE = 500;++export const toggleSelection = (selected: readonly string[], id: string): string[] =>+ selected.includes(id) ? selected.filter((item) => item !== id) : [...selected, id];++/**+ * Shift+click: add every row between the anchor and `id` (inclusive) to the+ * selection. Without a usable anchor it behaves like a toggle-on of `id`.+ */+export const selectRange = (+ order: readonly string[],+ selected: readonly string[],+ anchorId: string | undefined,+ id: string,+): string[] => {+ const to = order.indexOf(id);+ const from = anchorId ? order.indexOf(anchorId) : -1;+ if (to < 0) return [...selected];+ if (from < 0) return selected.includes(id) ? [...selected] : [...selected, id];++ const [start, end] = from <= to ? [from, to] : [to, from];+ const next = new Set(selected);+ for (const rowId of order.slice(start, end + 1)) next.add(rowId);+ return [...next];+};++/**+ * Drop ids that left the list (deleted, filtered out, moved to another view)+ * so the count and the batch never act on rows the user can no longer see.+ * Returns the same array when nothing changed, to keep store updates cheap.+ */+export const pruneSelection = (+ selected: readonly string[],+ visibleIds: ReadonlySet<string>,+): readonly string[] => {+ const next = selected.filter((id) => visibleIds.has(id));+ return next.length === selected.length ? selected : next;+};++export const chunkIds = (ids: readonly string[], size = TASK_BATCH_CHUNK_SIZE): string[][] => {+ const chunks: string[][] = [];+ for (let i = 0; i < ids.length; i += size) chunks.push(ids.slice(i, i + size));+ return chunks;+};++export interface TaskBatchOutcome {+ failed: { error: string; id: string }[];+ followUpFailed?: boolean;+ skipped: { id: string; reason: string }[];+ updated: string[];+}++export const mergeOutcomes = (outcomes: readonly TaskBatchOutcome[]): TaskBatchOutcome => ({+ failed: outcomes.flatMap((outcome) => outcome.failed),+ followUpFailed: outcomes.some((outcome) => outcome.followUpFailed),+ skipped: outcomes.flatMap((outcome) => outcome.skipped),+ updated: outcomes.flatMap((outcome) => outcome.updated),+});++/** Keyboard focus is in a text field: native shortcuts (⌘A, Esc) belong to it. */+export const isEditableTarget = (target: EventTarget | null): boolean => {+ if (!target || typeof (target as HTMLElement).closest !== 'function') return false;+ const element = target as HTMLElement;+ if (element.isContentEditable) return true;+ return !!element.closest('input, textarea, select, [contenteditable="true"], [role="textbox"]');+};diff --git a/src/features/AgentTasks/AgentTaskList/selection/useSelectionScope.test.ts b/src/features/AgentTasks/AgentTaskList/selection/useSelectionScope.test.tsnew file mode 100644index 00000000000..4829320c00a--- /dev/null+++ b/src/features/AgentTasks/AgentTaskList/selection/useSelectionScope.test.ts@@ -0,0 +1,40 @@+import { renderHook } from '@testing-library/react';+import { afterEach, describe, expect, it } from 'vitest';++import { useTaskSelectionStore } from './store';+import { useSelectionScope } from './useSelectionScope';++afterEach(() => useTaskSelectionStore.getState().clear());++describe('useSelectionScope', () => {+ it('keeps the selection while the scope is unchanged', () => {+ const { rerender } = renderHook(({ scope }) => useSelectionScope(scope), {+ initialProps: { scope: 'mine:assigned:1' },+ });+ useTaskSelectionStore.getState().selectAll(['shared-task']);++ rerender({ scope: 'mine:assigned:1' });++ expect(useTaskSelectionStore.getState().selectedIds).toEqual(['shared-task']);+ });++ it('drops a selection shared by two collections when switching between them', () => {+ const { rerender } = renderHook(({ scope }) => useSelectionScope(scope), {+ initialProps: { scope: 'mine:assigned:1' },+ });+ useTaskSelectionStore.getState().prune(new Set(['shared-task']));+ useTaskSelectionStore.getState().selectAll(['shared-task']);++ // "My created" also contains the task, so a prune alone would keep it.+ rerender({ scope: 'mine:created:1' });++ expect(useTaskSelectionStore.getState().selectedIds).toEqual([]);+ });++ it('clears on unmount', () => {+ const { unmount } = renderHook(() => useSelectionScope('scheduled::1'));+ useTaskSelectionStore.getState().selectAll(['a']);+ unmount();+ expect(useTaskSelectionStore.getState().selectedIds).toEqual([]);+ });+});diff --git a/src/features/AgentTasks/AgentTaskList/selection/useSelectionScope.ts b/src/features/AgentTasks/AgentTaskList/selection/useSelectionScope.tsnew file mode 100644index 00000000000..2cab9b5bf07--- /dev/null+++ b/src/features/AgentTasks/AgentTaskList/selection/useSelectionScope.ts@@ -0,0 +1,12 @@+import { useEffect } from 'react';++import { useTaskSelectionStore } from './store';++/**+ * Drop the selection when the list behind it changes identity (another tab,+ * sub-scope, page or owner) and when the list unmounts. Rows present in both+ * collections would otherwise stay selected across the switch.+ */+export const useSelectionScope = (scope: string) => {+ useEffect(() => () => useTaskSelectionStore.getState().clear(), [scope]);+};diff --git a/src/features/AgentTasks/AgentTaskList/selection/useTaskBatchActions.test.ts b/src/features/AgentTasks/AgentTaskList/selection/useTaskBatchActions.test.tsnew file mode 100644index 00000000000..1d6231fae55--- /dev/null+++ b/src/features/AgentTasks/AgentTaskList/selection/useTaskBatchActions.test.ts@@ -0,0 +1,168 @@+import { act, renderHook } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { useTaskSelectionStore } from './store';+import { useTaskBatchActions } from './useTaskBatchActions';++const batchUpdate = vi.fn();+const refreshTaskList = vi.fn(async () => {});+const toastWarning = vi.fn();++vi.mock('@/services/task', () => ({+ taskService: { batchUpdate: (...args: unknown[]) => batchUpdate(...args) },+}));+vi.mock('@/store/task', () => ({+ useTaskStore: (selector: (s: { refreshTaskList: () => Promise<void> }) => unknown) =>+ selector({ refreshTaskList }),+}));+vi.mock('@lobehub/ui', () => ({+ toast: {+ error: vi.fn(),+ success: vi.fn(),+ warning: (...args: unknown[]) => toastWarning(...args),+ },+}));+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));++const partialFailure = { failed: [{ error: 'boom', id: 'b' }], skipped: [], updated: ['a'] };++beforeEach(() => {+ batchUpdate.mockReset();+ refreshTaskList.mockReset();+ refreshTaskList.mockResolvedValue(undefined);+ toastWarning.mockReset();+ useTaskSelectionStore.getState().clear();+ useTaskSelectionStore.setState({ progress: undefined });+});++afterEach(() => {+ useTaskSelectionStore.getState().clear();+});++describe('useTaskBatchActions', () => {+ it('keeps the failed tasks selected for a retry', async () => {+ batchUpdate.mockResolvedValue(partialFailure);+ useTaskSelectionStore.getState().prune(new Set(['a', 'b', 'c']));+ useTaskSelectionStore.getState().selectAll(['a', 'b']);+ const { result } = renderHook(() => useTaskBatchActions());++ await act(() => result.current.run({ kind: 'update', patch: { priority: 1 } }));++ expect(useTaskSelectionStore.getState().selectedIds).toEqual(['b']);+ expect(useTaskSelectionStore.getState().progress).toBeUndefined();+ });++ it('does not restore a selection whose list was left while the batch ran', async () => {+ let resolve!: (value: typeof partialFailure) => void;+ batchUpdate.mockReturnValue(new Promise((r) => (resolve = r)));+ useTaskSelectionStore.getState().selectAll(['a', 'b']);+ const { result } = renderHook(() => useTaskBatchActions());++ let pending!: Promise<void>;+ act(() => {+ pending = result.current.run({ kind: 'update', patch: { priority: 1 } });+ });+ // The user moves to another collection: TaskList's cleanup clears the store,+ // and the new list selects its own row.+ act(() => {+ useTaskSelectionStore.getState().clear();+ useTaskSelectionStore.getState().toggle('other-list-task');+ });+ // The new list is neither frozen nor showing the old batch's progress.+ expect(useTaskSelectionStore.getState().progress).toBeUndefined();+ await act(async () => {+ resolve(partialFailure);+ await pending;+ });++ expect(useTaskSelectionStore.getState().selectedIds).toEqual(['other-list-task']);+ });++ it('does not bring back ids of a page or scope the reused list no longer shows', async () => {+ let resolve!: (value: typeof partialFailure) => void;+ batchUpdate.mockReturnValue(new Promise((r) => (resolve = r)));+ useTaskSelectionStore.getState().prune(new Set(['a', 'b']));+ useTaskSelectionStore.getState().selectAll(['a', 'b']);+ const { result } = renderHook(() => useTaskBatchActions());++ let pending!: Promise<void>;+ act(() => {+ pending = result.current.run({ kind: 'update', patch: { priority: 1 } });+ });+ // Same TaskList instance, next page: only the prune runs, no clear().+ act(() => useTaskSelectionStore.getState().prune(new Set(['x', 'y'])));+ await act(async () => {+ resolve(partialFailure);+ await pending;+ });++ expect(useTaskSelectionStore.getState().selectedIds).toEqual([]);+ });++ it('freezes the selection while the batch runs', async () => {+ let resolve!: (value: typeof partialFailure) => void;+ batchUpdate.mockReturnValue(new Promise((r) => (resolve = r)));+ useTaskSelectionStore.getState().prune(new Set(['a', 'b', 'c']));+ useTaskSelectionStore.getState().selectAll(['a', 'b']);+ const { result } = renderHook(() => useTaskBatchActions());++ let pending!: Promise<void>;+ act(() => {+ pending = result.current.run({ kind: 'update', patch: { priority: 1 } });+ });+ act(() => {+ const store = useTaskSelectionStore.getState();+ store.toggle('c');+ store.selectAll(['a', 'b', 'c']);+ store.selectRange(['a', 'b', 'c'], 'c');+ });+ expect(useTaskSelectionStore.getState().selectedIds).toEqual(['a', 'b']);++ await act(async () => {+ resolve(partialFailure);+ await pending;+ });+ expect(useTaskSelectionStore.getState().selectedIds).toEqual(['b']);+ });++ it('reports a failed list refresh after a committed batch, with a retry', async () => {+ batchUpdate.mockResolvedValue({ failed: [], skipped: [], updated: ['a', 'b'] });+ refreshTaskList.mockRejectedValueOnce(new Error('network down'));+ vi.spyOn(console, 'error').mockImplementation(() => {});+ useTaskSelectionStore.getState().prune(new Set(['a', 'b']));+ useTaskSelectionStore.getState().selectAll(['a', 'b']);+ const { result } = renderHook(() => useTaskBatchActions());++ await act(() => result.current.run({ kind: 'update', patch: { priority: 1 } }));++ const refreshWarning = toastWarning.mock.calls.find(+ ([arg]) => typeof arg === 'object' && arg?.title === 'taskList.bulk.refreshFailed.title',+ );+ expect(refreshWarning).toBeDefined();+ // The batch itself was committed: its selection is done.+ expect(useTaskSelectionStore.getState().selectedIds).toEqual([]);++ refreshWarning![0].actions[0].onClick();+ expect(refreshTaskList).toHaveBeenCalledTimes(2);+ });++ it('warns when the completion follow-ups failed after the batch committed', async () => {+ batchUpdate.mockResolvedValue({+ failed: [],+ followUpFailed: true,+ skipped: [],+ updated: ['a'],+ });+ useTaskSelectionStore.getState().prune(new Set(['a']));+ useTaskSelectionStore.getState().selectAll(['a']);+ const { result } = renderHook(() => useTaskBatchActions());++ await act(() => result.current.run({ kind: 'update', patch: { priority: 1 } }));++ expect(+ toastWarning.mock.calls.some(+ ([arg]) => typeof arg === 'object' && arg?.title === 'taskList.bulk.followUpFailed.title',+ ),+ ).toBe(true);+ });+});diff --git a/src/features/AgentTasks/AgentTaskList/selection/useTaskBatchActions.ts b/src/features/AgentTasks/AgentTaskList/selection/useTaskBatchActions.tsnew file mode 100644index 00000000000..f2388f80df5--- /dev/null+++ b/src/features/AgentTasks/AgentTaskList/selection/useTaskBatchActions.ts@@ -0,0 +1,152 @@+import { toast } from '@lobehub/ui';+import { useCallback } from 'react';+import { useTranslation } from 'react-i18next';++import { taskService } from '@/services/task';+import { useTaskStore } from '@/store/task';++import { useTaskSelectionStore } from './store';+import { chunkIds, mergeOutcomes, type TaskBatchOutcome } from './taskSelectionModel';++export type TaskBatchStatus = 'backlog' | 'canceled' | 'completed' | 'paused';++export type TaskBatchAction =+ | { archived: boolean; kind: 'archive' }+ | { kind: 'delete' }+ | { kind: 'status'; status: TaskBatchStatus }+ | {+ kind: 'update';+ patch: { assigneeAgentId?: string | null; assigneeUserId?: string | null; priority?: number };+ };++const runChunk = (action: TaskBatchAction, ids: string[]): Promise<TaskBatchOutcome> => {+ switch (action.kind) {+ case 'archive': {+ return taskService.batchArchive(ids, action.archived);+ }+ case 'delete': {+ return taskService.batchDelete(ids);+ }+ case 'status': {+ return taskService.batchUpdateStatus(ids, action.status);+ }+ case 'update': {+ return taskService.batchUpdate({ ids, ...action.patch });+ }+ }+};++/**+ * Apply one action to the current selection: one request per 500 tasks (the+ * server's batch limit), then a single list refresh and a single summary+ * toast. Tasks that failed stay selected so the user can retry them.+ */+export const useTaskBatchActions = () => {+ const { t } = useTranslation('chat');+ const refreshTaskList = useTaskStore((s) => s.refreshTaskList);+ const running = useTaskSelectionStore((s) => !!s.progress);++ const run = useCallback(+ async (action: TaskBatchAction) => {+ const { generation, progress, selectedIds } = useTaskSelectionStore.getState();+ // Progress belongs to the selection this batch started from; once that+ // is cleared (list left, Esc) later updates must not reach the new list.+ const setProgress = (next?: { done: number; total: number }) => {+ const store = useTaskSelectionStore.getState();+ if (store.generation === generation) store.setProgress(next);+ };+ // One batch at a time: a second action must not race the first.+ if (progress) return;+ const ids = [...selectedIds];+ if (ids.length === 0) return;++ setProgress({ done: 0, total: ids.length });+ const outcomes: TaskBatchOutcome[] = [];+ let requestError: unknown;+ try {+ // Sequential: each chunk is already a set-based write on the server,+ // and ordering keeps a later chunk from racing an earlier one.+ let done = 0;+ for (const chunk of chunkIds(ids)) {+ outcomes.push(await runChunk(action, chunk));+ done += chunk.length;+ setProgress({ done, total: ids.length });+ }+ } catch (error) {+ requestError = error;+ }+ // The batch is committed whatever happens here; a failed refresh only+ // means the list on screen is stale, so say that (with a retry) instead+ // of hiding it behind the success toast.+ await refreshTaskList().catch((error: unknown) => {+ console.error('[task batch] list refresh failed after a committed batch', error);+ const retry = () => {+ void refreshTaskList().catch((retryError: unknown) => {+ console.error('[task batch] list refresh retry failed', retryError);+ });+ };+ toast.warning({+ actions: [{ label: t('taskList.bulk.refreshFailed.retry'), onClick: retry }],+ description: t('taskList.bulk.refreshFailed.desc'),+ title: t('taskList.bulk.refreshFailed.title'),+ });+ });+ setProgress(undefined);++ const { failed, followUpFailed, skipped, updated } = mergeOutcomes(outcomes);+ const unprocessed = ids.length - updated.length - skipped.length - failed.length;+ const failedCount = failed.length + Math.max(unprocessed, 0);++ if (requestError && updated.length === 0) {+ toast.error(+ requestError instanceof Error && requestError.message+ ? requestError.message+ : t('taskList.bulk.result.error'),+ );+ return;+ }++ const parts = [+ t(+ action.kind === 'delete'+ ? 'taskList.bulk.result.deleted'+ : 'taskList.bulk.result.updated',+ { count: updated.length },+ ),+ ];+ if (skipped.length > 0)+ parts.push(t('taskList.bulk.result.skipped', { count: skipped.length }));+ if (failedCount > 0) parts.push(t('taskList.bulk.result.failed', { count: failedCount }));+ if (followUpFailed) {+ toast.warning({+ description: t('taskList.bulk.followUpFailed.desc'),+ title: t('taskList.bulk.followUpFailed.title'),+ });+ }+ const message = parts.join(' · ');+ if (failedCount > 0) toast.warning(message);+ else toast.success(message);++ const selection = useTaskSelectionStore.getState();+ // The list this batch started from was left (or its selection cleared)+ // while the requests ran: its ids mean nothing to the list on screen now,+ // so neither restore them nor clear the new list's own selection.+ if (selection.generation !== generation) return;+ if (failedCount > 0) {+ // Keep exactly what still needs attention selected.+ // Only rows the list on screen still shows: after a page or scope change+ // the old ids are not visible, and must not come back selected.+ const done = new Set([...updated, ...skipped.map((item) => item.id)]);+ useTaskSelectionStore.setState({+ panelOpen: false,+ selectedIds: ids.filter((id) => !done.has(id) && selection.visibleIds.has(id)),+ });+ } else {+ selection.clear();+ }+ },+ [refreshTaskList, t],+ );++ return { run, running };+};diff --git a/src/services/task.ts b/src/services/task.tsindex 5db51057d45..cd1b18f1b38 100644--- a/src/services/task.ts+++ b/src/services/task.ts@@ -174,6 +174,27 @@ class TaskService {},) => lambdaClient.task.update.mutate({ id, ...data });+ // ── Batch (list multi-select) ──+ // One request per action for the whole selection; the server answers with a+ // per-task outcome (`updated` / `skipped` / `failed`).++ batchUpdate = async (params: {+ assigneeAgentId?: string | null;+ assigneeUserId?: string | null;+ ids: string[];+ priority?: number;+ }) => lambdaClient.task.batchUpdate.mutate(params);++ batchUpdateStatus = async (+ ids: string[],+ status: 'backlog' | 'canceled' | 'completed' | 'paused',+ ) => lambdaClient.task.batchUpdateStatus.mutate({ ids, status });++ batchArchive = async (ids: string[], archived: boolean) =>+ lambdaClient.task.batchArchive.mutate({ archived, ids });++ batchDelete = async (ids: string[]) => lambdaClient.task.batchDelete.mutate({ ids });+delete = async (id: string) => lambdaClient.task.delete.mutate({ id });archive = async (id: string, archived: boolean) =>