Skip to content

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

✨ feat(task): instant batch actions with undo, and a recycle bin for deleted tasks (#22167)

Rdmclin2cb4da65a821a
diff --git a/apps/server/src/routers/lambda/_helpers/taskListSchemas.ts b/apps/server/src/routers/lambda/_helpers/taskListSchemas.ts
index 30694a2cd2b..b61cb14779a 100644
--- a/apps/server/src/routers/lambda/_helpers/taskListSchemas.ts
+++ b/apps/server/src/routers/lambda/_helpers/taskListSchemas.ts
@@ -62,7 +62,9 @@ export const listSchema = z.object({
filter: taskListFilterSchema.optional(),
// Archived tasks are user-closed; lists leave them out unless asked.
includeArchived: z.boolean().optional(),
- limit: z.number().min(1).max(100).default(50),
+ // Up to 500: the Tasks list view walks the whole list page by page, and
+ // every page is a sequential round trip (refresh after each edit included).
+ limit: z.number().min(1).max(500).default(50),
offset: z.number().min(0).default(0),
// Which timestamp orders the page, newest first. Defaults to creation time.
orderBy: z.enum(['createdAt', 'updatedAt']).optional(),
@@ -93,7 +95,9 @@ export const groupListSchema = z
.array(
z.object({
key: z.string(),
- limit: z.number().min(1).max(100).default(50),
+ // Up to 500: the Tasks list view walks the whole list page by page, and
+ // every page is a sequential round trip (refresh after each edit included).
+ limit: z.number().min(1).max(500).default(50),
offset: z.number().min(0).default(0),
statuses: z.array(z.string()).min(1).max(10),
}),
diff --git a/apps/server/src/routers/lambda/task/batch.ts b/apps/server/src/routers/lambda/task/batch.ts
index 9952315d75e..6ff3fd2ade7 100644
--- a/apps/server/src/routers/lambda/task/batch.ts
+++ b/apps/server/src/routers/lambda/task/batch.ts
@@ -1,3 +1,4 @@
+import type { TaskItem } from '@lobechat/types';
import { TRPCError } from '@trpc/server';
import { z } from 'zod';
@@ -5,6 +6,7 @@ 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 { TaskBatchRevertService } from '@/server/services/task/batchRevert';
import { taskProcedureWrite } from './procedures';
@@ -18,6 +20,36 @@ const batchService = (ctx: {
workspaceId?: string | null;
}) => new TaskBatchService(ctx.serverDB, ctx.userId, ctx.workspaceId ?? undefined);
+/**
+ * The list-visible columns of each changed row, so the client can confirm its
+ * optimistic rows with server-computed values (`completedAt`, `updatedAt`)
+ * without waiting for a list refetch. Only these columns: a full row carries
+ * the instruction and config, which a 500-task batch has no reason to ship.
+ */
+const toChangedRow = (task: TaskItem) => ({
+ assigneeAgentId: task.assigneeAgentId,
+ assigneeUserId: task.assigneeUserId,
+ completedAt: task.completedAt,
+ id: task.id,
+ priority: task.priority,
+ status: task.status,
+ updatedAt: task.updatedAt,
+});
+
+const revertValues = z.object({
+ archived: z.boolean().optional(),
+ assigneeAgentId: z.string().nullish(),
+ assigneeUserId: z.string().nullish(),
+ priority: z.number().int().min(0).max(4).nullish(),
+ status: z.string().optional(),
+});
+
+const revertService = (ctx: {
+ serverDB: LobeChatDatabase;
+ userId: string;
+ workspaceId?: string | null;
+}) => new TaskBatchRevertService(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);
@@ -44,6 +76,42 @@ export const batchRouter = router({
batchService(ctx).delete(input.ids).catch(rethrow('batchDelete', 'Failed to delete tasks')),
),
+ /** Undo of a batch delete: bring the tasks back out of the recycle bin. */
+ batchRestoreDeleted: taskProcedureWrite
+ .input(idsInput)
+ .mutation(({ ctx, input }) =>
+ revertService(ctx)
+ .restoreDeleted(input.ids)
+ .catch(rethrow('batchRestoreDeleted', 'Failed to restore tasks')),
+ ),
+
+ /**
+ * Undo of a batch status / field / archive change: put back each task's
+ * `before`, only while it still holds `after` (a later edit wins — reported
+ * as `skipped: conflict`). Takes the `reverts` the forward call returned.
+ */
+ batchRevert: taskProcedureWrite
+ .input(
+ z.object({
+ reverts: z
+ .array(
+ z.object({
+ after: revertValues,
+ before: revertValues,
+ id: z.string().trim().min(1),
+ }),
+ )
+ .min(1)
+ .max(TASK_BATCH_MAX_IDS),
+ }),
+ )
+ .mutation(({ ctx, input }) =>
+ revertService(ctx)
+ // A person undid their own batch; recorded as their change.
+ .revert(input.reverts, { agentId: ctx.actingAgentId ?? null, userId: ctx.userId })
+ .catch(rethrow('batchRevert', 'Failed to undo the batch')),
+ ),
+
batchUpdate: taskProcedureWrite
.input(
idsInput.extend({
@@ -54,22 +122,22 @@ export const batchRouter = router({
)
.mutation(async ({ ctx, input }) => {
const { ids, ...patch } = input;
- const { result } = await batchService(ctx)
+ const { result, tasks } = 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;
+ return { ...result, tasks: tasks.map(toChangedRow) };
}),
batchUpdateStatus: taskProcedureWrite
.input(idsInput.extend({ status: z.enum(TASK_BATCH_STATUSES) }))
.mutation(async ({ ctx, input }) => {
- const { result } = await batchService(ctx)
+ const { result, tasks } = 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;
+ return { ...result, tasks: tasks.map(toChangedRow) };
}),
});
diff --git a/apps/server/src/routers/lambda/task/index.procedures.test.ts b/apps/server/src/routers/lambda/task/index.procedures.test.ts
index 7f8ec22b1af..522b8c0b340 100644
--- a/apps/server/src/routers/lambda/task/index.procedures.test.ts
+++ b/apps/server/src/routers/lambda/task/index.procedures.test.ts
@@ -32,6 +32,8 @@ function expected(): Array<
['archive', 'mutation', 13],
['batchArchive', 'mutation', 13],
['batchDelete', 'mutation', 13],
+ ['batchRestoreDeleted', 'mutation', 13],
+ ['batchRevert', 'mutation', 13],
['batchUpdate', 'mutation', 13],
['batchUpdateStatus', 'mutation', 13],
['cancelTopic', 'mutation', 13],
diff --git a/apps/server/src/services/editLock/__tests__/index.test.ts b/apps/server/src/services/editLock/__tests__/index.test.ts
index 193bf377f13..38bfd3f0234 100644
--- a/apps/server/src/services/editLock/__tests__/index.test.ts
+++ b/apps/server/src/services/editLock/__tests__/index.test.ts
@@ -28,6 +28,7 @@ const makeFakeRedis = () => {
},
),
get: vi.fn(async (key: string) => store.get(key) ?? null),
+ mget: vi.fn(async (keys: string[]) => keys.map((key) => store.get(key) ?? null)),
set: vi.fn(async (key: string, value: string, ...args: unknown[]) => {
if (args.includes('NX') && store.has(key)) return null;
store.set(key, value);
@@ -198,6 +199,31 @@ describe('EditLockService', () => {
).toBe('user-1');
});
+ it('getBlockingHolders reads many locks in one MGET and reports only other members', async () => {
+ const redis = makeFakeRedis();
+ await new EditLockService('user-1', redis as any).acquire('task', 't-1', 'owner-1');
+ await new EditLockService('user-2', redis as any).acquire('task', 't-2', 'owner-2');
+ // Legacy raw user-id payloads still count as a holder.
+ redis.store.set('editlock:task:t-3', 'user-3');
+
+ const blocking = await new EditLockService('user-2', redis as any).getBlockingHolders('task', [
+ 't-1',
+ 't-2',
+ 't-3',
+ 't-4',
+ ]);
+
+ expect(redis.mget).toHaveBeenCalledTimes(1);
+ expect(redis.get).not.toHaveBeenCalled();
+ expect([...blocking]).toEqual([
+ ['t-1', 'user-1'],
+ ['t-3', 'user-3'],
+ ]);
+ expect(
+ (await new EditLockService('user-2', redis as any).getBlockingHolders('task', [])).size,
+ ).toBe(0);
+ });
+
it('only releases the lock for the current owner', async () => {
const redis = makeFakeRedis();
await new EditLockService('user-1', redis as any).acquire('document', 'doc-1', 'owner-1');
@@ -260,6 +286,7 @@ describe('EditLockService', () => {
ownerId: null,
});
expect(await svc.getBlockingHolder('document', 'doc-1')).toBeNull();
+ expect((await svc.getBlockingHolders('document', ['doc-1'])).size).toBe(0);
await expect(svc.release('document', 'doc-1')).resolves.toBe(false);
});
@@ -270,6 +297,7 @@ describe('EditLockService', () => {
const redis = {
eval: vi.fn().mockRejectedValue(down),
get: vi.fn().mockRejectedValue(down),
+ mget: vi.fn().mockRejectedValue(down),
set: vi.fn().mockRejectedValue(down),
};
const svc = new EditLockService('user-1', redis as any);
@@ -282,6 +310,7 @@ describe('EditLockService', () => {
});
expect(await svc.getActiveHolder('document', 'doc-1')).toBeUndefined();
expect(await svc.getBlockingHolder('document', 'doc-1')).toBeNull();
+ expect((await svc.getBlockingHolders('document', ['doc-1'])).size).toBe(0);
await expect(svc.canWrite('document', 'doc-1', 'owner-1')).resolves.toBe(true);
await expect(svc.release('document', 'doc-1')).resolves.toBe(false);
});
diff --git a/apps/server/src/services/editLock/index.ts b/apps/server/src/services/editLock/index.ts
index 2c07ac64834..3b6575f927f 100644
--- a/apps/server/src/services/editLock/index.ts
+++ b/apps/server/src/services/editLock/index.ts
@@ -215,6 +215,34 @@ export class EditLockService {
return null;
}
+ /**
+ * `getBlockingHolder` (without an owner id) for many resources in one MGET,
+ * so a batch write costs one Redis round trip instead of one per resource.
+ * Same fail-open rule: a Redis error reports every resource as unlocked.
+ */
+ async getBlockingHolders(
+ type: EditLockResourceType,
+ ids: readonly string[],
+ ): Promise<Map<string, string>> {
+ const blocking = new Map<string, string>();
+ const redis = this.redis;
+ if (!redis || ids.length === 0) return blocking;
+ let raws: (string | null)[];
+ try {
+ raws = await redis.mget(ids.map((id) => lockKey(type, id)));
+ } catch (error) {
+ log('getBlockingHolders failed for %s (%d ids) %O', type, ids.length, error);
+ return blocking;
+ }
+ ids.forEach((id, index) => {
+ const raw = raws[index];
+ if (!raw) return;
+ const holder = parseStoredLock(raw);
+ if (holder.userId !== this.userId) blocking.set(id, holder.userId);
+ });
+ return blocking;
+ }
+
/**
* Validate a content write against the current lease. When a caller provides
* an owner id, the active Redis lock must still belong to that owner; otherwise
diff --git a/apps/server/src/services/task/batch.ts b/apps/server/src/services/task/batch.ts
index 61ae8046a95..33c8c1dfd5c 100644
--- a/apps/server/src/services/task/batch.ts
+++ b/apps/server/src/services/task/batch.ts
@@ -7,12 +7,12 @@ 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 { trashTasksInTransaction } from '../trash';
import { assertArchivedTaskStaysIdle, findTasksInOpenGoals } from './archiveGuard';
import { notifyAssignedBestEffort } from './assignmentNotification';
import type { TaskBatchStatus } from './batchLimits';
@@ -24,8 +24,6 @@ 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 =
/** The task is part of an open goal and cannot be archived. */
@@ -39,7 +37,28 @@ export type TaskBatchSkipReason =
/** Already in the requested state. */
| 'unchanged'
/** The change would break a visibility or archive invariant. */
- | 'invalid';
+ | 'invalid'
+ /** Undo only: someone changed the task again since the batch, so it is left as it is. */
+ | 'conflict';
+
+/** The values one batch write replaced on one task, and what it wrote instead. */
+export interface TaskBatchRevertValues {
+ archived?: boolean;
+ assigneeAgentId?: string | null;
+ assigneeUserId?: string | null;
+ priority?: number | null;
+ status?: string;
+}
+
+/**
+ * How to undo a batch on one task: write `before` back, but only while the
+ * task still holds `after` — a later edit by anyone wins over the undo.
+ */
+export interface TaskBatchRevert {
+ after: TaskBatchRevertValues;
+ before: TaskBatchRevertValues;
+ id: string;
+}
export interface TaskBatchResult {
failed: { error: string; id: string }[];
@@ -49,6 +68,12 @@ export interface TaskBatchResult {
* tasks are completed; the caller should say the follow-ups did not run.
*/
followUpFailed?: boolean;
+ /**
+ * One entry per task in `updated`: the values this write replaced, as read
+ * under the row lock (not the caller's possibly stale copy), so an undo can
+ * put exactly those back. Absent for deletes — they undo through the bin.
+ */
+ reverts?: TaskBatchRevert[];
skipped: { id: string; reason: TaskBatchSkipReason }[];
/** Ids (as stored, not the caller's refs) that the batch changed. */
updated: string[];
@@ -107,14 +132,13 @@ export class TaskBatchService {
/** 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 },
+ // One MGET for the whole selection, not one GET per task.
+ const blocked = await new EditLockService(this.userId).getBlockingHolders(
+ 'task',
+ tasks.map((task) => task.id),
);
- return tasks.filter((task, index) => {
- if (!blocked[index]) return true;
+ return tasks.filter((task) => {
+ if (!blocked.has(task.id)) return true;
result.skipped.push({ id: task.id, reason: 'locked' });
return false;
});
@@ -283,6 +307,16 @@ export class TaskBatchService {
});
result.updated = updatedTasks.map(({ task }) => task.id);
+ const pick = (row: TaskBatchRevertValues): TaskBatchRevertValues => ({
+ ...(data.assigneeAgentId !== undefined && { assigneeAgentId: row.assigneeAgentId ?? null }),
+ ...(data.assigneeUserId !== undefined && { assigneeUserId: row.assigneeUserId ?? null }),
+ ...(data.priority !== undefined && { priority: row.priority ?? null }),
+ });
+ result.reverts = updatedTasks.map(({ before, task }) => ({
+ after: pick(task),
+ before: pick(before),
+ id: 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).
@@ -378,6 +412,7 @@ export class TaskBatchService {
const extra =
status === 'completed' || status === 'canceled' ? { completedAt: new Date() } : undefined;
let updatedTasks: TaskItem[] = [];
+ const statusBefore = new Map<string, string>();
let canceledTopics: Awaited<ReturnType<TaskTopicModel['cancelRunningByTaskIds']>> = [];
await this.db.transaction(async (tx) => {
const model = new TaskModel(tx, this.userId, this.workspaceId);
@@ -405,6 +440,7 @@ export class TaskBatchService {
return true;
});
const changingIds = changing.map((row) => row.id);
+ for (const row of changing) statusBefore.set(row.id, row.status);
canceledTopics = await new TaskTopicModel(
tx,
@@ -425,6 +461,11 @@ export class TaskBatchService {
);
});
result.updated = updatedTasks.map((task) => task.id);
+ result.reverts = updatedTasks.map((task) => ({
+ after: { status },
+ before: { status: statusBefore.get(task.id)! },
+ id: task.id,
+ }));
// Best-effort: stop operations that only showed up inside the transaction.
const interrupted = new Set(runningTopics.map((topic) => topic.operationId));
@@ -510,6 +551,11 @@ export class TaskBatchService {
if (!archived) {
const restored = await archiveModel.unarchiveMany(candidates.map((task) => task.id));
result.updated = restored.map((task) => task.id);
+ result.reverts = result.updated.map((id) => ({
+ after: { archived: false },
+ before: { archived: true },
+ id,
+ }));
return result;
}
@@ -531,6 +577,11 @@ export class TaskBatchService {
if (!done.has(task.id)) result.skipped.push({ id: task.id, reason: 'running' });
}
result.updated = [...done];
+ result.reverts = result.updated.map((id) => ({
+ after: { archived: true },
+ before: { archived: false },
+ id,
+ }));
return result;
}
@@ -572,17 +623,23 @@ export class TaskBatchService {
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,
- );
+ // Same cascade as the single delete: each task's linked topics go into
+ // the recycle bin with it (as its children) instead of lingering as
+ // sidebar orphans. One stamp and one registry write for the batch.
+ const topicIdsByTask = new Map<string, string[]>();
+ for (const link of await txTopics.findByTaskIds(deletable.map((row) => row.id))) {
+ if (!link.topicId) continue;
+ topicIdsByTask.set(link.taskId, [...(topicIdsByTask.get(link.taskId) ?? []), link.topicId]);
}
+ const deleted = await trashTasksInTransaction(
+ tx,
+ { userId: this.userId, workspaceId: this.workspaceId },
+ deletable.map((row) => ({
+ status: row.status,
+ taskId: row.id,
+ topicIds: topicIdsByTask.get(row.id) ?? [],
+ })),
+ );
return deleted;
});
result.updated.push(...deletedIdle);
diff --git a/apps/server/src/services/task/batchRevert.integration.test.ts b/apps/server/src/services/task/batchRevert.integration.test.ts
new file mode 100644
index 00000000000..7f93eefa3ca
--- /dev/null
+++ b/apps/server/src/services/task/batchRevert.integration.test.ts
@@ -0,0 +1,116 @@
+// @vitest-environment node
+import { type LobeChatDatabase } from '@lobechat/database';
+import { getTestDB } from '@lobechat/database/test-utils';
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { TaskModel } from '@/database/models/task';
+import { users } from '@/database/schemas';
+
+import { TaskBatchService } from './batch';
+import { TaskBatchRevertService } from './batchRevert';
+
+vi.mock('@/server/utils/scheduleAfterResponse', () => ({ after: vi.fn() }));
+vi.mock('@/server/services/file', () => ({
+ FileService: vi.fn().mockImplementation(() => ({ deleteFile: vi.fn(), deleteFiles: vi.fn() })),
+}));
+
+const userId = 'task-batch-revert-user';
+const actor = { agentId: null, userId };
+
+// Module-level: the first call migrates a fresh database, which can outlast a
+// hook timeout on a loaded CI shard.
+const db: LobeChatDatabase = await getTestDB();
+
+describe('TaskBatchRevertService (real PostgreSQL)', () => {
+ let model: TaskModel;
+ let batch: TaskBatchService;
+ let revert: TaskBatchRevertService;
+
+ beforeEach(async () => {
+ await db.delete(users).where(eq(users.id, userId));
+ await db.insert(users).values({ id: userId });
+ model = new TaskModel(db, userId);
+ batch = new TaskBatchService(db, userId);
+ revert = new TaskBatchRevertService(db, userId);
+ });
+
+ afterEach(async () => {
+ await db.delete(users).where(eq(users.id, userId));
+ });
+
+ const create = (data: Record<string, unknown> = {}) =>
+ model.create({ instruction: 'Do it', ...data });
+
+ it('puts each task back to its own previous status, not one shared value', async () => {
+ const a = await create();
+ const b = await create();
+ await model.updateStatus(b.id, 'paused');
+
+ const { result } = await batch.updateStatus([a.id, b.id], 'completed', actor);
+ expect(result.reverts).toEqual(
+ expect.arrayContaining([
+ { after: { status: 'completed' }, before: { status: 'backlog' }, id: a.id },
+ { after: { status: 'completed' }, before: { status: 'paused' }, id: b.id },
+ ]),
+ );
+
+ const undone = await revert.revert(result.reverts!, actor);
+
+ expect(undone.updated.sort()).toEqual([a.id, b.id].sort());
+ expect((await model.findById(a.id))?.status).toBe('backlog');
+ expect((await model.findById(b.id))?.status).toBe('paused');
+ });
+
+ it('leaves a task someone changed again since the batch alone', async () => {
+ const a = await create();
+ const b = await create();
+ const { result } = await batch.updateStatus([a.id, b.id], 'completed', actor);
+ await model.updateStatus(b.id, 'canceled');
+
+ const undone = await revert.revert(result.reverts!, actor);
+
+ expect(undone.updated).toEqual([a.id]);
+ expect(undone.skipped).toEqual([{ id: b.id, reason: 'conflict' }]);
+ expect((await model.findById(b.id))?.status).toBe('canceled');
+ });
+
+ it('restores per-task priorities and assignees', async () => {
+ const a = await create({ priority: 1 });
+ const b = await create({ priority: 3 });
+
+ const { result } = await batch.updateFields([a.id, b.id], { priority: 4 }, actor);
+ const undone = await revert.revert(result.reverts!, actor);
+
+ expect(undone.updated.sort()).toEqual([a.id, b.id].sort());
+ expect((await model.findById(a.id))?.priority).toBe(1);
+ expect((await model.findById(b.id))?.priority).toBe(3);
+ });
+
+ it('undoes an archive by restoring the tasks to the lists', async () => {
+ const a = await create();
+ const archived = await batch.archive([a.id], true);
+ expect(archived.reverts).toEqual([
+ { after: { archived: true }, before: { archived: false }, id: a.id },
+ ]);
+
+ const undone = await revert.revert(archived.reverts!, actor);
+
+ expect(undone.updated).toEqual([a.id]);
+ expect((await model.findById(a.id))?.archivedAt).toBeNull();
+ });
+
+ it('undoes a delete by bringing the tasks back out of the recycle bin', async () => {
+ const a = await create();
+ const b = await create();
+ await batch.delete([a.id, b.id]);
+ expect(await model.findById(a.id)).toBeNull();
+
+ const undone = await revert.restoreDeleted([a.id, b.id, 'task_missing']);
+
+ expect(undone.updated.sort()).toEqual([a.id, b.id].sort());
+ expect(undone.skipped).toEqual([{ id: 'task_missing', reason: 'notFound' }]);
+ expect(await model.findById(a.id)).not.toBeNull();
+ expect(await model.findById(b.id)).not.toBeNull();
+ });
+});
diff --git a/apps/server/src/services/task/batchRevert.ts b/apps/server/src/services/task/batchRevert.ts
new file mode 100644
index 00000000000..6e9350abb71
--- /dev/null
+++ b/apps/server/src/services/task/batchRevert.ts
@@ -0,0 +1,184 @@
+import type { TaskItem } from '@lobechat/types';
+
+import { TaskModel } from '@/database/models/task';
+import { TrashModel } from '@/database/models/trash';
+import type { LobeChatDatabase } from '@/database/type';
+
+import { TrashService } from '../trash';
+import {
+ type TaskBatchFieldsPatch,
+ type TaskBatchResult,
+ type TaskBatchRevert,
+ type TaskBatchRevertValues,
+ TaskBatchService,
+} from './batch';
+import { TASK_BATCH_STATUSES, type TaskBatchStatus } from './batchLimits';
+
+type Actor = { agentId?: string | null; userId?: string | null };
+
+const BATCH_STATUS_SET = new Set<string>(TASK_BATCH_STATUSES);
+
+/**
+ * The status an undo writes back. A task the batch stopped mid-run cannot be
+ * resumed by an undo (the run is gone), so it comes back paused. Statuses a
+ * person cannot set directly (failed, scheduled) are not restored.
+ */
+const revertStatus = (before: string): TaskBatchStatus | undefined => {
+ if (BATCH_STATUS_SET.has(before)) return before as TaskBatchStatus;
+ if (before === 'running') return 'paused';
+ return undefined;
+};
+
+/** Whether the task still holds every value the batch wrote (nobody edited it since). */
+const stillAfter = (task: TaskItem, after: TaskBatchRevertValues) =>
+ (after.status === undefined || task.status === after.status) &&
+ (after.archived === undefined || !!task.archivedAt === after.archived) &&
+ (after.priority === undefined || (task.priority ?? null) === after.priority) &&
+ (after.assigneeAgentId === undefined ||
+ (task.assigneeAgentId ?? null) === after.assigneeAgentId) &&
+ (after.assigneeUserId === undefined || (task.assigneeUserId ?? null) === after.assigneeUserId);
+
+const groupBy = <T>(items: T[], key: (item: T) => string | undefined) => {
+ const groups = new Map<string, T[]>();
+ for (const item of items) {
+ const k = key(item);
+ if (k === undefined) continue;
+ groups.set(k, [...(groups.get(k) ?? []), item]);
+ }
+ return groups;
+};
+
+const merge = (into: TaskBatchResult, from: TaskBatchResult) => {
+ into.updated.push(...from.updated);
+ into.skipped.push(...from.skipped);
+ into.failed.push(...from.failed);
+ if (from.followUpFailed) into.followUpFailed = true;
+};
+
+/**
+ * Undo of the task list's batch actions. Each revert goes back through the
+ * same batch write it undoes (status, fields, archive), so every invariant,
+ * lock and activity row the forward write had applies to the undo too — it is
+ * recorded as the caller's own change. A task someone changed again since the
+ * batch is reported as `conflict` and left alone: the undo never overwrites a
+ * later edit.
+ */
+export class TaskBatchRevertService {
+ private readonly db: LobeChatDatabase;
+ private readonly userId: string;
+ private readonly workspaceId?: string;
+
+ constructor(db: LobeChatDatabase, userId: string, workspaceId?: string) {
+ this.db = db;
+ this.userId = userId;
+ this.workspaceId = workspaceId;
+ }
+
+ async revert(reverts: TaskBatchRevert[], actor: Actor): Promise<TaskBatchResult> {
+ const result: TaskBatchResult = { failed: [], skipped: [], updated: [] };
+ const current = new Map(
+ (
+ await new TaskModel(this.db, this.userId, this.workspaceId).findByIds(
+ reverts.map((r) => r.id),
+ )
+ ).map((task) => [task.id, task]),
+ );
+
+ const applicable = reverts.filter((r) => {
+ const task = current.get(r.id);
+ if (!task) {
+ result.skipped.push({ id: r.id, reason: 'notFound' });
+ return false;
+ }
+ if (!stillAfter(task, r.after)) {
+ result.skipped.push({ id: r.id, reason: 'conflict' });
+ return false;
+ }
+ return true;
+ });
+
+ const batch = new TaskBatchService(this.db, this.userId, this.workspaceId);
+
+ // Status: one forward write per status to go back to.
+ const statusReverts = applicable.filter((r) => r.before.status !== undefined);
+ for (const [status, group] of groupBy(statusReverts, (r) => revertStatus(r.before.status!))) {
+ const { result: part } = await batch.updateStatus(
+ group.map((r) => r.id),
+ status as TaskBatchStatus,
+ actor,
+ );
+ merge(result, part);
+ }
+ for (const r of statusReverts) {
+ if (!revertStatus(r.before.status!)) result.skipped.push({ id: r.id, reason: 'invalid' });
+ }
+
+ // Archive: restore or re-archive.
+ const archiveReverts = applicable.filter((r) => r.before.archived !== undefined);
+ for (const [archived, group] of groupBy(archiveReverts, (r) => String(r.before.archived))) {
+ merge(
+ result,
+ await batch.archive(
+ group.map((r) => r.id),
+ archived === 'true',
+ ),
+ );
+ }
+
+ // Fields: one forward write per distinct set of values to put back.
+ const fieldReverts = applicable.filter(
+ (r) =>
+ r.before.priority !== undefined ||
+ r.before.assigneeAgentId !== undefined ||
+ r.before.assigneeUserId !== undefined,
+ );
+ const patchOf = (r: TaskBatchRevert): TaskBatchFieldsPatch => ({
+ ...(r.before.assigneeAgentId !== undefined && { assigneeAgentId: r.before.assigneeAgentId }),
+ ...(r.before.assigneeUserId !== undefined && { assigneeUserId: r.before.assigneeUserId }),
+ // A task that had no priority goes back to the default (0, "none").
+ ...(r.before.priority !== undefined && { priority: r.before.priority ?? 0 }),
+ });
+ for (const [key, group] of groupBy(fieldReverts, (r) => JSON.stringify(patchOf(r)))) {
+ const { result: part } = await batch.updateFields(
+ group.map((r) => r.id),
+ JSON.parse(key) as TaskBatchFieldsPatch,
+ actor,
+ );
+ merge(result, part);
+ }
+
+ return result;
+ }
+
+ /**
+ * Undo of a batch delete: bring the tasks back out of the recycle bin (with
+ * the topics that went in with them). A task whose parent is still in the
+ * bin, or that was purged meanwhile, is reported instead of restored.
+ */
+ async restoreDeleted(taskIds: string[]): Promise<TaskBatchResult> {
+ const result: TaskBatchResult = { failed: [], skipped: [], updated: [] };
+ const roots = await new TrashModel(this.db, this.userId, this.workspaceId).findRootsByResources(
+ 'task',
+ taskIds,
+ );
+ const byRoot = new Map(roots.map((root) => [root.id, root.resourceId]));
+ const found = new Set(roots.map((root) => root.resourceId));
+ for (const id of taskIds) {
+ if (!found.has(id)) result.skipped.push({ id, reason: 'notFound' });
+ }
+
+ const outcome = await new TrashService(this.db, this.userId, this.workspaceId).restore([
+ ...byRoot.keys(),
+ ]);
+ result.updated = outcome.restored.map((item) => item.resourceId);
+ for (const { code, id } of outcome.failed) {
+ const taskId = byRoot.get(id);
+ if (!taskId) continue;
+ result.skipped.push({
+ id: taskId,
+ reason: code === 'parentTrashed' ? 'invalid' : 'notFound',
+ });
+ }
+ return result;
+ }
+}
diff --git a/apps/server/src/services/task/index.deleteTask.test.ts b/apps/server/src/services/task/index.deleteTask.test.ts
new file mode 100644
index 00000000000..9ad5d6bdfc6
--- /dev/null
+++ b/apps/server/src/services/task/index.deleteTask.test.ts
@@ -0,0 +1,454 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { AgentModel } from '@/database/models/agent';
+import { BriefModel } from '@/database/models/brief';
+import { RbacModel } from '@/database/models/rbac';
+import { TaskModel } from '@/database/models/task';
+import { TaskTopicModel } from '@/database/models/taskTopic';
+import { TopicModel } from '@/database/models/topic';
+import { WorkspaceMemberModel } from '@/database/models/workspaceMember';
+import type { LobeChatDatabase } from '@/database/type';
+
+import { TaskService } from './index';
+
+const { cancelScheduled, scheduleNextTopic, trashTasksInTransaction } = vi.hoisted(() => ({
+ cancelScheduled: vi.fn(),
+ scheduleNextTopic: vi.fn(),
+ trashTasksInTransaction: vi.fn(),
+}));
+
+vi.mock('../trash', () => ({ trashTasksInTransaction }));
+
+vi.mock('@/database/models/agent', () => ({
+ AgentModel: vi.fn(),
+}));
+
+vi.mock('@/database/models/task', () => ({
+ TaskModel: vi.fn(),
+ taskActivityActor: (actor: { agentId?: string | null; userId?: string | null }) => ({
+ actorAgentId: actor.agentId ?? null,
+ actorKind: actor.agentId ? 'agent' : actor.userId ? 'user' : 'system',
+ actorUserId: actor.agentId ? null : (actor.userId ?? null),
+ }),
+}));
+
+const { findGoalByTaskId } = vi.hoisted(() => ({
+ findGoalByTaskId: vi.fn().mockResolvedValue(undefined),
+}));
+vi.mock('@/database/models/goalGraph', () => ({
+ GoalGraphModel: vi.fn().mockImplementation(function () {
+ return { findGoalByTaskId };
+ }),
+}));
+
+vi.mock('@/database/models/taskTopic', () => ({
+ TaskTopicModel: vi.fn(),
+}));
+
+vi.mock('@/database/models/topic', () => ({
+ TopicModel: vi.fn(),
+}));
+
+vi.mock('@/database/models/brief', () => ({
+ BriefModel: vi.fn(),
+}));
+
+vi.mock('@/database/models/rbac', () => ({
+ RbacModel: vi.fn(),
+}));
+
+vi.mock('@/database/models/workspaceMember', () => ({
+ WorkspaceMemberModel: vi.fn(),
+}));
+
+vi.mock('@/database/models/user', () => ({
+ UserModel: { findByIds: vi.fn().mockResolvedValue([]) },
+}));
+
+const { resolveTaskAcceptance } = vi.hoisted(() => ({
+ resolveTaskAcceptance: vi.fn(),
+}));
+
+vi.mock('@/server/services/verify/taskAcceptanceResolution', () => ({ resolveTaskAcceptance }));
+
+// AiAgentService pulls in ~14 sub-dependencies in its constructor; mock it so
+// the running-status branch in updateStatus doesn't drag them in.
+const { interruptTaskMock } = vi.hoisted(() => ({ interruptTaskMock: vi.fn() }));
+vi.mock('@/server/services/aiAgent', () => ({
+ AiAgentService: vi.fn().mockImplementation(function () {
+ return {
+ interruptTask: interruptTaskMock,
+ };
+ }),
+}));
+
+vi.mock('@/server/services/taskScheduler', () => ({
+ createTaskSchedulerModule: () => ({ cancelScheduled, scheduleNextTopic }),
+}));
+
+// Attachment resolver hits FileModel + DocumentService + FileService — stub it
+// out so getTaskDetail tests don't need a real file pipeline.
+vi.mock('@/server/services/file/resolveAttachments', () => ({
+ resolveAttachmentMetadata: vi.fn().mockResolvedValue([]),
+}));
+
+describe('TaskService.deleteTask', () => {
+ const db = {} as LobeChatDatabase;
+ const userId = 'user-1';
+
+ const mockAgentModel = {
+ existsById: vi.fn().mockResolvedValue(true),
+ getAgentAvatarsByIds: vi.fn().mockResolvedValue([]),
+ getAgentModelConfig: vi.fn().mockResolvedValue(null),
+ getAgentSnapshotForTaskCreate: vi
+ .fn()
+ .mockResolvedValue({ snapshot: null, visibility: 'public' }),
+ getAgentVisibility: vi.fn().mockResolvedValue('public'),
+ };
+
+ const mockTaskModel = {
+ addActivities: vi.fn(),
+ addActivity: vi.fn(),
+ findSubtasks: vi.fn(),
+ lockForStatusChange: vi.fn(),
+ updateStatusForIds: vi.fn(),
+ updateWithLog: vi.fn(),
+ create: vi.fn(),
+ delete: vi.fn(),
+ deleteIfStatus: vi.fn().mockResolvedValue(true),
+ lockForUpdate: vi.fn().mockResolvedValue(true),
+ findById: vi.fn(),
+ findByIds: vi.fn(),
+ findAllDescendants: vi.fn(),
+ getActivities: vi.fn().mockResolvedValue([]),
+ getCheckpointConfig: vi.fn(),
+ getComments: vi.fn(),
+ getCommentFileIdsMap: vi.fn().mockResolvedValue({}),
+ getDependencies: vi.fn(),
+ getDependenciesByTaskIds: vi.fn().mockResolvedValue([]),
+ getReviewConfig: vi.fn(),
+ getVerifyConfig: vi.fn(),
+ getTaskFileIds: vi.fn().mockResolvedValue([]),
+ getTreeAgentIdsForTaskIds: vi.fn().mockResolvedValue({}),
+ getTreePinnedDocuments: vi.fn(),
+
+ update: vi.fn(),
+ updateContext: vi.fn(),
+ updateStatus: vi.fn(),
+ };
+
+ const mockTaskTopicModel = {
+ cancelIfRunning: vi.fn(),
+ cancelRunningByTaskIds: vi.fn(),
+ findByTaskId: vi.fn(),
+ findRunningByTaskIds: vi.fn().mockResolvedValue([]),
+ findWithHandoff: vi.fn(),
+ findWithHandoffByTaskIds: vi.fn().mockResolvedValue([]),
+ timeoutRunning: vi.fn(),
+ };
+
+ const mockTopicModel = {
+ batchDeleteIncludingTrashed: vi.fn().mockResolvedValue(undefined),
+ };
+
+ const mockBriefModel = {
+ findByTaskId: vi.fn(),
+ };
+
+ const mockRbacModel = {
+ hasAnyPermission: vi.fn().mockResolvedValue(true),
+ };
+
+ const mockWorkspaceMemberModel = {
+ getMember: vi.fn().mockResolvedValue({ role: 'member', userId: 'member-1' }),
+ };
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ interruptTaskMock.mockReset().mockResolvedValue({ success: true });
+ cancelScheduled.mockResolvedValue(undefined);
+ scheduleNextTopic.mockResolvedValue('tick-new');
+ resolveTaskAcceptance.mockResolvedValue(undefined);
+ mockTaskTopicModel.findRunningByTaskIds.mockResolvedValue([]);
+ mockTaskModel.getActivities.mockResolvedValue([]);
+ mockTopicModel.batchDeleteIncludingTrashed.mockResolvedValue(undefined);
+ (AgentModel as any).mockImplementation(function () {
+ return mockAgentModel;
+ });
+ (TaskModel as any).mockImplementation(function () {
+ return mockTaskModel;
+ });
+ (TaskTopicModel as any).mockImplementation(function () {
+ return mockTaskTopicModel;
+ });
+ (TopicModel as any).mockImplementation(function () {
+ return mockTopicModel;
+ });
+ (BriefModel as any).mockImplementation(function () {
+ return mockBriefModel;
+ });
+ (RbacModel as any).mockImplementation(function () {
+ return mockRbacModel;
+ });
+ (WorkspaceMemberModel as any).mockImplementation(function () {
+ return mockWorkspaceMemberModel;
+ });
+ });
+
+ describe('deleteTask', () => {
+ beforeEach(() => {
+ (db as any).transaction = async (fn: (tx: unknown) => Promise<unknown>) => fn(db);
+ mockTaskModel.lockForUpdate.mockResolvedValue(true);
+ // Moves every target into the recycle bin unless a test says otherwise.
+ trashTasksInTransaction.mockReset();
+ trashTasksInTransaction.mockImplementation(
+ async (_tx: unknown, _scope: unknown, targets: { taskId: string }[]) =>
+ targets.map((target) => target.taskId),
+ );
+ mockTaskTopicModel.findByTaskId.mockResolvedValue([]);
+ });
+
+ it('interrupts a running execution before trashing the task', async () => {
+ mockTaskModel.findById.mockResolvedValue({
+ id: 'task-live',
+ identifier: 'T-2',
+ status: 'running',
+ });
+ mockTaskTopicModel.findRunningByTaskIds.mockResolvedValue([
+ { operationId: 'op-live', status: 'running', taskId: 'task-live', topicId: 'topic-live' },
+ ]);
+
+ await new TaskService(db, userId).deleteTask('T-2');
+
+ expect(interruptTaskMock).toHaveBeenCalledWith({ operationId: 'op-live' });
+ expect(interruptTaskMock.mock.invocationCallOrder[0]).toBeLessThan(
+ trashTasksInTransaction.mock.invocationCallOrder[0],
+ );
+ expect(trashTasksInTransaction).toHaveBeenCalledWith(
+ expect.anything(),
+ { userId, workspaceId: undefined },
+ [expect.objectContaining({ status: 'running', taskId: 'task-live' })],
+ );
+ });
+
+ it('keeps the task when its execution cannot be stopped', async () => {
+ mockTaskModel.findById.mockResolvedValue({
+ id: 'task-live',
+ identifier: 'T-2',
+ status: 'running',
+ });
+ mockTaskTopicModel.findRunningByTaskIds.mockResolvedValue([
+ { operationId: 'op-live', status: 'running', taskId: 'task-live', topicId: 'topic-live' },
+ ]);
+ interruptTaskMock.mockResolvedValueOnce({ success: false });
+
+ await expect(new TaskService(db, userId).deleteTask('T-2')).rejects.toThrow(
+ 'Task interruption was not confirmed',
+ );
+ expect(trashTasksInTransaction).not.toHaveBeenCalled();
+ });
+
+ it('refuses to delete a task whose run is still starting', async () => {
+ mockTaskModel.findById.mockResolvedValue({
+ id: 'task-starting',
+ identifier: 'T-4',
+ startedAt: new Date(),
+ status: 'running',
+ });
+ mockTaskTopicModel.findRunningByTaskIds.mockResolvedValue([]);
+
+ await expect(new TaskService(db, userId).deleteTask('T-4')).rejects.toMatchObject({
+ code: 'CONFLICT',
+ });
+ expect(trashTasksInTransaction).not.toHaveBeenCalled();
+ });
+
+ it('deletes a running task whose start died long ago', async () => {
+ mockTaskModel.findById.mockResolvedValue({
+ id: 'task-stale',
+ identifier: 'T-5',
+ startedAt: new Date(Date.now() - 60 * 60 * 1000),
+ status: 'running',
+ });
+ mockTaskTopicModel.findRunningByTaskIds.mockResolvedValue([]);
+
+ await new TaskService(db, userId).deleteTask('T-5');
+
+ expect(trashTasksInTransaction).toHaveBeenCalledWith(
+ expect.anything(),
+ { userId, workspaceId: undefined },
+ [expect.objectContaining({ status: 'running', taskId: 'task-stale' })],
+ );
+ });
+
+ it('loses to a run that started after the checks instead of orphaning it', async () => {
+ mockTaskModel.findById.mockResolvedValue({
+ id: 'task-race',
+ identifier: 'T-6',
+ status: 'backlog',
+ });
+ trashTasksInTransaction.mockResolvedValueOnce([]);
+
+ await expect(new TaskService(db, userId).deleteTask('T-6')).rejects.toMatchObject({
+ code: 'CONFLICT',
+ });
+ expect(trashTasksInTransaction).toHaveBeenCalledWith(
+ expect.anything(),
+ { userId, workspaceId: undefined },
+ [expect.objectContaining({ status: 'backlog', taskId: 'task-race' })],
+ );
+ });
+
+ it('loses to a run that recorded a new topic while the delete was interrupting', async () => {
+ mockTaskModel.findById.mockResolvedValue({
+ id: 'task-cont',
+ identifier: 'T-8',
+ status: 'running',
+ });
+ const liveA = {
+ operationId: 'op-a',
+ status: 'running',
+ taskId: 'task-cont',
+ topicId: 'topic-a',
+ };
+ const continuedB = {
+ operationId: 'op-b',
+ status: 'running',
+ taskId: 'task-cont',
+ topicId: 'topic-b',
+ };
+ mockTaskTopicModel.findRunningByTaskIds
+ .mockResolvedValueOnce([liveA])
+ .mockResolvedValueOnce([liveA, continuedB]);
+
+ await expect(new TaskService(db, userId).deleteTask('T-8')).rejects.toMatchObject({
+ code: 'CONFLICT',
+ });
+ expect(interruptTaskMock).toHaveBeenCalledWith({ operationId: 'op-a' });
+ expect(mockTaskModel.lockForUpdate).toHaveBeenCalledWith('task-cont');
+ expect(trashTasksInTransaction).not.toHaveBeenCalled();
+ });
+
+ it('treats a task already gone as deleted', async () => {
+ mockTaskModel.findById.mockResolvedValue({
+ id: 'task-gone',
+ identifier: 'T-7',
+ status: 'backlog',
+ });
+ mockTaskModel.lockForUpdate.mockResolvedValueOnce(false);
+
+ await expect(new TaskService(db, userId).deleteTask('T-7')).resolves.toMatchObject({
+ id: 'task-gone',
+ });
+ expect(trashTasksInTransaction).not.toHaveBeenCalled();
+ });
+
+ it("does not interrupt the caller's own run", async () => {
+ mockTaskModel.findById.mockResolvedValue({
+ id: 'task-self',
+ identifier: 'T-3',
+ status: 'running',
+ });
+ mockTaskTopicModel.findRunningByTaskIds.mockResolvedValue([
+ { operationId: 'op-self', status: 'running', taskId: 'task-self', topicId: 'topic-self' },
+ ]);
+
+ await new TaskService(db, userId).deleteTask('T-3', { keepOperationId: 'op-self' });
+
+ expect(interruptTaskMock).not.toHaveBeenCalled();
+ expect(trashTasksInTransaction).toHaveBeenCalledWith(
+ expect.anything(),
+ { userId, workspaceId: undefined },
+ [expect.objectContaining({ status: 'running', taskId: 'task-self' })],
+ );
+ });
+
+ it('trashes the linked topics with the task, from the snapshot taken under the lock', async () => {
+ mockTaskModel.findById.mockResolvedValue({
+ id: 'task-topics',
+ identifier: 'T-9',
+ status: 'backlog',
+ });
+ mockTaskTopicModel.findByTaskId.mockResolvedValue([
+ { status: 'completed', taskId: 'task-topics', topicId: 'topic-1' },
+ { status: 'completed', taskId: 'task-topics', topicId: 'topic-2' },
+ ]);
+
+ await new TaskService(db, userId).deleteTask('T-9');
+
+ // The topic rows have no FK back to the task: they go into the bin as its
+ // children (restored with it), instead of lingering as sidebar orphans.
+ expect(trashTasksInTransaction).toHaveBeenCalledWith(expect.anything(), expect.anything(), [
+ { status: 'backlog', taskId: 'task-topics', topicIds: ['topic-1', 'topic-2'] },
+ ]);
+ expect(mockTopicModel.batchDeleteIncludingTrashed).not.toHaveBeenCalled();
+ });
+
+ it('spares the kept operation topic when a task deletes itself mid-run', async () => {
+ mockTaskModel.findById.mockResolvedValue({
+ id: 'task-self-topics',
+ identifier: 'T-12',
+ status: 'running',
+ });
+ mockTaskTopicModel.findRunningByTaskIds.mockResolvedValue([
+ {
+ operationId: 'op-self',
+ status: 'running',
+ taskId: 'task-self-topics',
+ topicId: 'topic-live',
+ },
+ ]);
+ mockTaskTopicModel.findByTaskId.mockResolvedValue([
+ {
+ operationId: 'op-self',
+ status: 'running',
+ taskId: 'task-self-topics',
+ topicId: 'topic-live',
+ },
+ { status: 'completed', taskId: 'task-self-topics', topicId: 'topic-old' },
+ ]);
+
+ await new TaskService(db, userId).deleteTask('T-12', { keepOperationId: 'op-self' });
+
+ // The live run's topic must survive with its operation — it stays out of
+ // the bin, so the still-running tool call keeps its conversation.
+ expect(trashTasksInTransaction).toHaveBeenCalledWith(expect.anything(), expect.anything(), [
+ { status: 'running', taskId: 'task-self-topics', topicIds: ['topic-old'] },
+ ]);
+ });
+
+ it('trashes the task alone when it has no topics', async () => {
+ mockTaskModel.findById.mockResolvedValue({
+ id: 'task-bare',
+ identifier: 'T-10',
+ status: 'backlog',
+ });
+ mockTaskTopicModel.findByTaskId.mockResolvedValue([]);
+
+ await new TaskService(db, userId).deleteTask('T-10');
+
+ expect(trashTasksInTransaction).toHaveBeenCalledWith(expect.anything(), expect.anything(), [
+ { status: 'backlog', taskId: 'task-bare', topicIds: [] },
+ ]);
+ });
+
+ it('reports a conflict when the status CAS loses the race', async () => {
+ mockTaskModel.findById.mockResolvedValue({
+ id: 'task-race-topics',
+ identifier: 'T-11',
+ status: 'backlog',
+ });
+ mockTaskTopicModel.findByTaskId.mockResolvedValue([
+ { status: 'completed', taskId: 'task-race-topics', topicId: 'topic-race' },
+ ]);
+ trashTasksInTransaction.mockResolvedValueOnce([]);
+
+ await expect(new TaskService(db, userId).deleteTask('T-11')).rejects.toMatchObject({
+ code: 'CONFLICT',
+ });
+ expect(mockTopicModel.batchDeleteIncludingTrashed).not.toHaveBeenCalled();
+ expect(mockTaskModel.deleteIfStatus).not.toHaveBeenCalled();
+ });
+ });
+});
diff --git a/apps/server/src/services/task/index.test.ts b/apps/server/src/services/task/index.test.ts
index 16bb83d62bc..6c3a0c8efb2 100644
--- a/apps/server/src/services/task/index.test.ts
+++ b/apps/server/src/services/task/index.test.ts
@@ -13,11 +13,14 @@ import type { LobeChatDatabase } from '@/database/type';
import { TaskService } from './index';
-const { cancelScheduled, scheduleNextTopic } = vi.hoisted(() => ({
+const { cancelScheduled, scheduleNextTopic, trashTasksInTransaction } = vi.hoisted(() => ({
cancelScheduled: vi.fn(),
scheduleNextTopic: vi.fn(),
+ trashTasksInTransaction: vi.fn(),
}));
+vi.mock('../trash', () => ({ trashTasksInTransaction }));
+
vi.mock('@/database/models/agent', () => ({
AgentModel: vi.fn(),
}));
@@ -164,6 +167,8 @@ describe('TaskService', () => {
beforeEach(() => {
vi.clearAllMocks();
+ // Run transactions inline on the mocked client (status writes open one).
+ (db as any).transaction = async (fn: (tx: unknown) => Promise<unknown>) => fn(db);
interruptTaskMock.mockReset().mockResolvedValue({ success: true });
cancelScheduled.mockResolvedValue(undefined);
scheduleNextTopic.mockResolvedValue('tick-new');
@@ -1632,238 +1637,6 @@ describe('TaskService', () => {
);
});
- describe('deleteTask', () => {
- beforeEach(() => {
- (db as any).transaction = async (fn: (tx: unknown) => Promise<unknown>) => fn(db);
- mockTaskModel.lockForUpdate.mockResolvedValue(true);
- mockTaskModel.deleteIfStatus.mockResolvedValue(true);
- mockTaskTopicModel.findByTaskId.mockResolvedValue([]);
- });
-
- it('interrupts a running execution before deleting the task row', async () => {
- mockTaskModel.findById.mockResolvedValue({
- id: 'task-live',
- identifier: 'T-2',
- status: 'running',
- });
- mockTaskTopicModel.findRunningByTaskIds.mockResolvedValue([
- { operationId: 'op-live', status: 'running', taskId: 'task-live', topicId: 'topic-live' },
- ]);
-
- await new TaskService(db, userId).deleteTask('T-2');
-
- expect(interruptTaskMock).toHaveBeenCalledWith({ operationId: 'op-live' });
- expect(interruptTaskMock.mock.invocationCallOrder[0]).toBeLessThan(
- mockTaskModel.deleteIfStatus.mock.invocationCallOrder[0],
- );
- expect(mockTaskModel.deleteIfStatus).toHaveBeenCalledWith('task-live', 'running');
- });
-
- it('keeps the task when its execution cannot be stopped', async () => {
- mockTaskModel.findById.mockResolvedValue({
- id: 'task-live',
- identifier: 'T-2',
- status: 'running',
- });
- mockTaskTopicModel.findRunningByTaskIds.mockResolvedValue([
- { operationId: 'op-live', status: 'running', taskId: 'task-live', topicId: 'topic-live' },
- ]);
- interruptTaskMock.mockResolvedValueOnce({ success: false });
-
- await expect(new TaskService(db, userId).deleteTask('T-2')).rejects.toThrow(
- 'Task interruption was not confirmed',
- );
- expect(mockTaskModel.deleteIfStatus).not.toHaveBeenCalled();
- });
-
- it('refuses to delete a task whose run is still starting', async () => {
- mockTaskModel.findById.mockResolvedValue({
- id: 'task-starting',
- identifier: 'T-4',
- startedAt: new Date(),
- status: 'running',
- });
- mockTaskTopicModel.findRunningByTaskIds.mockResolvedValue([]);
-
- await expect(new TaskService(db, userId).deleteTask('T-4')).rejects.toMatchObject({
- code: 'CONFLICT',
- });
- expect(mockTaskModel.deleteIfStatus).not.toHaveBeenCalled();
- });
-
- it('deletes a running task whose start died long ago', async () => {
- mockTaskModel.findById.mockResolvedValue({
- id: 'task-stale',
- identifier: 'T-5',
- startedAt: new Date(Date.now() - 60 * 60 * 1000),
- status: 'running',
- });
- mockTaskTopicModel.findRunningByTaskIds.mockResolvedValue([]);
-
- await new TaskService(db, userId).deleteTask('T-5');
-
- expect(mockTaskModel.deleteIfStatus).toHaveBeenCalledWith('task-stale', 'running');
- });
-
- it('loses to a run that started after the checks instead of orphaning it', async () => {
- mockTaskModel.findById.mockResolvedValue({
- id: 'task-race',
- identifier: 'T-6',
- status: 'backlog',
- });
- mockTaskModel.deleteIfStatus.mockResolvedValueOnce(false);
-
- await expect(new TaskService(db, userId).deleteTask('T-6')).rejects.toMatchObject({
- code: 'CONFLICT',
- });
- expect(mockTaskModel.deleteIfStatus).toHaveBeenCalledWith('task-race', 'backlog');
- });
-
- it('loses to a run that recorded a new topic while the delete was interrupting', async () => {
- mockTaskModel.findById.mockResolvedValue({
- id: 'task-cont',
- identifier: 'T-8',
- status: 'running',
- });
- const liveA = {
- operationId: 'op-a',
- status: 'running',
- taskId: 'task-cont',
- topicId: 'topic-a',
- };
- const continuedB = {
- operationId: 'op-b',
- status: 'running',
- taskId: 'task-cont',
- topicId: 'topic-b',
- };
- mockTaskTopicModel.findRunningByTaskIds
- .mockResolvedValueOnce([liveA])
- .mockResolvedValueOnce([liveA, continuedB]);
-
- await expect(new TaskService(db, userId).deleteTask('T-8')).rejects.toMatchObject({
- code: 'CONFLICT',
- });
- expect(interruptTaskMock).toHaveBeenCalledWith({ operationId: 'op-a' });
- expect(mockTaskModel.lockForUpdate).toHaveBeenCalledWith('task-cont');
- expect(mockTaskModel.deleteIfStatus).not.toHaveBeenCalled();
- });
-
- it('treats a task already gone as deleted', async () => {
- mockTaskModel.findById.mockResolvedValue({
- id: 'task-gone',
- identifier: 'T-7',
- status: 'backlog',
- });
- mockTaskModel.lockForUpdate.mockResolvedValueOnce(false);
-
- await expect(new TaskService(db, userId).deleteTask('T-7')).resolves.toMatchObject({
- id: 'task-gone',
- });
- expect(mockTaskModel.deleteIfStatus).not.toHaveBeenCalled();
- });
-
- it("does not interrupt the caller's own run", async () => {
- mockTaskModel.findById.mockResolvedValue({
- id: 'task-self',
- identifier: 'T-3',
- status: 'running',
- });
- mockTaskTopicModel.findRunningByTaskIds.mockResolvedValue([
- { operationId: 'op-self', status: 'running', taskId: 'task-self', topicId: 'topic-self' },
- ]);
-
- await new TaskService(db, userId).deleteTask('T-3', { keepOperationId: 'op-self' });
-
- expect(interruptTaskMock).not.toHaveBeenCalled();
- expect(mockTaskModel.deleteIfStatus).toHaveBeenCalledWith('task-self', 'running');
- });
-
- it('cascades the underlying topic rows when the task row is deleted', async () => {
- mockTaskModel.findById.mockResolvedValue({
- id: 'task-topics',
- identifier: 'T-9',
- status: 'backlog',
- });
- mockTaskTopicModel.findByTaskId.mockResolvedValue([
- { status: 'completed', taskId: 'task-topics', topicId: 'topic-1' },
- { status: 'completed', taskId: 'task-topics', topicId: 'topic-2' },
- ]);
-
- await new TaskService(db, userId).deleteTask('T-9');
-
- // Topic ids are snapshotted before the task row goes, then removed in
- // the same transaction — `task_topics` links alone cascade via FK, the
- // topic rows would otherwise survive as sidebar orphans.
- expect(mockTopicModel.batchDeleteIncludingTrashed).toHaveBeenCalledWith([
- 'topic-1',
- 'topic-2',
- ]);
- });
-
- it('spares the kept operation topic when a task deletes itself mid-run', async () => {
- mockTaskModel.findById.mockResolvedValue({
- id: 'task-self-topics',
- identifier: 'T-12',
- status: 'running',
- });
- mockTaskTopicModel.findRunningByTaskIds.mockResolvedValue([
- {
- operationId: 'op-self',
- status: 'running',
- taskId: 'task-self-topics',
- topicId: 'topic-live',
- },
- ]);
- mockTaskTopicModel.findByTaskId.mockResolvedValue([
- {
- operationId: 'op-self',
- status: 'running',
- taskId: 'task-self-topics',
- topicId: 'topic-live',
- },
- { status: 'completed', taskId: 'task-self-topics', topicId: 'topic-old' },
- ]);
-
- await new TaskService(db, userId).deleteTask('T-12', { keepOperationId: 'op-self' });
-
- // The live run's topic must survive with its operation — messages
- // cascade off the topic row, so deleting it would rip the conversation
- // out from under the still-running tool call.
- expect(mockTopicModel.batchDeleteIncludingTrashed).toHaveBeenCalledWith(['topic-old']);
- });
-
- it('deletes no topic rows when the task has none', async () => {
- mockTaskModel.findById.mockResolvedValue({
- id: 'task-bare',
- identifier: 'T-10',
- status: 'backlog',
- });
- mockTaskTopicModel.findByTaskId.mockResolvedValue([]);
-
- await new TaskService(db, userId).deleteTask('T-10');
-
- expect(mockTopicModel.batchDeleteIncludingTrashed).not.toHaveBeenCalled();
- });
-
- it('leaves topic rows alone when the delete loses the race', async () => {
- mockTaskModel.findById.mockResolvedValue({
- id: 'task-race-topics',
- identifier: 'T-11',
- status: 'backlog',
- });
- mockTaskTopicModel.findByTaskId.mockResolvedValue([
- { status: 'completed', taskId: 'task-race-topics', topicId: 'topic-race' },
- ]);
- mockTaskModel.deleteIfStatus.mockResolvedValueOnce(false);
-
- await expect(new TaskService(db, userId).deleteTask('T-11')).rejects.toMatchObject({
- code: 'CONFLICT',
- });
- expect(mockTopicModel.batchDeleteIncludingTrashed).not.toHaveBeenCalled();
- });
- });
-
describe('updateStatus / scheduleStartedAt', () => {
const baseTask = (overrides: Partial<Record<string, unknown>> = {}) => ({
automationMode: 'schedule',
diff --git a/apps/server/src/services/task/index.ts b/apps/server/src/services/task/index.ts
index 412b81c5e94..82779ceb143 100644
--- a/apps/server/src/services/task/index.ts
+++ b/apps/server/src/services/task/index.ts
@@ -16,6 +16,7 @@ import { AiAgentService } from '../aiAgent';
import { displaySubtaskPlan, type SubtaskGraphPlan, TaskGraphService } from '../taskGraph';
import { type ReviewResult, TaskReviewService } from '../taskReview';
import { TaskRunnerService } from '../taskRunner';
+import { trashTasksInTransaction } from '../trash';
import { writeKeepingArchivedIdle } from './archiveGuard';
import { armScheduleOnColumnWrite } from './armScheduleOnColumnWrite';
import { armScheduleOnCreate } from './armScheduleOnCreate';
@@ -384,14 +385,12 @@ export class TaskService {
// stops its own execution. Compare-and-delete on the status as well, so a
// run that moved the task on in the meantime is never deleted under.
//
- // The tool contract ("dependencies/topics/comments cascade-delete") is
- // honored here for topics themselves: `task_topics` rows go via FK
- // cascade, but the underlying `topics` rows have no FK back to `tasks`
- // and would otherwise survive as orphans that keep showing up in the
- // sidebar. Collect their ids before the task row goes (the cascade wipes
- // the links with it), then delete the topic rows in the same transaction.
- // The kept operation's own topic is excluded — it must survive with its
- // run (see the snapshot below).
+ // The task goes to the recycle bin, and its linked topics with it: the
+ // `topics` rows have no FK back to `tasks` and would otherwise keep
+ // showing up in the sidebar. Collect their ids under the lock and trash
+ // them in the same transaction (they come back with a restore and are
+ // hard-deleted at purge). The kept operation's own topic is excluded — it
+ // must survive with its run (see the snapshot below).
const handled = new Set(runningTopics.map((topic) => topic.operationId));
const outcome = await this.db.transaction(async (tx) => {
const taskModel = new TaskModel(tx, this.userId, this.workspaceId);
@@ -416,16 +415,15 @@ export class TaskService {
.map((topic) => topic.topicId)
.filter((topicId): topicId is string => !!topicId);
- if (!(await taskModel.deleteIfStatus(task.id, task.status))) return 'conflict' as const;
-
- if (topicIds.length > 0) {
- // trashScope variant: a linked topic already sitting in the recycle
- // bin must go too, or restoring it later resurrects the sidebar
- // orphan this cascade exists to eliminate.
- await new TopicModel(tx, this.userId, this.workspaceId).batchDeleteIncludingTrashed(
- topicIds,
- );
- }
+ // Into the recycle bin, with its linked topics as children (restorable
+ // for the retention window, hard-deleted at purge). The status CAS is
+ // part of the stamp: a task a run moved on is not trashed under it.
+ const trashed = await trashTasksInTransaction(
+ tx,
+ { userId: this.userId, workspaceId: this.workspaceId },
+ [{ status: task.status, taskId: task.id, topicIds }],
+ );
+ if (trashed.length === 0) return 'conflict' as const;
return 'deleted' as const;
});
if (outcome === 'conflict') {
diff --git a/apps/server/src/services/trash/__tests__/task.test.ts b/apps/server/src/services/trash/__tests__/task.test.ts
new file mode 100644
index 00000000000..fad91f15aec
--- /dev/null
+++ b/apps/server/src/services/trash/__tests__/task.test.ts
@@ -0,0 +1,205 @@
+// @vitest-environment node
+import { getTestDB } from '@lobechat/database/test-utils';
+import { eq, inArray } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { BriefModel } from '@/database/models/brief';
+import { RecentModel } from '@/database/models/recent';
+import { TaskModel } from '@/database/models/task';
+import { TaskTopicModel } from '@/database/models/taskTopic';
+import { TopicModel } from '@/database/models/topic';
+import { tasks, topics, trashItems, users } from '@/database/schemas';
+import type { LobeChatDatabase } from '@/database/type';
+import { TaskService } from '@/server/services/task';
+import { TaskBatchService } from '@/server/services/task/batch';
+
+import { TrashService } from '../index';
+
+vi.mock('@/server/utils/scheduleAfterResponse', () => ({ after: vi.fn() }));
+vi.mock('@/server/services/file', () => ({
+ FileService: vi.fn().mockImplementation(() => ({ deleteFile: vi.fn(), deleteFiles: vi.fn() })),
+}));
+
+const userId = 'trash-task-user';
+
+// Module-level: the first call migrates a fresh database, which can outlast a
+// hook timeout on a loaded CI shard.
+const db: LobeChatDatabase = await getTestDB();
+
+describe('TrashService — tasks', () => {
+ let taskModel: TaskModel;
+ let trash: TrashService;
+
+ beforeEach(async () => {
+ await db.delete(users).where(eq(users.id, userId));
+ await db.insert(users).values({ id: userId });
+ taskModel = new TaskModel(db, userId);
+ trash = new TrashService(db, userId);
+ });
+
+ afterEach(async () => {
+ await db.delete(users).where(eq(users.id, userId));
+ });
+
+ const createTask = (data: Record<string, unknown> = {}) =>
+ taskModel.create({ instruction: 'Do the thing', name: 'Write report', ...data });
+
+ /** A task with one linked topic (a past run). */
+ const createTaskWithTopic = async () => {
+ const task = await createTask();
+ const topic = await new TopicModel(db, userId).create({ title: 'Run 1' });
+ await new TaskTopicModel(db, userId).add(task.id, topic.id, { seq: 1 });
+ return { task, topic };
+ };
+
+ const rootOf = async (taskId: string) => {
+ const { items } = await trash.list({ resourceType: 'task' });
+ return items.find((item) => item.resourceId === taskId);
+ };
+
+ const rawTask = async (id: string) => (await db.select().from(tasks).where(eq(tasks.id, id)))[0];
+ const rawTopic = async (id: string) =>
+ (await db.select().from(topics).where(eq(topics.id, id)))[0];
+
+ it('a batch delete moves tasks into the bin with their topics, and restore brings both back', async () => {
+ const { task, topic } = await createTaskWithTopic();
+
+ const result = await new TaskBatchService(db, userId).delete([task.id]);
+ expect(result.updated).toEqual([task.id]);
+
+ // Hidden from reads, but the rows are still there, stamped.
+ expect(await taskModel.findById(task.id)).toBeNull();
+ expect((await rawTask(task.id))?.isDeleted).toBe(true);
+ expect(await new TopicModel(db, userId).findById(topic.id)).toBeUndefined();
+ expect((await rawTopic(topic.id))?.isDeleted).toBe(true);
+
+ const root = await rootOf(task.id);
+ expect(root).toMatchObject({
+ meta: expect.objectContaining({ childCount: 1, kind: task.identifier }),
+ resourceType: 'task',
+ title: 'Write report',
+ });
+ // The topic is registered under the task, never listed on its own.
+ const { items: topicRoots } = await trash.list({ resourceType: 'topic' });
+ expect(topicRoots.some((item) => item.resourceId === topic.id)).toBe(false);
+
+ const outcome = await trash.restore([root!.id]);
+ expect(outcome.failed).toEqual([]);
+ expect(await taskModel.findById(task.id)).not.toBeNull();
+ expect(await new TopicModel(db, userId).findById(topic.id)).toBeDefined();
+ expect(await rootOf(task.id)).toBeUndefined();
+ });
+
+ it('the single-task delete goes to the bin too', async () => {
+ const { task, topic } = await createTaskWithTopic();
+
+ await new TaskService(db, userId).deleteTask(task.id);
+
+ expect(await taskModel.findById(task.id)).toBeNull();
+ expect((await rawTopic(topic.id))?.isDeleted).toBe(true);
+ expect(await rootOf(task.id)).toMatchObject({
+ meta: expect.objectContaining({ childCount: 1 }),
+ });
+ });
+
+ it('keeps subtasks live while the parent is in the bin, and blocks restoring a trashed subtask first', async () => {
+ const parent = await createTask({ name: 'Parent' });
+ const child = await createTask({ name: 'Child', parentTaskId: parent.id });
+ const other = await createTask({ name: 'Other child', parentTaskId: parent.id });
+
+ await new TaskBatchService(db, userId).delete([parent.id, child.id]);
+
+ // Not cascaded: the untouched subtask stays visible, still pointing at its parent.
+ expect(await taskModel.findById(other.id)).toMatchObject({ parentTaskId: parent.id });
+
+ const childRoot = await rootOf(child.id);
+ const parentRoot = await rootOf(parent.id);
+ expect((await trash.restore([childRoot!.id])).failed).toEqual([
+ { code: 'parentTrashed', id: childRoot!.id },
+ ]);
+
+ // Restoring both in one call works whichever order the registry hands them over.
+ const outcome = await trash.restore([childRoot!.id, parentRoot!.id]);
+ expect(outcome.failed).toEqual([]);
+ expect(await taskModel.findById(child.id)).toMatchObject({ parentTaskId: parent.id });
+ });
+
+ it('stops a trashed dependency from blocking its dependents', async () => {
+ const blocker = await createTask({ name: 'Blocker' });
+ const dependent = await createTask({ name: 'Dependent' });
+ await taskModel.addDependency(dependent.id, blocker.id);
+ expect(await taskModel.areAllDependenciesCompleted(dependent.id)).toBe(false);
+
+ await new TaskBatchService(db, userId).delete([blocker.id]);
+ expect(await taskModel.areAllDependenciesCompleted(dependent.id)).toBe(true);
+
+ // Restored, it blocks again: the dependency row survived in the bin.
+ await trash.restore([(await rootOf(blocker.id))!.id]);
+ expect(await taskModel.areAllDependenciesCompleted(dependent.id)).toBe(false);
+ });
+
+ it('purge removes the task and its topics for good, and frees its subtasks', async () => {
+ const { task, topic } = await createTaskWithTopic();
+ const child = await createTask({ name: 'Child', parentTaskId: task.id });
+ await new TaskBatchService(db, userId).delete([task.id]);
+ const root = await rootOf(task.id);
+
+ const outcome = await trash.purge([root!.id]);
+
+ expect(outcome.purged).toBe(1);
+ expect(await rawTask(task.id)).toBeUndefined();
+ expect(await rawTopic(topic.id)).toBeUndefined();
+ expect(await taskModel.findById(child.id)).toMatchObject({ parentTaskId: null });
+ expect(
+ await db
+ .select()
+ .from(trashItems)
+ .where(inArray(trashItems.resourceId, [task.id, topic.id])),
+ ).toEqual([]);
+ });
+
+ it('keeps a topic trashed on its own as its own root', async () => {
+ const { task, topic } = await createTaskWithTopic();
+ await trash.trashTopics([topic.id]);
+
+ await new TaskBatchService(db, userId).delete([task.id]);
+
+ expect(await rootOf(task.id)).toMatchObject({
+ meta: expect.objectContaining({ childCount: 0 }),
+ });
+ const { items } = await trash.list({ resourceType: 'topic' });
+ expect(items.some((item) => item.resourceId === topic.id)).toBe(true);
+ });
+
+ it('hides a trashed task from recents, the home brief feed and the scheduler', async () => {
+ const task = await createTask({
+ automationMode: 'schedule',
+ name: 'Nightly digest',
+ schedulePattern: '0 2 * * *',
+ });
+ await new BriefModel(db, userId).create({
+ summary: 'Ready for review',
+ taskId: task.id,
+ title: 'Digest',
+ type: 'decision',
+ });
+ const recents = () => new RecentModel(db, userId).queryRecent(20, ['task']);
+ const feed = () => new BriefModel(db, userId).listUnresolvedEnriched();
+ const scheduled = async () =>
+ (await TaskModel.getScheduledTasks(db)).filter((t) => t.id === task.id);
+ expect((await recents()).some((item) => item.id === task.id)).toBe(true);
+ expect((await feed()).some((row) => row.brief.taskId === task.id)).toBe(true);
+ expect(await scheduled()).toHaveLength(1);
+
+ await new TaskBatchService(db, userId).delete([task.id]);
+
+ expect((await recents()).some((item) => item.id === task.id)).toBe(false);
+ expect((await feed()).some((row) => row.brief.taskId === task.id)).toBe(false);
+ // Its status is untouched in the bin, so the schedule filter alone must not pick it.
+ expect(await scheduled()).toHaveLength(0);
+
+ await trash.restore([(await rootOf(task.id))!.id]);
+ expect((await recents()).some((item) => item.id === task.id)).toBe(true);
+ expect(await scheduled()).toHaveLength(1);
+ });
+});
diff --git a/apps/server/src/services/trash/handlers/index.ts b/apps/server/src/services/trash/handlers/index.ts
index 978f90b9a33..8992f7e50fc 100644
--- a/apps/server/src/services/trash/handlers/index.ts
+++ b/apps/server/src/services/trash/handlers/index.ts
@@ -5,6 +5,7 @@ import { channelHandler } from './channel';
import { channelThreadHandler } from './channelThread';
import { dashboardHandler } from './dashboard';
import { messageHandler } from './message';
+import { taskHandler } from './task';
import { topicHandler } from './topic';
import type { TrashHandler } from './types';
import { widgetHandler } from './widget';
@@ -23,6 +24,7 @@ export const TRASH_HANDLERS: Partial<Record<TrashResourceType, TrashHandler>> =
channelThread: channelThreadHandler,
message: messageHandler,
dashboard: dashboardHandler,
+ task: taskHandler,
topic: topicHandler,
widget: widgetHandler,
};
@@ -40,5 +42,6 @@ export const resolveTrashHandler = (resourceType: TrashResourceType): TrashHandl
export { softDeleteAgent } from './agent';
export { softDeleteMessages } from './message';
+export { softDeleteTasks, type TaskTrashTarget } from './task';
export { topicCascades } from './topic';
export * from './types';
diff --git a/apps/server/src/services/trash/handlers/task.ts b/apps/server/src/services/trash/handlers/task.ts
new file mode 100644
index 00000000000..78f66836cbc
--- /dev/null
+++ b/apps/server/src/services/trash/handlers/task.ts
@@ -0,0 +1,116 @@
+import type { TaskItem } from '@lobechat/types';
+
+import { TaskModel } from '@/database/models/task';
+import { TopicModel } from '@/database/models/topic';
+import type { TrashRegisterEntry } from '@/database/models/trash';
+import type { SoftDeleteOptions } from '@/database/utils/softDelete';
+
+import { topicEntry } from './topic';
+import {
+ type TrashCascade,
+ type TrashHandler,
+ type TrashHandlerContext,
+ TrashRestoreError,
+} from './types';
+
+export const taskEntry = (task: TaskItem, childCount: number): TrashRegisterEntry => ({
+ // `kind` carries the identifier so the bin can show "T-12 · name".
+ meta: { childCount, kind: task.identifier },
+ projectId: task.projectId ?? null,
+ resourceId: task.id,
+ resourceType: 'task',
+ title: task.name || task.identifier,
+});
+
+export interface TaskTrashTarget {
+ /** The status the caller decided on; a task that moved on since is left alone. */
+ status: string;
+ taskId: string;
+ /** Topics linked to the task, as read under the caller's row lock. */
+ topicIds: string[];
+}
+
+/**
+ * Trash tasks with the cascade the hard delete had: each task's linked topics
+ * (which have no FK back to the task and would otherwise linger in the
+ * sidebar) go into the bin with it, registered as its children so a restore
+ * brings the conversations back too. Subtasks are not cascaded — they stay
+ * live and list as top-level rows while the parent is in the bin.
+ *
+ * Runs inside the caller's transaction, after it has taken the tasks' row
+ * locks, so no run can record a topic between the snapshot and the stamp.
+ * Returns one cascade per task actually stamped (the status CAS held).
+ */
+export const softDeleteTasks = async (
+ ctx: Pick<TrashHandlerContext, 'db' | 'userId' | 'workspaceId'>,
+ targets: TaskTrashTarget[],
+ options: SoftDeleteOptions,
+): Promise<TrashCascade[]> => {
+ if (targets.length === 0) return [];
+ const stamped = await new TaskModel(ctx.db, ctx.userId, ctx.workspaceId).softDeleteIfStatusForIds(
+ targets.map(({ status, taskId }) => ({ id: taskId, status })),
+ options,
+ );
+ if (stamped.length === 0) return [];
+
+ const topicIdsByTask = new Map(targets.map((target) => [target.taskId, target.topicIds]));
+ // A topic already in the bin keeps its own root (`softDelete` skips it).
+ const topics = await new TopicModel(ctx.db, ctx.userId, ctx.workspaceId).softDelete(
+ stamped.flatMap((task) => topicIdsByTask.get(task.id) ?? []),
+ { deletedAt: options.deletedAt },
+ );
+ const topicsById = new Map(topics.map((topic) => [topic.id, topic]));
+
+ return stamped.map((task) => {
+ const children = (topicIdsByTask.get(task.id) ?? [])
+ .map((id) => topicsById.get(id))
+ .filter((topic) => !!topic)
+ .map((topic) => topicEntry(topic));
+ return { children, root: taskEntry(task, children.length) };
+ });
+};
+
+export const taskHandler: TrashHandler = {
+ /**
+ * One transaction: the task row and its registered topics go together, and
+ * a restore that won the race (nothing left stamped) keeps both.
+ */
+ purge: async (ctx, root, children) => {
+ await ctx.db.transaction(async (tx) => {
+ const db = tx as unknown as typeof ctx.db;
+ // FK cascades take dependencies, comments, documents and `task_topics`;
+ // subtasks get `parent_task_id = NULL`, as the hard delete always did.
+ const purged = await new TaskModel(db, ctx.userId, ctx.workspaceId).purge([root.resourceId]);
+ if (purged.length === 0) return;
+
+ const topicIds = children
+ .filter((child) => child.resourceType === 'topic')
+ .map((child) => child.resourceId);
+ if (topicIds.length > 0) {
+ await new TopicModel(db, ctx.userId, ctx.workspaceId).batchDeleteIncludingTrashed(topicIds);
+ }
+ });
+ },
+ restore: async (ctx, root, children) => {
+ const taskModel = new TaskModel(ctx.db, ctx.userId, ctx.workspaceId);
+ const [task] = await taskModel.findTrashedByIds([root.resourceId]);
+ if (!task) throw new TrashRestoreError('notFound');
+
+ // A subtask whose parent is itself in the bin would come back under an
+ // invisible parent: restore the parent first.
+ if (task.parentTaskId && (await taskModel.findTrashedIds([task.parentTaskId])).length > 0) {
+ throw new TrashRestoreError('parentTrashed');
+ }
+
+ // Only a row this update actually brought back counts (a purge may have
+ // won between the read above and here).
+ const restored = await taskModel.restore([root.resourceId]);
+ if (restored.length === 0) throw new TrashRestoreError('notFound');
+
+ const topicIds = children
+ .filter((child) => child.resourceType === 'topic')
+ .map((child) => child.resourceId);
+ await new TopicModel(ctx.db, ctx.userId, ctx.workspaceId).restore(topicIds);
+ },
+ type: 'task',
+};
diff --git a/apps/server/src/services/trash/index.ts b/apps/server/src/services/trash/index.ts
index 086efe74fa4..f0fad94aef7 100644
--- a/apps/server/src/services/trash/index.ts
+++ b/apps/server/src/services/trash/index.ts
@@ -12,7 +12,7 @@ import debug from 'debug';
import { TopicModel } from '@/database/models/topic';
import { TrashModel } from '@/database/models/trash';
import type { TrashItemRow } from '@/database/schemas';
-import type { LobeChatDatabase } from '@/database/type';
+import type { LobeChatDatabase, Transaction } from '@/database/type';
import type { SoftDeleteOptions } from '@/database/utils/softDelete';
import { FileService } from '@/server/services/file';
@@ -20,6 +20,8 @@ import {
resolveTrashHandler,
softDeleteAgent,
softDeleteMessages,
+ softDeleteTasks,
+ type TaskTrashTarget,
topicCascades,
type TrashCascade,
type TrashHandlerContext,
@@ -56,6 +58,33 @@ export interface TrashSweepOutcome {
purged: number;
}
+/**
+ * Trash tasks inside a transaction the caller already holds — the task delete
+ * paths decide under their own row locks (a run recording a topic takes the
+ * same lock) and must stamp + register before releasing them. Returns the ids
+ * actually moved to the bin; a task whose status changed since the caller
+ * decided is not among them.
+ */
+export const trashTasksInTransaction = async (
+ tx: Transaction,
+ scope: { userId: string; workspaceId?: string },
+ targets: TaskTrashTarget[],
+): Promise<string[]> => {
+ const db = tx as unknown as LobeChatDatabase;
+ const deletedAt = new Date();
+ const cascades = await softDeleteTasks(
+ { db, userId: scope.userId, workspaceId: scope.workspaceId },
+ targets,
+ { deletedAt },
+ );
+ await new TrashModel(db, scope.userId, scope.workspaceId).registerMany(
+ { cascades, deletedAt },
+ tx,
+ );
+ log('trashed %d task(s)', cascades.length);
+ return cascades.map((cascade) => cascade.root.resourceId);
+};
+
/**
* Recycle-bin orchestrator. Every user-facing "delete" of a trash-aware entity
* funnels through `trashXxx` here: the handler stamps the rows (and their
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index efa3c9b3dbc..665ad31e2c5 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -2475,7 +2475,7 @@
"taskDetail.comment.edit": "Edit",
"taskDetail.comment.save": "Save",
"taskDetail.commentPlaceholder": "Leave a comment, or @ a teammate — comments also guide the next run...",
- "taskDetail.deleteConfirm.content": "This action cannot be undone.",
+ "taskDetail.deleteConfirm.content": "The task moves to the trash with its runs and can be restored within 30 days.",
"taskDetail.deleteConfirm.ok": "Delete",
"taskDetail.deleteConfirm.title": "Delete this task?",
"taskDetail.followUpFailed": "Couldn’t send the follow-up. Your message is kept — try again.",
@@ -2665,7 +2665,7 @@
"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.content": "Deleted tasks move to the trash with their comments and runs and can be restored within 30 days; their subtasks stay in the list. Running tasks are stopped first.",
"taskList.bulk.deleteConfirm.ok": "Delete",
"taskList.bulk.deleteConfirm.othersWarning_one": "{{count}} of these tasks was created by another workspace member. Deleting it removes it for everyone.",
"taskList.bulk.deleteConfirm.othersWarning_other": "{{count}} of these tasks were created by other workspace members. Deleting them removes them for everyone.",
@@ -2678,8 +2678,8 @@
"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.deleted_one": "{{count}} task moved to the trash",
+ "taskList.bulk.result.deleted_other": "{{count}} tasks moved to the trash",
"taskList.bulk.result.error": "The batch action failed. Try again.",
"taskList.bulk.result.failed_one": "{{count}} failed",
"taskList.bulk.result.failed_other": "{{count}} failed",
@@ -2698,6 +2698,12 @@
"taskList.bulk.unarchive": "Unarchive",
"taskList.bulk.unassignAgent": "No agent",
"taskList.bulk.unassignMember": "Unassign member",
+ "taskList.bulk.undo.action": "Undo",
+ "taskList.bulk.undo.conflict_one": "{{count}} changed since, left as is",
+ "taskList.bulk.undo.conflict_other": "{{count}} changed since, left as is",
+ "taskList.bulk.undo.done_one": "Undid {{count}} task",
+ "taskList.bulk.undo.done_other": "Undid {{count}} tasks",
+ "taskList.bulk.undo.error": "Could not undo. Try again.",
"taskList.completedTasks.all": "All",
"taskList.completedTasks.day": "Past day",
"taskList.completedTasks.month": "Past month",
diff --git a/locales/en-US/setting.json b/locales/en-US/setting.json
index 371238a3e7b..936568d1749 100644
--- a/locales/en-US/setting.json
+++ b/locales/en-US/setting.json
@@ -2309,6 +2309,7 @@
"trash.type.channelThread": "Channel thread",
"trash.type.dashboard": "Dashboard",
"trash.type.message": "Message",
+ "trash.type.task": "Task",
"trash.type.topic": "Topic",
"trash.type.widget": "Widget",
"trash.untitled": "Untitled",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index f189680f118..4a835797dfc 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -2475,7 +2475,7 @@
"taskDetail.comment.edit": "编辑",
"taskDetail.comment.save": "保存",
"taskDetail.commentPlaceholder": "留下评论,输入 @ 可提及成员,评论也会引导下次运行...",
- "taskDetail.deleteConfirm.content": "此操作不可撤销。",
+ "taskDetail.deleteConfirm.content": "任务及其运行记录会移入回收站,30 天内可以恢复。",
"taskDetail.deleteConfirm.ok": "删除",
"taskDetail.deleteConfirm.title": "确认删除此任务?",
"taskDetail.followUpFailed": "追问未发送成功,内容已保留,请重试。",
@@ -2665,7 +2665,7 @@
"taskList.bulk.count_one": "{{count}} 个任务",
"taskList.bulk.count_other": "{{count}} 个任务",
"taskList.bulk.delete": "删除…",
- "taskList.bulk.deleteConfirm.content": "删除后,任务及其评论和运行记录无法恢复,子任务会保留为顶层任务。运行中的任务会先被停止。",
+ "taskList.bulk.deleteConfirm.content": "删除的任务连同评论和运行记录会移入回收站,30 天内可以恢复;子任务仍保留在列表中。运行中的任务会先被停止。",
"taskList.bulk.deleteConfirm.ok": "删除",
"taskList.bulk.deleteConfirm.othersWarning_one": "其中 {{count}} 个任务由其他成员创建,删除后所有成员都将无法再看到。",
"taskList.bulk.deleteConfirm.othersWarning_other": "其中 {{count}} 个任务由其他成员创建,删除后所有成员都将无法再看到。",
@@ -2678,8 +2678,8 @@
"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.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}} 个失败",
@@ -2698,6 +2698,12 @@
"taskList.bulk.unarchive": "取消归档",
"taskList.bulk.unassignAgent": "不指派助理",
"taskList.bulk.unassignMember": "取消指派成员",
+ "taskList.bulk.undo.action": "撤销",
+ "taskList.bulk.undo.conflict_one": "{{count}} 个已被再次修改,未撤销",
+ "taskList.bulk.undo.conflict_other": "{{count}} 个已被再次修改,未撤销",
+ "taskList.bulk.undo.done_one": "已撤销 {{count}} 个任务",
+ "taskList.bulk.undo.done_other": "已撤销 {{count}} 个任务",
+ "taskList.bulk.undo.error": "撤销失败,请重试。",
"taskList.completedTasks.all": "全部",
"taskList.completedTasks.day": "过去一天",
"taskList.completedTasks.month": "过去一个月",
diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.json
index b1a9cb24cb3..2dc9ad293b9 100644
--- a/locales/zh-CN/setting.json
+++ b/locales/zh-CN/setting.json
@@ -2309,6 +2309,7 @@
"trash.type.channelThread": "频道线程",
"trash.type.dashboard": "看板",
"trash.type.message": "消息",
+ "trash.type.task": "任务",
"trash.type.topic": "话题",
"trash.type.widget": "小组件",
"trash.untitled": "未命名",
diff --git a/packages/builtin-tool-task/src/manifest.ts b/packages/builtin-tool-task/src/manifest.ts
index df049282fd2..2ecc7692918 100644
--- a/packages/builtin-tool-task/src/manifest.ts
+++ b/packages/builtin-tool-task/src/manifest.ts
@@ -527,7 +527,7 @@ export const TaskManifest: BuiltinToolManifest = {
},
{
description:
- 'Permanently delete a task by identifier. Subtasks are NOT cascaded — they become top-level tasks after deletion. Dependencies, topics, pinned documents, comments, and briefs attached to the task are cascade-deleted. This action is irreversible.',
+ 'Delete a task by identifier. The task moves to the recycle bin together with its topics, and the user can restore it within 30 days; it is removed for good when the bin is emptied or the retention window ends. Subtasks are NOT cascaded — they stay in the list. A dependency on the deleted task stops blocking its dependents.',
name: TaskApiName.deleteTask,
parameters: {
properties: {
diff --git a/packages/builtin-tool-task/src/systemRole.ts b/packages/builtin-tool-task/src/systemRole.ts
index 8f7933e6007..34eea68b061 100644
--- a/packages/builtin-tool-task/src/systemRole.ts
+++ b/packages/builtin-tool-task/src/systemRole.ts
@@ -12,7 +12,7 @@ export const systemPrompt = `You have access to Task management tools. Use them
- **runTask**: Actually START a task — kicks off the assigned agent in a new (or continued) topic. Use this to launch execution; do NOT use updateTaskStatus(running) to start a task, that only flips a flag without executing. The task must have an assigneeAgentId
- **runTasks**: Start multiple tasks in one call. Prefer this when launching a batch of related subtasks (e.g. all subtasks you just created); cuts down on tool calls and makes the start atomic from the user's perspective
- **updateTaskStatus**: Change a task's status. If you mark a task as failed, include an error message explaining why. Use this to mark tasks completed/cancelled/paused/failed — NOT to start them (use runTask for that). Omitting identifier only works when there is a current task context
-- **deleteTask**: Delete a task. Subtasks become top-level (not cascaded); dependencies/topics/comments cascade-delete; irreversible. The freed identifier (e.g. "T-9") can be reused by a later task — use the stable id returned by createTask/listTasks in subsequent calls. User-provided identifiers remain accepted
+- **deleteTask**: Delete a task. It moves to the recycle bin with its topics (the user can restore it within 30 days); subtasks are not cascaded and stay in the list; a dependency on it stops blocking. Its identifier (e.g. "T-9") stays reserved while it is in the bin — use the stable id returned by createTask/listTasks in subsequent calls. User-provided identifiers remain accepted
Task links: Use the display identifier in user-facing URLs, e.g. /task/T-3. Keep stable task ids for subsequent tool calls and internal references.
diff --git a/packages/database/src/models/brief.ts b/packages/database/src/models/brief.ts
index bc44da91d74..6b61d31c83b 100644
--- a/packages/database/src/models/brief.ts
+++ b/packages/database/src/models/brief.ts
@@ -6,6 +6,7 @@ import type { BriefItem, NewBrief } from '../schemas/task';
import { briefs, tasks } from '../schemas/task';
import type { LobeChatDatabase } from '../type';
import { normalizeInboxAgentAvatar, normalizeInboxAgentTitle } from '../utils/inboxAgent';
+import { notTrashed } from '../utils/softDelete';
import { buildWorkspacePayload } from '../utils/workspace';
export interface UnresolvedBriefRow {
@@ -110,6 +111,9 @@ export class BriefModel {
this.ownership(),
isNull(briefs.resolvedAt),
notInArray(briefs.type, HOME_FEED_EXCLUDED_BRIEF_TYPES),
+ // Briefs hide with their task while it sits in the recycle bin
+ // (a brief without a task joins NULL, which passes).
+ notTrashed(tasks.isDeleted),
),
)
.orderBy(
@@ -152,6 +156,7 @@ export class BriefModel {
and(
this.ownership(),
inArray(briefs.type, NEWS_BRIEF_TYPES),
+ notTrashed(tasks.isDeleted),
gte(briefs.createdAt, startAt),
lt(briefs.createdAt, endAt),
),
diff --git a/packages/database/src/models/recent.ts b/packages/database/src/models/recent.ts
index f003b3b9634..d97dad11ae3 100644
--- a/packages/database/src/models/recent.ts
+++ b/packages/database/src/models/recent.ts
@@ -14,6 +14,7 @@ import {
} from '../schemas';
import type { LobeChatDatabase } from '../type';
import { notShareVisitorTopic } from '../utils/shareVisitor';
+import { notTrashed } from '../utils/softDelete';
import { CHANNEL_TOPIC_TRIGGER } from '../utils/topicVisibility';
import { buildWorkspaceWhere } from '../utils/workspace';
@@ -117,9 +118,14 @@ export class RecentModel {
// `tasks` uses `createdByUserId` instead of `userId`, so apply the
// workspace-aware predicate inline.
- const taskScopeWhere = this.workspaceId
- ? eq(tasks.workspaceId, this.workspaceId)
- : and(eq(tasks.createdByUserId, this.userId), isNull(tasks.workspaceId));
+ // Hand-built (it bypasses `buildWorkspaceWhere`), so the recycle-bin
+ // filter the other arms get from that funnel is added here explicitly.
+ const taskScopeWhere = and(
+ this.workspaceId
+ ? eq(tasks.workspaceId, this.workspaceId)
+ : and(eq(tasks.createdByUserId, this.userId), isNull(tasks.workspaceId)),
+ notTrashed(tasks.isDeleted),
+ );
// Workspace rows are shared across members; `mineOnly` narrows a workspace
// feed back to the viewer's own items. A no-op in personal mode, where the
diff --git a/packages/database/src/models/task/dependencies.ts b/packages/database/src/models/task/dependencies.ts
index 6479b089fa6..94f046b7773 100644
--- a/packages/database/src/models/task/dependencies.ts
+++ b/packages/database/src/models/task/dependencies.ts
@@ -2,6 +2,7 @@ import type { TaskItem } from '@lobechat/types';
import { and, eq, inArray, ne, sql } from 'drizzle-orm';
import { taskDependencies, tasks } from '../../schemas/task';
+import { notTrashed } from '../../utils/softDelete';
import { depsOwnership, type TaskModelContext, taskOwnership } from './context';
export const removeDependency = async (
@@ -56,6 +57,9 @@ export const areAllDependenciesCompleted = async (
eq(taskDependencies.taskId, taskId),
eq(taskDependencies.type, 'blocks'),
ne(tasks.status, 'completed'),
+ // A dependency sitting in the recycle bin no longer blocks: it is
+ // treated as removed, the way the hard delete's FK cascade removed it.
+ notTrashed(tasks.isDeleted),
depsOwnership(ctx),
),
);
@@ -98,6 +102,9 @@ export const getUnlockedTasksForMany = async (
inArray(taskDependencies.taskId, dependentIds),
eq(taskDependencies.type, 'blocks'),
ne(tasks.status, 'completed'),
+ // A dependency sitting in the recycle bin no longer blocks: it is
+ // treated as removed, the way the hard delete's FK cascade removed it.
+ notTrashed(tasks.isDeleted),
depsOwnership(ctx),
),
);
diff --git a/packages/database/src/models/task/index.ts b/packages/database/src/models/task/index.ts
index cc9fe5a0887..bdf8d3ff846 100644
--- a/packages/database/src/models/task/index.ts
+++ b/packages/database/src/models/task/index.ts
@@ -19,6 +19,7 @@ import type {
} from '../../schemas/task';
import { taskDependencies, tasks } from '../../schemas/task';
import type { LobeChatDatabase } from '../../type';
+import type { SoftDeleteOptions } from '../../utils/softDelete';
import { ProjectModel } from '../project';
import type { TaskListFilterOptions, TaskListOptions } from '../taskListFilters';
import * as activities from './activities';
@@ -34,6 +35,7 @@ import * as rows from './rows';
import type { InterruptedRunningTopic, OrphanedRunningTopic } from './scheduling';
import * as scheduling from './scheduling';
import * as transfer from './transfer';
+import * as trash from './trash';
import * as tree from './tree';
import {
DEFAULT_TASK_IDENTIFIER_PREFIX,
@@ -216,6 +218,31 @@ export class TaskModel {
return rows.deleteIfStatusForIds(this.ctx, expected);
}
+ // ── Recycle bin (see `./trash.ts`; driven by the server's task trash handler) ──
+
+ async softDeleteIfStatusForIds(
+ expected: { id: string; status: string }[],
+ options: SoftDeleteOptions,
+ ): Promise<TaskItem[]> {
+ return trash.softDeleteIfStatusForIds(this.ctx, expected, options);
+ }
+
+ async restore(ids: string[]): Promise<TaskItem[]> {
+ return trash.restore(this.ctx, ids);
+ }
+
+ async findTrashedByIds(ids: string[]): Promise<TaskItem[]> {
+ return trash.findTrashedByIds(this.ctx, ids);
+ }
+
+ async findTrashedIds(ids: string[]): Promise<string[]> {
+ return trash.findTrashedIds(this.ctx, ids);
+ }
+
+ async purge(ids: string[]): Promise<string[]> {
+ return trash.purge(this.ctx, ids);
+ }
+
async deleteAll(options?: { restrictToCreator?: boolean }): Promise<number> {
return rows.deleteAll(this.ctx, options);
}
diff --git a/packages/database/src/models/task/scheduling.ts b/packages/database/src/models/task/scheduling.ts
index 7754e96239f..6dd39013271 100644
--- a/packages/database/src/models/task/scheduling.ts
+++ b/packages/database/src/models/task/scheduling.ts
@@ -6,6 +6,7 @@ import type { AgentOperationError } from '../../schemas/agentOperations';
import { agentOperations } from '../../schemas/agentOperations';
import { tasks, taskTopics } from '../../schemas/task';
import type { LobeChatDatabase } from '../../type';
+import { notTrashed } from '../../utils/softDelete';
/**
* Operation outcomes the orphaned-run reconciliation settles.
@@ -47,6 +48,8 @@ export const getScheduledTasks = async (db: LobeChatDatabase): Promise<TaskItem[
and(
eq(tasks.automationMode, 'schedule'),
isNotNull(tasks.schedulePattern),
+ // A task in the recycle bin keeps its status; its schedule must not fire.
+ notTrashed(tasks.isDeleted),
notInArray(tasks.status, ['canceled', 'completed', 'failed', 'paused', 'running']),
),
);
@@ -92,6 +95,7 @@ export const findStuckTasks = async (db: LobeChatDatabase): Promise<TaskItem[]>
.where(
and(
eq(tasks.status, 'running'),
+ notTrashed(tasks.isDeleted),
isNotNull(tasks.lastHeartbeatAt),
isNotNull(tasks.heartbeatTimeout),
sql`${tasks.lastHeartbeatAt} < now() - make_interval(secs => ${tasks.heartbeatTimeout})`,
diff --git a/packages/database/src/models/task/trash.ts b/packages/database/src/models/task/trash.ts
new file mode 100644
index 00000000000..d0f1c3df69c
--- /dev/null
+++ b/packages/database/src/models/task/trash.ts
@@ -0,0 +1,111 @@
+import type { TaskItem } from '@lobechat/types';
+import { and, eq, inArray, or, type SQL } from 'drizzle-orm';
+
+import { tasks } from '../../schemas/task';
+import {
+ isTrashed,
+ restoreStamp,
+ type SoftDeleteOptions,
+ trashStamp,
+} from '../../utils/softDelete';
+import { buildWorkspaceWhere } from '../../utils/workspace';
+import type { TaskModelContext } from './context';
+
+/**
+ * `taskOwnership` without the recycle-bin filter — the scope restore / purge
+ * internals run in, so a trashed row is reachable. Visibility still applies:
+ * a member can only bring back (or purge) a task they could see.
+ */
+export const taskTrashScope = (ctx: TaskModelContext): SQL =>
+ buildWorkspaceWhere(
+ { userId: ctx.userId, workspaceId: ctx.workspaceId },
+ {
+ userId: tasks.createdByUserId,
+ visibility: tasks.visibility,
+ workspaceId: tasks.workspaceId,
+ },
+ );
+
+/**
+ * Move tasks to the recycle bin with the same compare-and-set the hard delete
+ * used: a row is stamped only while its status is still the one the caller
+ * decided on, so a run that moved it on in the meantime wins. Rows already
+ * trashed (or not visible) are left alone. Briefs, comments, dependencies and
+ * documents are not stamped — they hide with the task and hard-cascade at
+ * purge time. Subtasks are not cascaded: they stay live and list as top-level
+ * rows until their parent comes back.
+ */
+export const softDeleteIfStatusForIds = async (
+ ctx: TaskModelContext,
+ expected: { id: string; status: string }[],
+ options: SoftDeleteOptions,
+): Promise<TaskItem[]> => {
+ if (expected.length === 0) return [];
+ const matches = expected.map(({ id, status }) => and(eq(tasks.id, id), eq(tasks.status, status)));
+ return ctx.db
+ .update(tasks)
+ .set(trashStamp(options.deletedAt))
+ .where(
+ and(
+ or(...matches),
+ // With `isDeleted` the scope carries `is_deleted IS NOT TRUE`: only live rows.
+ buildWorkspaceWhere(
+ { userId: ctx.userId, workspaceId: ctx.workspaceId },
+ {
+ isDeleted: tasks.isDeleted,
+ userId: tasks.createdByUserId,
+ visibility: tasks.visibility,
+ workspaceId: tasks.workspaceId,
+ },
+ ),
+ ),
+ )
+ .returning();
+};
+
+/** Bring trashed tasks back. Only rows currently stamped are touched. */
+export const restore = async (ctx: TaskModelContext, ids: string[]): Promise<TaskItem[]> => {
+ if (ids.length === 0) return [];
+ return ctx.db
+ .update(tasks)
+ .set(restoreStamp())
+ .where(and(inArray(tasks.id, ids), taskTrashScope(ctx), isTrashed(tasks.isDeleted)))
+ .returning();
+};
+
+/** Trashed rows by id, bypassing the recycle-bin filter (restore / purge internals). */
+export const findTrashedByIds = async (
+ ctx: TaskModelContext,
+ ids: string[],
+): Promise<TaskItem[]> => {
+ if (ids.length === 0) return [];
+ return ctx.db
+ .select()
+ .from(tasks)
+ .where(and(inArray(tasks.id, ids), taskTrashScope(ctx), isTrashed(tasks.isDeleted)));
+};
+
+/** Of `ids`, the tasks sitting in the recycle bin (a subtask's restore checks its parent). */
+export const findTrashedIds = async (ctx: TaskModelContext, ids: string[]): Promise<string[]> => {
+ if (ids.length === 0) return [];
+ const rows = await ctx.db
+ .select({ id: tasks.id })
+ .from(tasks)
+ .where(and(inArray(tasks.id, ids), taskTrashScope(ctx), isTrashed(tasks.isDeleted)));
+ return rows.map((row) => row.id);
+};
+
+/**
+ * Hard delete for the purge sweep. Only rows still stamped: a restore that
+ * commits first keeps its task. FK cascades take dependencies, comments,
+ * briefs links and `task_topics`; subtasks keep living — the self FK is
+ * `ON DELETE SET NULL`, the same outcome the hard delete always had.
+ */
+export const purge = async (ctx: TaskModelContext, ids: string[]): Promise<string[]> => {
+ if (ids.length === 0) return [];
+ const deleted = await ctx.db
+ .delete(tasks)
+ .where(and(inArray(tasks.id, ids), taskTrashScope(ctx), isTrashed(tasks.isDeleted)))
+ .returning({ id: tasks.id });
+ return deleted.map((row) => row.id);
+};
diff --git a/packages/database/src/models/trash.ts b/packages/database/src/models/trash.ts
index e0eb08cbf81..21321cd65ce 100644
--- a/packages/database/src/models/trash.ts
+++ b/packages/database/src/models/trash.ts
@@ -21,6 +21,7 @@ import {
dashboards,
messages,
projects,
+ tasks,
topics,
trashItems,
widgets,
@@ -64,6 +65,7 @@ const ROOT_TABLES: Record<TrashResourceType, { id: any; isDeleted: any; table: a
},
dashboard: { id: dashboards.id, isDeleted: dashboards.isDeleted, table: dashboards },
message: { id: messages.id, isDeleted: messages.isDeleted, table: messages },
+ task: { id: tasks.id, isDeleted: tasks.isDeleted, table: tasks },
topic: { id: topics.id, isDeleted: topics.isDeleted, table: topics },
widget: { id: widgets.id, isDeleted: widgets.isDeleted, table: widgets },
};
@@ -126,6 +128,11 @@ const livePrivateWhere = (): SQL =>
eq(trashItems.resourceType, 'message'),
sql`EXISTS (SELECT 1 FROM ${messages} WHERE ${messages.id} = ${trashItems.resourceId} AND (${privateAgent(messages.agentId)} OR ${privateGroup(messages.groupId)} OR ${privateTopic(messages.topicId)}))`,
),
+ // A task is private on its own (`visibility`), or under a private project.
+ and(
+ eq(trashItems.resourceType, 'task'),
+ sql`EXISTS (SELECT 1 FROM ${tasks} WHERE ${tasks.id} = ${trashItems.resourceId} AND (${tasks.visibility} = 'private' OR ${privateProject(tasks.projectId)}))`,
+ ),
and(
eq(trashItems.resourceType, 'widget'),
sql`EXISTS (SELECT 1 FROM ${widgets} WHERE ${widgets.id} = ${uuidResourceId('widget')} AND (${widgets.visibility} = 'private' OR ${privateAgent(widgets.agentId)} OR ${privateProject(widgets.projectId)}))`,
@@ -515,6 +522,25 @@ export class TrashModel {
});
};
+ /** The roots (not cascaded children) registered for these resources of one kind. */
+ findRootsByResources = async (
+ resourceType: TrashResourceType,
+ resourceIds: string[],
+ ): Promise<TrashItemRow[]> => {
+ if (resourceIds.length === 0) return [];
+ return this.db
+ .select()
+ .from(trashItems)
+ .where(
+ and(
+ eq(trashItems.resourceType, resourceType),
+ inArray(trashItems.resourceId, resourceIds),
+ isNull(trashItems.rootId),
+ this.ownership(),
+ ),
+ );
+ };
+
/** Registry rows cascaded under a root (any type). */
findChildren = async (rootId: string, trx?: Transaction): Promise<TrashItemRow[]> => {
const db = trx ?? this.db;
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index 2717496b2f8..a0f42690f89 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -2162,7 +2162,8 @@ export default {
'taskDetail.replyInThread': 'Reply in this thread',
'taskDetail.replyPlaceholder': 'Reply in this thread...',
'taskDetail.sendFollowUp': 'Send follow up message',
- 'taskDetail.deleteConfirm.content': 'This action cannot be undone.',
+ 'taskDetail.deleteConfirm.content':
+ 'The task moves to the trash with its runs and can be restored within 30 days.',
'taskDetail.deleteConfirm.ok': 'Delete',
'taskDetail.deleteConfirm.title': 'Delete this task?',
'taskDetail.instruction': 'Instruction',
@@ -3138,7 +3139,7 @@ export default {
'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.',
+ 'Deleted tasks move to the trash with their comments and runs and can be restored within 30 days; their subtasks stay in the list. Running tasks are stopped first.',
'taskList.bulk.deleteConfirm.ok': 'Delete',
'taskList.bulk.deleteConfirm.othersWarning_one':
'{{count}} of these tasks was created by another workspace member. Deleting it removes it for everyone.',
@@ -3155,8 +3156,8 @@ export default {
'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.deleted_one': '{{count}} task moved to the trash',
+ 'taskList.bulk.result.deleted_other': '{{count}} tasks moved to the trash',
'taskList.bulk.result.error': 'The batch action failed. Try again.',
'taskList.bulk.result.failed_one': '{{count}} failed',
'taskList.bulk.result.failed_other': '{{count}} failed',
@@ -3164,6 +3165,12 @@ export default {
'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.undo.action': 'Undo',
+ 'taskList.bulk.undo.conflict_one': '{{count}} changed since, left as is',
+ 'taskList.bulk.undo.conflict_other': '{{count}} changed since, left as is',
+ 'taskList.bulk.undo.done_one': 'Undid {{count}} task',
+ 'taskList.bulk.undo.done_other': 'Undid {{count}} tasks',
+ 'taskList.bulk.undo.error': 'Could not undo. Try again.',
'taskList.bulk.search.agent': 'Assign to agent…',
'taskList.bulk.search.placeholder': 'Type a command…',
'taskList.bulk.search.priority': 'Set priority…',
diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.ts
index d69e4739bdc..78dab88dc19 100644
--- a/packages/locales/src/default/setting.ts
+++ b/packages/locales/src/default/setting.ts
@@ -2070,6 +2070,7 @@ When I am ___, I need ___
'trash.type.channelThread': 'Channel thread',
'trash.type.dashboard': 'Dashboard',
'trash.type.message': 'Message',
+ 'trash.type.task': 'Task',
'trash.type.topic': 'Topic',
'trash.type.widget': 'Widget',
'trash.untitled': 'Untitled',
diff --git a/packages/types/src/trash.ts b/packages/types/src/trash.ts
index 3d99c5444d5..5a4234c4b0d 100644
--- a/packages/types/src/trash.ts
+++ b/packages/types/src/trash.ts
@@ -23,6 +23,7 @@ export const TRASH_RESOURCE_TYPES = [
'dashboard',
'channel',
'channelThread',
+ 'task',
] as const;
export type TrashResourceType = (typeof TRASH_RESOURCE_TYPES)[number];
diff --git a/src/features/AgentTasks/AgentTaskList/TaskList.tsx b/src/features/AgentTasks/AgentTaskList/TaskList.tsx
index ca1f232aeb2..2a0d1d565f6 100644
--- a/src/features/AgentTasks/AgentTaskList/TaskList.tsx
+++ b/src/features/AgentTasks/AgentTaskList/TaskList.tsx
@@ -47,6 +47,7 @@ import SelectableTaskRow, { selectableTaskItemClassName } from './selection/Sele
import { useTaskSelectionStore } from './selection/store';
import TaskBulkActionBar from './selection/TaskBulkActionBar';
import { isEditableTarget } from './selection/taskSelectionModel';
+import { useTaskBatchUndo } from './selection/undo/useTaskBatchUndo';
import { useSelectionScope } from './selection/useSelectionScope';
import TaskGroupLabel from './TaskGroupLabel';
import TaskItemSkeleton from './TaskItemSkeleton';
@@ -350,6 +351,11 @@ const TaskList = memo<TaskListProps>((props) => {
}, [selectableIds]);
const selectionScope = props.selectionScope ?? (items ? 'items' : (queryKey ?? ''));
useSelectionScope(selectionScope);
+ const { undoLast } = useTaskBatchUndo();
+ const undoLastRef = useRef(undoLast);
+ useEffect(() => {
+ undoLastRef.current = undoLast;
+ }, [undoLast]);
useEffect(() => {
const onKeyDown = (event: KeyboardEvent) => {
@@ -372,6 +378,17 @@ const TaskList = memo<TaskListProps>((props) => {
selection.selectAll(selectableIdsRef.current);
return;
}
+ // ⌘/Ctrl+Z: undo the most recent batch action (session-wide stack, so it
+ // still works after its toast is gone). Shift+⌘Z is left to the page.
+ if (
+ event.key.toLowerCase() === 'z' &&
+ (event.metaKey || event.ctrlKey) &&
+ !event.shiftKey &&
+ !event.altKey
+ ) {
+ if (undoLastRef.current()) event.preventDefault();
+ return;
+ }
if (event.key === 'Escape' && selection.selectedIds.length > 0 && !selection.progress) {
event.preventDefault();
selection.clear();
diff --git a/src/features/AgentTasks/AgentTaskList/selection/optimisticBatch.test.ts b/src/features/AgentTasks/AgentTaskList/selection/optimisticBatch.test.ts
new file mode 100644
index 00000000000..1759ada6c6d
--- /dev/null
+++ b/src/features/AgentTasks/AgentTaskList/selection/optimisticBatch.test.ts
@@ -0,0 +1,127 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ confirmedTaskPatches,
+ optimisticTaskPatch,
+ optimisticUndoPatch,
+ undoStatus,
+} from './optimisticBatch';
+
+const task = { archivedAt: null, id: 'a', priority: 0, status: 'backlog' } as any;
+const hidesArchived = { includeArchived: false };
+const showsArchived = { includeArchived: true };
+
+describe('optimisticTaskPatch', () => {
+ it('moves the status and stamps the close time on completed / canceled', () => {
+ const completed = optimisticTaskPatch({ kind: 'status', status: 'completed' })(task, {});
+ expect(completed).toMatchObject({ status: 'completed' });
+ expect(completed?.completedAt).toBeInstanceOf(Date);
+ expect(completed?.updatedAt).toBe(completed?.completedAt);
+
+ const paused = optimisticTaskPatch({ kind: 'status', status: 'paused' })(task, {});
+ expect(paused).toMatchObject({ status: 'paused' });
+ expect(paused).not.toHaveProperty('completedAt');
+ expect(paused?.updatedAt).toBeInstanceOf(Date);
+ });
+
+ it('takes a reassigned row out of a collection scoped to its old assignee', () => {
+ const toBeta = optimisticTaskPatch({ kind: 'update', patch: { assigneeAgentId: 'beta' } });
+ const row = { ...task, assigneeAgentId: 'alpha', assigneeUserId: 'me' };
+ expect(toBeta(row, { agentId: 'alpha' })).toBeUndefined();
+ expect(toBeta(row, { agentId: 'beta' })).toMatchObject({ assigneeAgentId: 'beta' });
+ expect(toBeta(row, {})).toMatchObject({ assigneeAgentId: 'beta' });
+
+ const toOther = optimisticTaskPatch({ kind: 'update', patch: { assigneeUserId: 'other' } });
+ expect(toOther(row, { scope: 'assigned' })).toBeUndefined();
+ expect(toOther(row, { scope: 'created' })).toMatchObject({ assigneeUserId: 'other' });
+ // Priority-only edits never move a row out of a scope.
+ const priority = optimisticTaskPatch({ kind: 'update', patch: { priority: 3 } });
+ expect(priority(row, { agentId: 'alpha', scope: 'assigned' })).toMatchObject({ priority: 3 });
+ });
+
+ it('sets only the fields the patch names, null included', () => {
+ const next = optimisticTaskPatch({
+ kind: 'update',
+ patch: { assigneeUserId: null, priority: 2 },
+ })({ ...task, assigneeAgentId: 'agt', assigneeUserId: 'u1' }, {});
+ expect(next).toMatchObject({ assigneeAgentId: 'agt', assigneeUserId: null, priority: 2 });
+ });
+
+ it('takes deleted rows out of every collection', () => {
+ expect(optimisticTaskPatch({ kind: 'delete' })(task, showsArchived)).toBeUndefined();
+ });
+
+ it('archives out of lists that hide archived rows, and marks them where they show', () => {
+ const archive = optimisticTaskPatch({ archived: true, kind: 'archive' });
+ expect(archive(task, hidesArchived)).toBeUndefined();
+ // Unknown collection (persisted, unloaded): left as stored.
+ expect(archive(task, {})).toBe(task);
+ expect(archive(task, showsArchived)?.archivedAt).toBeInstanceOf(Date);
+ expect(
+ optimisticTaskPatch({ archived: false, kind: 'archive' })(
+ { ...task, archivedAt: new Date() },
+ showsArchived,
+ )?.archivedAt,
+ ).toBeNull();
+ });
+});
+
+describe('confirmedTaskPatches', () => {
+ const patch = optimisticTaskPatch({ kind: 'status', status: 'completed' });
+
+ it('keeps only the updated ids', () => {
+ expect([...confirmedTaskPatches(patch, ['a', 'c']).keys()]).toEqual(['a', 'c']);
+ });
+
+ it('confirms a returned row with the server values', () => {
+ const completedAt = new Date('2026-11-03T00:00:00Z');
+ const keep = confirmedTaskPatches(patch, ['a'], [{ completedAt, id: 'a' } as any]);
+ expect(keep.get('a')!(task, {})).toMatchObject({ completedAt, status: 'completed' });
+ });
+
+ it('keeps a removal a removal', () => {
+ const remove = optimisticTaskPatch({ kind: 'delete' });
+ const keep = confirmedTaskPatches(remove, ['a'], [{ id: 'a' } as any]);
+ expect(keep.get('a')!(task, {})).toBeUndefined();
+ });
+});
+
+describe('optimisticUndoPatch', () => {
+ const reverts = [
+ { after: { status: 'completed' }, before: { status: 'backlog' }, id: 'a' },
+ { after: { status: 'completed' }, before: { status: 'running' }, id: 'b' },
+ { after: { priority: 4 }, before: { priority: 1 }, id: 'c' },
+ { after: { archived: false }, before: { archived: true }, id: 'd' },
+ ];
+ const patch = optimisticUndoPatch(reverts);
+
+ it('gives each task its own previous values', () => {
+ expect(patch({ ...task, id: 'a', status: 'completed' }, {})).toMatchObject({
+ status: 'backlog',
+ });
+ // A stopped run cannot resume: the task comes back paused.
+ expect(patch({ ...task, id: 'b', status: 'completed' }, {})).toMatchObject({
+ status: 'paused',
+ });
+ expect(patch({ ...task, id: 'c', priority: 4 }, {})).toMatchObject({ priority: 1 });
+ });
+
+ it('re-archives out of lists that hide archived rows', () => {
+ expect(patch({ ...task, id: 'd' }, hidesArchived)).toBeUndefined();
+ expect(patch({ ...task, id: 'd' }, showsArchived)?.archivedAt).toBeInstanceOf(Date);
+ });
+
+ it('leaves tasks outside the batch untouched', () => {
+ const other = { ...task, id: 'z' };
+ expect(patch(other, {})).toBe(other);
+ });
+});
+
+describe('undoStatus', () => {
+ it('maps statuses a person cannot set back to nothing', () => {
+ expect(undoStatus('paused')).toBe('paused');
+ expect(undoStatus('running')).toBe('paused');
+ expect(undoStatus('failed')).toBeUndefined();
+ expect(undoStatus('scheduled')).toBeUndefined();
+ });
+});
diff --git a/src/features/AgentTasks/AgentTaskList/selection/optimisticBatch.ts b/src/features/AgentTasks/AgentTaskList/selection/optimisticBatch.ts
new file mode 100644
index 00000000000..2e15d89b297
--- /dev/null
+++ b/src/features/AgentTasks/AgentTaskList/selection/optimisticBatch.ts
@@ -0,0 +1,167 @@
+import type { CollectionTasksPatch } from '@/store/task/slices/list/action';
+import type { CollectionTask } from '@/store/task/slices/list/projection';
+
+import 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 };
+ };
+
+/** A changed row as `batchUpdate` / `batchUpdateStatus` return it (list-visible columns). */
+export type TaskBatchChangedRow = Partial<CollectionTask> & { id: string };
+
+/** Values one batch write replaced on a task, and what it wrote (server `TaskBatchRevertValues`). */
+export interface TaskBatchRevertValues {
+ archived?: boolean;
+ assigneeAgentId?: string | null;
+ assigneeUserId?: string | null;
+ priority?: number | null;
+ status?: string;
+}
+
+/** How to undo a batch on one task (server `TaskBatchRevert`). */
+export interface TaskBatchRevert {
+ after: TaskBatchRevertValues;
+ before: TaskBatchRevertValues;
+ id: string;
+}
+
+export type TaskBatchResponse = TaskBatchOutcome & {
+ reverts?: TaskBatchRevert[];
+ tasks?: TaskBatchChangedRow[];
+};
+
+/**
+ * The status an undo puts back, as the server will (`TaskBatchRevertService`):
+ * a task the batch stopped mid-run comes back paused; statuses a person
+ * cannot set (failed, scheduled) are not restored.
+ */
+export const undoStatus = (before: string): string | undefined => {
+ if (['backlog', 'paused', 'completed', 'canceled'].includes(before)) return before;
+ if (before === 'running') return 'paused';
+ return undefined;
+};
+
+/**
+ * How the list shows an undo before the server answers: each task gets its
+ * own `before` values back (not one shared value). Archive state is put back
+ * too — out of a list that hides archived rows, or unmarked where it shows
+ * them; a task re-appearing in a list that hides archived rows waits for the
+ * refresh, since that list never held it.
+ */
+export const optimisticUndoPatch = (reverts: readonly TaskBatchRevert[]): CollectionTasksPatch => {
+ const byId = new Map(reverts.map((revert) => [revert.id, revert.before]));
+ return (task, query) => {
+ const before = byId.get(task.id);
+ if (!before) return task;
+ if (before.archived === true && query.includeArchived === false) return undefined;
+ const status = before.status === undefined ? undefined : undoStatus(before.status);
+ return {
+ ...task,
+ ...(status !== undefined && { status }),
+ ...(before.archived !== undefined && { archivedAt: before.archived ? new Date() : null }),
+ ...(before.priority !== undefined && { priority: before.priority ?? 0 }),
+ ...(before.assigneeAgentId !== undefined && { assigneeAgentId: before.assigneeAgentId }),
+ ...(before.assigneeUserId !== undefined && { assigneeUserId: before.assigneeUserId }),
+ } as CollectionTask;
+ };
+};
+
+/** Statuses the server stamps `completedAt` on (`TaskBatchService.updateStatus`). */
+const TERMINAL_STATUSES = new Set<TaskBatchStatus>(['canceled', 'completed']);
+
+/**
+ * How the list shows a batch action before the server answers — the same
+ * change the server is about to make to each row:
+ * - status: patched in place (a status board moves the card); closing a task
+ * stamps `completedAt` / `updatedAt` now, as the server will, so a
+ * "completed within" window does not date it by its stale `updatedAt`;
+ * - fields: patched in place; a reassigned row leaves a collection scoped to
+ * its old assignee (an agent's tasks, "My tasks: assigned");
+ * - delete: the row leaves every collection;
+ * - archive: the row leaves collections that hide archived rows, and is
+ * marked archived where "Show archived" keeps it; restore clears the mark.
+ * A collection whose query is unknown (a persisted, unloaded row) is left
+ * as stored: guessing would drop the row from a "Show archived" view.
+ */
+export const optimisticTaskPatch = (action: TaskBatchAction): CollectionTasksPatch => {
+ switch (action.kind) {
+ case 'delete': {
+ return () => undefined;
+ }
+ case 'archive': {
+ if (!action.archived) return (task) => ({ ...task, archivedAt: null });
+ const archivedAt = new Date();
+ return (task, query) => {
+ if (query.includeArchived === undefined) return task;
+ return query.includeArchived ? { ...task, archivedAt } : undefined;
+ };
+ }
+ case 'status': {
+ const now = new Date();
+ const closes = TERMINAL_STATUSES.has(action.status);
+ return (task) => ({
+ ...task,
+ status: action.status,
+ updatedAt: now,
+ ...(closes && { completedAt: now }),
+ });
+ }
+ case 'update': {
+ const { patch } = action;
+ return (task, query) => {
+ // The row leaves a collection scoped to the assignee it no longer has.
+ if (
+ query.agentId &&
+ patch.assigneeAgentId !== undefined &&
+ patch.assigneeAgentId !== query.agentId
+ )
+ return undefined;
+ if (
+ query.scope === 'assigned' &&
+ patch.assigneeUserId !== undefined &&
+ patch.assigneeUserId !== task.assigneeUserId
+ )
+ return undefined;
+ return {
+ ...task,
+ ...(patch.assigneeAgentId !== undefined && { assigneeAgentId: patch.assigneeAgentId }),
+ ...(patch.assigneeUserId !== undefined && { assigneeUserId: patch.assigneeUserId }),
+ ...(patch.priority !== undefined && { priority: patch.priority }),
+ };
+ };
+ }
+ }
+};
+
+/**
+ * The patches to keep once the server answered: only the rows it changed.
+ * Failed and skipped rows are left out, so they fall back to what they were.
+ * A changed row the server sent back is confirmed with its values (e.g. the
+ * `completedAt` it stamped), on top of the optimistic patch.
+ */
+export const confirmedTaskPatches = (
+ patch: CollectionTasksPatch,
+ updated: readonly string[],
+ rows: readonly TaskBatchChangedRow[] = [],
+): Map<string, CollectionTasksPatch> => {
+ const byId = new Map(rows.map((row) => [row.id, row]));
+ return new Map(
+ updated.map((id) => {
+ const row = byId.get(id);
+ if (!row) return [id, patch] as const;
+ const confirmed: CollectionTasksPatch = (task, query) => {
+ const next = patch(task, query);
+ return next && ({ ...next, ...row } as CollectionTask);
+ };
+ return [id, confirmed] as const;
+ }),
+ );
+};
diff --git a/src/features/AgentTasks/AgentTaskList/selection/serverQueue.ts b/src/features/AgentTasks/AgentTaskList/selection/serverQueue.ts
new file mode 100644
index 00000000000..7ebf88b21fe
--- /dev/null
+++ b/src/features/AgentTasks/AgentTaskList/selection/serverQueue.ts
@@ -0,0 +1,13 @@
+/**
+ * Batches — and their undos — reach the server in click order. The list
+ * already shows each one, so a second action never waits on screen, but two
+ * writes to the same rows must land in the order the user made them, or the
+ * list would settle on the earlier one.
+ */
+let serverQueue: Promise<unknown> = Promise.resolve();
+
+export const enqueueBatchRequest = <T>(job: () => Promise<T>): Promise<T> => {
+ const next = serverQueue.then(job, job);
+ serverQueue = next.catch(() => undefined);
+ return next;
+};
diff --git a/src/features/AgentTasks/AgentTaskList/selection/store.test.ts b/src/features/AgentTasks/AgentTaskList/selection/store.test.ts
index 97344f94574..b65cfa5e831 100644
--- a/src/features/AgentTasks/AgentTaskList/selection/store.test.ts
+++ b/src/features/AgentTasks/AgentTaskList/selection/store.test.ts
@@ -8,28 +8,22 @@ afterEach(() => {
});
describe('useTaskSelectionStore', () => {
- it('bumps the generation on every clear so a late batch can tell its scope is gone', () => {
+ it('bumps the revision on every user selection change and clear, not on prune', () => {
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;
+ const at = () => useTaskSelectionStore.getState().revision;
+ const start = at();
store.toggle('a');
store.selectRange(['a', 'b', 'c'], 'c');
- store.prune(new Set(['a', 'b']));
+ store.selectAll(['a', 'b']);
+ expect(at()).toBe(start + 3);
- const state = useTaskSelectionStore.getState();
- expect(state.selectedIds).toEqual(['a', 'b']);
- expect(state.generation).toBe(before);
+ store.prune(new Set(['a']));
+ expect(at()).toBe(start + 3);
+ expect(useTaskSelectionStore.getState().selectedIds).toEqual(['a']);
+
+ store.clear();
+ expect(at()).toBe(start + 4);
+ expect(useTaskSelectionStore.getState().selectedIds).toEqual([]);
});
it('does not open the panel while a batch is running', () => {
@@ -38,4 +32,60 @@ describe('useTaskSelectionStore', () => {
store.setPanelOpen(true);
expect(useTaskSelectionStore.getState().panelOpen).toBe(false);
});
+
+ describe('restore', () => {
+ const settle = (visible: string[]) => {
+ const store = useTaskSelectionStore.getState();
+ store.clear();
+ store.prune(new Set(visible));
+ return useTaskSelectionStore.getState().revision;
+ };
+
+ it('selects shown rows now and hidden ones once the list shows them again', () => {
+ // `b` was hidden by the overlay (e.g. moved to a status the view hides).
+ const revision = settle(['a', 'c']);
+ useTaskSelectionStore.getState().restore(['a', 'b'], revision);
+ expect(useTaskSelectionStore.getState().selectedIds).toEqual(['a']);
+
+ // The rollback renders: the list prunes with `b` back in it.
+ useTaskSelectionStore.getState().prune(new Set(['a', 'b', 'c']));
+ expect(useTaskSelectionStore.getState().selectedIds).toEqual(['a', 'b']);
+ expect(useTaskSelectionStore.getState().pendingRestore).toBeUndefined();
+ });
+
+ it('drops pending rows the next list render does not show', () => {
+ const revision = settle([]);
+ useTaskSelectionStore.getState().restore(['a'], revision);
+ useTaskSelectionStore.getState().prune(new Set(['x']));
+ useTaskSelectionStore.getState().prune(new Set(['a', 'x']));
+ expect(useTaskSelectionStore.getState().selectedIds).toEqual([]);
+ });
+
+ it('leaves a selection the user moved on to alone', () => {
+ const revision = settle(['a', 'b']);
+ useTaskSelectionStore.getState().toggle('b');
+ useTaskSelectionStore.getState().restore(['a'], revision);
+ expect(useTaskSelectionStore.getState().selectedIds).toEqual(['b']);
+
+ useTaskSelectionStore.getState().clear();
+ useTaskSelectionStore.getState().restore(['a'], revision);
+ expect(useTaskSelectionStore.getState().selectedIds).toEqual([]);
+ });
+
+ it('does not restore after a select-then-deselect left the selection empty', () => {
+ const revision = settle(['a', 'b']);
+ useTaskSelectionStore.getState().toggle('b');
+ useTaskSelectionStore.getState().toggle('b');
+ useTaskSelectionStore.getState().restore(['a'], revision);
+ expect(useTaskSelectionStore.getState().selectedIds).toEqual([]);
+ });
+
+ it('forgets pending rows when the user selects before the list renders', () => {
+ const revision = settle(['c']);
+ useTaskSelectionStore.getState().restore(['a'], revision);
+ useTaskSelectionStore.getState().toggle('c');
+ useTaskSelectionStore.getState().prune(new Set(['a', 'c']));
+ expect(useTaskSelectionStore.getState().selectedIds).toEqual(['c']);
+ });
+ });
});
diff --git a/src/features/AgentTasks/AgentTaskList/selection/store.ts b/src/features/AgentTasks/AgentTaskList/selection/store.ts
index 34295d061af..d62ee36efca 100644
--- a/src/features/AgentTasks/AgentTaskList/selection/store.ts
+++ b/src/features/AgentTasks/AgentTaskList/selection/store.ts
@@ -5,15 +5,22 @@ import { pruneSelection, selectRange, toggleSelection } from './taskSelectionMod
interface TaskSelectionState {
/** Last row clicked without Shift — where the next Shift+click range starts. */
anchorId?: string;
+ panelOpen: boolean;
/**
- * 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.
+ * Rows a settled batch hands back for a retry that the list does not show
+ * yet (its rollback has not rendered). The list's next `prune` selects the
+ * ones it then shows and drops this; any selection change drops it too.
*/
- generation: number;
- panelOpen: boolean;
+ pendingRestore?: readonly string[];
/** A batch is in flight: `done` of `total` tasks sent so far. */
progress?: { done: number; total: number };
+ /**
+ * Bumped by every selection change the user (or `clear`) makes — not by
+ * `prune`. A settled batch restores rows only when nothing changed since it
+ * started: select-then-deselect leaves an empty selection, but the user has
+ * still moved on.
+ */
+ revision: number;
selectedIds: readonly string[];
/**
* Selectable rows of the list on screen, as last reported by `prune`. A batch
@@ -26,6 +33,12 @@ interface TaskSelectionState {
interface TaskSelectionActions {
clear: () => void;
prune: (visibleIds: ReadonlySet<string>) => void;
+ /**
+ * Re-select a settled batch's rows that still need attention, unless the
+ * selection changed at all since `revision`. Rows not on screen yet wait for
+ * the next `prune`.
+ */
+ restore: (ids: readonly string[], revision: number) => void;
selectAll: (order: readonly string[]) => void;
selectRange: (order: readonly string[], id: string) => void;
setPanelOpen: (open: boolean) => void;
@@ -46,32 +59,69 @@ export const useTaskSelectionStore = create<TaskSelectionState & TaskSelectionAc
clear: () =>
set((state) => ({
anchorId: undefined,
- generation: state.generation + 1,
panelOpen: false,
+ pendingRestore: undefined,
+ revision: state.revision + 1,
// 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,
+ pendingRestore: undefined,
prune: (visibleIds) =>
set((state) => {
- const selectedIds = pruneSelection(state.selectedIds, visibleIds);
+ let selectedIds = pruneSelection(state.selectedIds, visibleIds);
+ if (state.pendingRestore) {
+ const restored = state.pendingRestore.filter(
+ (id) => visibleIds.has(id) && !selectedIds.includes(id),
+ );
+ if (restored.length > 0) selectedIds = [...selectedIds, ...restored];
+ return {
+ panelOpen: state.panelOpen && selectedIds.length > 0,
+ pendingRestore: undefined,
+ selectedIds,
+ visibleIds,
+ };
+ }
if (selectedIds === state.selectedIds) return { visibleIds };
return { panelOpen: state.panelOpen && selectedIds.length > 0, selectedIds, visibleIds };
}),
+ restore: (ids, revision) =>
+ set((state) => {
+ if (state.revision !== revision || state.selectedIds.length > 0) return state;
+ const shown = ids.filter((id) => state.visibleIds.has(id));
+ const later = ids.filter((id) => !state.visibleIds.has(id));
+ return {
+ pendingRestore: later.length > 0 ? later : undefined,
+ selectedIds: shown.length > 0 ? shown : state.selectedIds,
+ };
+ }),
// 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] })),
+ set((state) =>
+ state.progress
+ ? state
+ : {
+ anchorId: order[0],
+ pendingRestore: undefined,
+ revision: state.revision + 1,
+ selectedIds: [...order],
+ },
+ ),
selectRange: (order, id) =>
set((state) =>
state.progress
? state
- : { selectedIds: selectRange(order, state.selectedIds, state.anchorId, id) },
+ : {
+ pendingRestore: undefined,
+ revision: state.revision + 1,
+ selectedIds: selectRange(order, state.selectedIds, state.anchorId, id),
+ },
),
+ revision: 0,
selectedIds: EMPTY,
setPanelOpen: (panelOpen) => set((state) => ({ panelOpen: panelOpen && !state.progress })),
setProgress: (progress) => set({ panelOpen: false, progress }),
@@ -79,7 +129,12 @@ export const useTaskSelectionStore = create<TaskSelectionState & TaskSelectionAc
set((state) =>
state.progress
? state
- : { anchorId: id, selectedIds: toggleSelection(state.selectedIds, id) },
+ : {
+ anchorId: id,
+ pendingRestore: undefined,
+ revision: state.revision + 1,
+ selectedIds: toggleSelection(state.selectedIds, id),
+ },
),
visibleIds: EMPTY_SET,
}));
diff --git a/src/features/AgentTasks/AgentTaskList/selection/undo/stack.test.ts b/src/features/AgentTasks/AgentTaskList/selection/undo/stack.test.ts
new file mode 100644
index 00000000000..e3fb0adb49a
--- /dev/null
+++ b/src/features/AgentTasks/AgentTaskList/selection/undo/stack.test.ts
@@ -0,0 +1,27 @@
+import { beforeEach, describe, expect, it } from 'vitest';
+
+import {
+ peekLastUndoEntry,
+ pushUndoEntry,
+ resetUndoStack,
+ takeUndoEntry,
+ TASK_BATCH_UNDO_LIMIT,
+} from './stack';
+
+beforeEach(() => resetUndoStack());
+
+describe('task batch undo stack', () => {
+ it('keeps the most recent batches, newest last', () => {
+ for (let i = 0; i < TASK_BATCH_UNDO_LIMIT + 2; i++)
+ pushUndoEntry({ kind: 'restore', taskIds: [`t${i}`] });
+ const last = peekLastUndoEntry();
+ expect(last).toMatchObject({ taskIds: [`t${TASK_BATCH_UNDO_LIMIT + 1}`] });
+ });
+
+ it('hands an entry out only once', () => {
+ const entry = pushUndoEntry({ kind: 'restore', taskIds: ['a'] });
+ expect(takeUndoEntry(entry.id)).toBe(true);
+ expect(takeUndoEntry(entry.id)).toBe(false);
+ expect(peekLastUndoEntry()).toBeUndefined();
+ });
+});
diff --git a/src/features/AgentTasks/AgentTaskList/selection/undo/stack.ts b/src/features/AgentTasks/AgentTaskList/selection/undo/stack.ts
new file mode 100644
index 00000000000..4e014c84782
--- /dev/null
+++ b/src/features/AgentTasks/AgentTaskList/selection/undo/stack.ts
@@ -0,0 +1,43 @@
+import type { TaskBatchRevert } from '../optimisticBatch';
+
+/**
+ * How to undo one committed batch. Status / field / archive changes carry the
+ * server's `reverts` (each task's replaced values, read under its row lock);
+ * a delete undoes by restoring the tasks from the recycle bin.
+ */
+export type TaskBatchUndoEntry =
+ | { id: number; kind: 'revert'; reverts: TaskBatchRevert[] }
+ | { id: number; kind: 'restore'; taskIds: string[] };
+
+/** Batches ⌘Z can still reach. Session memory only: a reload starts empty. */
+export const TASK_BATCH_UNDO_LIMIT = 10;
+
+let entries: TaskBatchUndoEntry[] = [];
+let nextId = 1;
+
+type NewEntry =
+ { kind: 'revert'; reverts: TaskBatchRevert[] } | { kind: 'restore'; taskIds: string[] };
+
+export const pushUndoEntry = (entry: NewEntry): TaskBatchUndoEntry => {
+ const pushed = { ...entry, id: nextId++ } as TaskBatchUndoEntry;
+ entries = [...entries, pushed].slice(-TASK_BATCH_UNDO_LIMIT);
+ return pushed;
+};
+
+/**
+ * Take an entry off the stack so it is undone at most once (the toast button
+ * and ⌘Z can race). Returns whether it was still there.
+ */
+export const takeUndoEntry = (id: number): boolean => {
+ const before = entries.length;
+ entries = entries.filter((entry) => entry.id !== id);
+ return entries.length < before;
+};
+
+export const peekLastUndoEntry = (): TaskBatchUndoEntry | undefined => entries.at(-1);
+
+/** Test helper. */
+export const resetUndoStack = () => {
+ entries = [];
+ nextId = 1;
+};
diff --git a/src/features/AgentTasks/AgentTaskList/selection/undo/useTaskBatchUndo.ts b/src/features/AgentTasks/AgentTaskList/selection/undo/useTaskBatchUndo.ts
new file mode 100644
index 00000000000..d39a8467290
--- /dev/null
+++ b/src/features/AgentTasks/AgentTaskList/selection/undo/useTaskBatchUndo.ts
@@ -0,0 +1,110 @@
+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 {
+ confirmedTaskPatches,
+ optimisticUndoPatch,
+ type TaskBatchResponse,
+} from '../optimisticBatch';
+import { enqueueBatchRequest } from '../serverQueue';
+import { useTaskSelectionStore } from '../store';
+import { chunkIds, mergeOutcomes, TASK_BATCH_CHUNK_SIZE } from '../taskSelectionModel';
+import { useBackgroundTaskListRefresh } from '../useBackgroundTaskListRefresh';
+import { peekLastUndoEntry, takeUndoEntry, type TaskBatchUndoEntry } from './stack';
+
+const chunk = <T>(items: readonly T[]): T[][] => {
+ const chunks: T[][] = [];
+ for (let i = 0; i < items.length; i += TASK_BATCH_CHUNK_SIZE)
+ chunks.push(items.slice(i, i + TASK_BATCH_CHUNK_SIZE));
+ return chunks;
+};
+
+/**
+ * Undo of a committed batch, as fast as the batch itself: status and field
+ * changes show their old values at once (each task its own `before`), the
+ * request runs behind it in click order, and the list refresh follows in the
+ * background. Tasks someone changed again since the batch are left alone and
+ * counted in the toast. The undone tasks come back selected (like Linear),
+ * unless the user has moved on to another selection.
+ */
+export const useTaskBatchUndo = () => {
+ const { t } = useTranslation('chat');
+ const beginOptimistic = useTaskStore((s) => s.internal_beginCollectionTasksOptimistic);
+ const refreshInBackground = useBackgroundTaskListRefresh();
+
+ const undo = useCallback(
+ async (entry: TaskBatchUndoEntry) => {
+ // At most once: the toast button and ⌘Z can both reach the same entry.
+ if (!takeUndoEntry(entry.id)) return;
+ const revision = useTaskSelectionStore.getState().revision;
+
+ const ids = entry.kind === 'revert' ? entry.reverts.map((r) => r.id) : entry.taskIds;
+ const patch = entry.kind === 'revert' ? optimisticUndoPatch(entry.reverts) : undefined;
+ // A restore from the bin has no rows on screen to patch; the refresh brings them.
+ const overlay = patch ? beginOptimistic(ids, patch) : undefined;
+
+ const outcomes: TaskBatchResponse[] = [];
+ let requestError: unknown;
+ await enqueueBatchRequest(async () => {
+ try {
+ if (entry.kind === 'revert') {
+ for (const part of chunk(entry.reverts))
+ outcomes.push(await taskService.batchRevert(part));
+ } else {
+ for (const part of chunkIds(entry.taskIds))
+ outcomes.push(await taskService.batchRestoreDeleted(part));
+ }
+ } catch (error) {
+ requestError = error;
+ }
+ });
+
+ const { failed, skipped, updated } = mergeOutcomes(outcomes);
+ if (overlay && patch) {
+ if (updated.length === 0) overlay.rollback();
+ else overlay.commit(confirmedTaskPatches(patch, updated));
+ }
+ if (updated.length > 0) refreshInBackground();
+
+ if (requestError && updated.length === 0) {
+ toast.error(
+ requestError instanceof Error && requestError.message
+ ? requestError.message
+ : t('taskList.bulk.undo.error'),
+ );
+ return;
+ }
+
+ const conflicts = skipped.filter((item) => item.reason === 'conflict').length;
+ const otherSkipped = skipped.length - conflicts;
+ const unprocessed = Math.max(ids.length - updated.length - skipped.length - failed.length, 0);
+ const parts = [t('taskList.bulk.undo.done', { count: updated.length })];
+ if (conflicts > 0) parts.push(t('taskList.bulk.undo.conflict', { count: conflicts }));
+ if (otherSkipped > 0) parts.push(t('taskList.bulk.result.skipped', { count: otherSkipped }));
+ if (failed.length + unprocessed > 0)
+ parts.push(t('taskList.bulk.result.failed', { count: failed.length + unprocessed }));
+ const message = parts.join(' · ');
+ if (updated.length < ids.length) toast.warning(message);
+ else toast.success(message);
+
+ // Like Linear: the undone tasks come back selected — once the list
+ // renders them (a restore from the bin needs the refresh first).
+ if (updated.length > 0) useTaskSelectionStore.getState().restore(updated, revision);
+ },
+ [beginOptimistic, refreshInBackground, t],
+ );
+
+ /** ⌘/Ctrl+Z: undo the most recent batch still on the stack. */
+ const undoLast = useCallback(() => {
+ const entry = peekLastUndoEntry();
+ if (!entry) return false;
+ void undo(entry);
+ return true;
+ }, [undo]);
+
+ return { undo, undoLast };
+};
diff --git a/src/features/AgentTasks/AgentTaskList/selection/useBackgroundTaskListRefresh.ts b/src/features/AgentTasks/AgentTaskList/selection/useBackgroundTaskListRefresh.ts
new file mode 100644
index 00000000000..8ae711805f2
--- /dev/null
+++ b/src/features/AgentTasks/AgentTaskList/selection/useBackgroundTaskListRefresh.ts
@@ -0,0 +1,31 @@
+import { toast } from '@lobehub/ui';
+import { useCallback } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useTaskStore } from '@/store/task';
+
+/**
+ * Refresh every loaded task list after a committed batch (or undo), without
+ * making anyone wait for it. A failed refresh only means the list on screen
+ * may be stale, so it says that, with a retry.
+ */
+export const useBackgroundTaskListRefresh = () => {
+ const { t } = useTranslation('chat');
+ const refreshTaskList = useTaskStore((s) => s.refreshTaskList);
+
+ return useCallback(() => {
+ void 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'),
+ });
+ });
+ }, [refreshTaskList, t]);
+};
diff --git a/src/features/AgentTasks/AgentTaskList/selection/useTaskBatchActions.test.ts b/src/features/AgentTasks/AgentTaskList/selection/useTaskBatchActions.test.ts
index 1d6231fae55..f62363eb78f 100644
--- a/src/features/AgentTasks/AgentTaskList/selection/useTaskBatchActions.test.ts
+++ b/src/features/AgentTasks/AgentTaskList/selection/useTaskBatchActions.test.ts
@@ -2,23 +2,37 @@ import { act, renderHook } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { useTaskSelectionStore } from './store';
+import { resetUndoStack } from './undo/stack';
+import { useTaskBatchUndo } from './undo/useTaskBatchUndo';
import { useTaskBatchActions } from './useTaskBatchActions';
const batchUpdate = vi.fn();
+const batchDelete = vi.fn();
+const batchRevert = vi.fn();
+const batchRestoreDeleted = vi.fn();
const refreshTaskList = vi.fn(async () => {});
const toastWarning = vi.fn();
+const toastError = vi.fn();
+const toastSuccess = vi.fn();
+const overlay = { commit: vi.fn(), rollback: vi.fn() };
+const beginOptimistic = vi.fn((..._args: unknown[]) => overlay);
vi.mock('@/services/task', () => ({
- taskService: { batchUpdate: (...args: unknown[]) => batchUpdate(...args) },
+ taskService: {
+ batchDelete: (...args: unknown[]) => batchDelete(...args),
+ batchRestoreDeleted: (...args: unknown[]) => batchRestoreDeleted(...args),
+ batchRevert: (...args: unknown[]) => batchRevert(...args),
+ batchUpdate: (...args: unknown[]) => batchUpdate(...args),
+ },
}));
vi.mock('@/store/task', () => ({
- useTaskStore: (selector: (s: { refreshTaskList: () => Promise<void> }) => unknown) =>
- selector({ refreshTaskList }),
+ useTaskStore: (selector: (s: Record<string, unknown>) => unknown) =>
+ selector({ internal_beginCollectionTasksOptimistic: beginOptimistic, refreshTaskList }),
}));
vi.mock('@lobehub/ui', () => ({
toast: {
- error: vi.fn(),
- success: vi.fn(),
+ error: (...args: unknown[]) => toastError(...args),
+ success: (...args: unknown[]) => toastSuccess(...args),
warning: (...args: unknown[]) => toastWarning(...args),
},
}));
@@ -28,6 +42,15 @@ const partialFailure = { failed: [{ error: 'boom', id: 'b' }], skipped: [], upda
beforeEach(() => {
batchUpdate.mockReset();
+ batchDelete.mockReset();
+ batchRevert.mockReset();
+ batchRestoreDeleted.mockReset();
+ resetUndoStack();
+ beginOptimistic.mockClear();
+ overlay.commit.mockReset();
+ overlay.rollback.mockReset();
+ toastError.mockReset();
+ toastSuccess.mockReset();
refreshTaskList.mockReset();
refreshTaskList.mockResolvedValue(undefined);
toastWarning.mockReset();
@@ -50,6 +73,106 @@ describe('useTaskBatchActions', () => {
expect(useTaskSelectionStore.getState().selectedIds).toEqual(['b']);
expect(useTaskSelectionStore.getState().progress).toBeUndefined();
+ // Only the row the server changed keeps its optimistic patch.
+ const [keep] = overlay.commit.mock.calls[0] as [Map<string, unknown>];
+ expect([...keep.keys()]).toEqual(['a']);
+ });
+
+ it('shows the result and clears the selection before the server answers', async () => {
+ let resolve!: (value: unknown) => 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 } });
+ });
+ expect(beginOptimistic).toHaveBeenCalledWith(['a', 'b'], expect.any(Function));
+ expect(useTaskSelectionStore.getState().selectedIds).toEqual([]);
+ expect(overlay.commit).not.toHaveBeenCalled();
+
+ await act(async () => {
+ resolve({ failed: [], skipped: [], updated: ['a', 'b'] });
+ await pending;
+ });
+ expect(overlay.commit).toHaveBeenCalledTimes(1);
+ expect(toastSuccess).toHaveBeenCalledTimes(1);
+ });
+
+ it('does not wait for the list refresh before settling', async () => {
+ batchUpdate.mockResolvedValue({ failed: [], skipped: [], updated: ['a'] });
+ refreshTaskList.mockReturnValue(new Promise(() => {}));
+ useTaskSelectionStore.getState().selectAll(['a']);
+ const { result } = renderHook(() => useTaskBatchActions());
+
+ await act(() => result.current.run({ kind: 'update', patch: { priority: 1 } }));
+
+ expect(refreshTaskList).toHaveBeenCalledTimes(1);
+ expect(toastSuccess).toHaveBeenCalledTimes(1);
+ });
+
+ it('rolls everything back and reselects the rows when the request fails', async () => {
+ batchDelete.mockRejectedValue(new Error('offline'));
+ useTaskSelectionStore.getState().prune(new Set(['a', 'b']));
+ useTaskSelectionStore.getState().selectAll(['a', 'b']);
+ const { result } = renderHook(() => useTaskBatchActions());
+
+ act(() => {
+ void result.current.run({ kind: 'delete' });
+ // The deleted rows left the list: its prune drops them from `visibleIds`.
+ useTaskSelectionStore.getState().prune(new Set());
+ });
+ await act(async () => {});
+
+ expect(overlay.rollback).toHaveBeenCalledTimes(1);
+ expect(overlay.commit).not.toHaveBeenCalled();
+ expect(refreshTaskList).not.toHaveBeenCalled();
+ expect(toastError).toHaveBeenCalledWith('offline');
+ // Selected again for a retry once the rolled-back rows render again.
+ expect(useTaskSelectionStore.getState().selectedIds).toEqual([]);
+ act(() => useTaskSelectionStore.getState().prune(new Set(['a', 'b'])));
+ expect(useTaskSelectionStore.getState().selectedIds).toEqual(['a', 'b']);
+ });
+
+ it('sends batches to the server in click order', async () => {
+ const order: string[] = [];
+ let releaseFirst!: () => void;
+ batchUpdate
+ .mockImplementationOnce(
+ () =>
+ new Promise((r) => {
+ releaseFirst = () => {
+ order.push('first');
+ r({ failed: [], skipped: [], updated: ['a'] });
+ };
+ }),
+ )
+ .mockImplementationOnce(async () => {
+ order.push('second');
+ return { failed: [], skipped: [], updated: ['a'] };
+ });
+ const { result } = renderHook(() => useTaskBatchActions());
+
+ let first!: Promise<void>;
+ let second!: Promise<void>;
+ act(() => {
+ useTaskSelectionStore.getState().selectAll(['a']);
+ first = result.current.run({ kind: 'update', patch: { priority: 1 } });
+ useTaskSelectionStore.getState().selectAll(['a']);
+ second = result.current.run({ kind: 'update', patch: { priority: 2 } });
+ });
+ // Both already show; the second request waits for the first.
+ expect(beginOptimistic).toHaveBeenCalledTimes(2);
+ await act(async () => {});
+ expect(batchUpdate).toHaveBeenCalledTimes(1);
+
+ await act(async () => {
+ releaseFirst();
+ await Promise.all([first, second]);
+ });
+ expect(order).toEqual(['first', 'second']);
});
it('does not restore a selection whose list was left while the batch ran', async () => {
@@ -99,7 +222,7 @@ describe('useTaskBatchActions', () => {
expect(useTaskSelectionStore.getState().selectedIds).toEqual([]);
});
- it('freezes the selection while the batch runs', async () => {
+ it('keeps a selection the user made while the batch ran', async () => {
let resolve!: (value: typeof partialFailure) => void;
batchUpdate.mockReturnValue(new Promise((r) => (resolve = r)));
useTaskSelectionStore.getState().prune(new Set(['a', 'b', 'c']));
@@ -110,19 +233,14 @@ describe('useTaskBatchActions', () => {
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']);
+ // The list is not frozen: the user goes on selecting.
+ act(() => useTaskSelectionStore.getState().toggle('c'));
await act(async () => {
resolve(partialFailure);
await pending;
});
- expect(useTaskSelectionStore.getState().selectedIds).toEqual(['b']);
+ expect(useTaskSelectionStore.getState().selectedIds).toEqual(['c']);
});
it('reports a failed list refresh after a committed batch, with a retry', async () => {
@@ -134,6 +252,7 @@ describe('useTaskBatchActions', () => {
const { result } = renderHook(() => useTaskBatchActions());
await act(() => result.current.run({ kind: 'update', patch: { priority: 1 } }));
+ await act(async () => {});
const refreshWarning = toastWarning.mock.calls.find(
([arg]) => typeof arg === 'object' && arg?.title === 'taskList.bulk.refreshFailed.title',
@@ -165,4 +284,77 @@ describe('useTaskBatchActions', () => {
),
).toBe(true);
});
+
+ describe('undo', () => {
+ const undoAction = () => {
+ const [options] = toastSuccess.mock.calls.at(-1)!;
+ return (options as { actions?: { label: string; onClick: () => void }[] }).actions?.[0];
+ };
+
+ it('offers an undo that writes back what the batch replaced', async () => {
+ const reverts = [{ after: { priority: 1 }, before: { priority: 3 }, id: 'a' }];
+ batchUpdate.mockResolvedValue({ failed: [], reverts, skipped: [], updated: ['a'] });
+ batchRevert.mockResolvedValue({ failed: [], skipped: [], updated: ['a'] });
+ useTaskSelectionStore.getState().selectAll(['a']);
+ const { result } = renderHook(() => useTaskBatchActions());
+
+ await act(() => result.current.run({ kind: 'update', patch: { priority: 1 } }));
+ const action = undoAction();
+ expect(action?.label).toBe('taskList.bulk.undo.action');
+
+ await act(async () => {
+ action!.onClick();
+ });
+ await act(async () => {});
+
+ expect(batchRevert).toHaveBeenCalledWith(reverts);
+ // Optimistic like the batch: one overlay for the undo, committed on success.
+ expect(beginOptimistic).toHaveBeenCalledTimes(2);
+ expect(overlay.commit).toHaveBeenCalledTimes(2);
+ expect(toastSuccess).toHaveBeenLastCalledWith('taskList.bulk.undo.done');
+ });
+
+ it('undoes a delete through the recycle bin, once', async () => {
+ batchDelete.mockResolvedValue({ failed: [], skipped: [], updated: ['a', 'b'] });
+ batchRestoreDeleted.mockResolvedValue({ failed: [], skipped: [], updated: ['a', 'b'] });
+ useTaskSelectionStore.getState().selectAll(['a', 'b']);
+ const { result } = renderHook(() => useTaskBatchActions());
+ const { result: undo } = renderHook(() => useTaskBatchUndo());
+
+ await act(() => result.current.run({ kind: 'delete' }));
+ // ⌘Z and the toast button reach the same entry: only one restore runs.
+ await act(async () => {
+ expect(undo.current.undoLast()).toBe(true);
+ undoAction()!.onClick();
+ });
+ await act(async () => {});
+
+ expect(batchRestoreDeleted).toHaveBeenCalledTimes(1);
+ expect(batchRestoreDeleted).toHaveBeenCalledWith(['a', 'b']);
+ expect(undo.current.undoLast()).toBe(false);
+ });
+
+ it('says how many tasks someone changed again since the batch', async () => {
+ const reverts = [
+ { after: { status: 'completed' }, before: { status: 'backlog' }, id: 'a' },
+ { after: { status: 'completed' }, before: { status: 'backlog' }, id: 'b' },
+ ];
+ batchUpdate.mockResolvedValue({ failed: [], reverts, skipped: [], updated: ['a', 'b'] });
+ batchRevert.mockResolvedValue({
+ failed: [],
+ skipped: [{ id: 'b', reason: 'conflict' }],
+ updated: ['a'],
+ });
+ useTaskSelectionStore.getState().selectAll(['a', 'b']);
+ const { result } = renderHook(() => useTaskBatchActions());
+
+ await act(() => result.current.run({ kind: 'update', patch: { priority: 1 } }));
+ await act(async () => undoAction()!.onClick());
+ await act(async () => {});
+
+ expect(toastWarning).toHaveBeenLastCalledWith(
+ 'taskList.bulk.undo.done · taskList.bulk.undo.conflict',
+ );
+ });
+ });
});
diff --git a/src/features/AgentTasks/AgentTaskList/selection/useTaskBatchActions.ts b/src/features/AgentTasks/AgentTaskList/selection/useTaskBatchActions.ts
index f2388f80df5..d374032d0cf 100644
--- a/src/features/AgentTasks/AgentTaskList/selection/useTaskBatchActions.ts
+++ b/src/features/AgentTasks/AgentTaskList/selection/useTaskBatchActions.ts
@@ -5,21 +5,23 @@ import { useTranslation } from 'react-i18next';
import { taskService } from '@/services/task';
import { useTaskStore } from '@/store/task';
+import {
+ confirmedTaskPatches,
+ optimisticTaskPatch,
+ type TaskBatchAction,
+ type TaskBatchChangedRow,
+ type TaskBatchResponse,
+} from './optimisticBatch';
+import { enqueueBatchRequest } from './serverQueue';
import { useTaskSelectionStore } from './store';
-import { chunkIds, mergeOutcomes, type TaskBatchOutcome } from './taskSelectionModel';
+import { chunkIds, mergeOutcomes } from './taskSelectionModel';
+import { pushUndoEntry } from './undo/stack';
+import { useTaskBatchUndo } from './undo/useTaskBatchUndo';
+import { useBackgroundTaskListRefresh } from './useBackgroundTaskListRefresh';
-export type TaskBatchStatus = 'backlog' | 'canceled' | 'completed' | 'paused';
+export type { TaskBatchAction, TaskBatchStatus } from './optimisticBatch';
-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> => {
+const runChunk = (action: TaskBatchAction, ids: string[]): Promise<TaskBatchResponse> => {
switch (action.kind) {
case 'archive': {
return taskService.batchArchive(ids, action.archived);
@@ -28,81 +30,81 @@ const runChunk = (action: TaskBatchAction, ids: string[]): Promise<TaskBatchOutc
return taskService.batchDelete(ids);
}
case 'status': {
- return taskService.batchUpdateStatus(ids, action.status);
+ return taskService.batchUpdateStatus(ids, action.status) as Promise<TaskBatchResponse>;
}
case 'update': {
- return taskService.batchUpdate({ ids, ...action.patch });
+ return taskService.batchUpdate({ ids, ...action.patch }) as Promise<TaskBatchResponse>;
}
}
};
/**
- * 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.
+ * Apply one action to the current selection, optimistically: every loaded
+ * list and board shows the result and the selection clears the moment the
+ * action is picked. The requests (one per 500 tasks, the server's batch
+ * limit) run behind it; their answer settles the overlay — rows the server
+ * did not change fall back and come back selected for a retry, a failed
+ * request rolls everything back — and the list refresh that follows runs in
+ * the background, never in front of the user.
*/
export const useTaskBatchActions = () => {
const { t } = useTranslation('chat');
- const refreshTaskList = useTaskStore((s) => s.refreshTaskList);
+ const beginOptimistic = useTaskStore((s) => s.internal_beginCollectionTasksOptimistic);
const running = useTaskSelectionStore((s) => !!s.progress);
+ const refreshInBackground = useBackgroundTaskListRefresh();
+ const { undo } = useTaskBatchUndo();
+
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];
+ const ids = [...useTaskSelectionStore.getState().selectedIds];
if (ids.length === 0) return;
- setProgress({ done: 0, total: ids.length });
- const outcomes: TaskBatchOutcome[] = [];
+ const patch = optimisticTaskPatch(action);
+ const overlay = beginOptimistic(ids, patch);
+ // The rows already show the result: the selection is done with.
+ useTaskSelectionStore.getState().clear();
+ const revision = useTaskSelectionStore.getState().revision;
+
+ const outcomes: TaskBatchResponse[] = [];
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 });
+ await enqueueBatchRequest(async () => {
+ try {
+ // Sequential: each chunk is already a set-based write on the server,
+ // and ordering keeps a later chunk from racing an earlier one.
+ for (const chunk of chunkIds(ids)) outcomes.push(await runChunk(action, chunk));
+ } catch (error) {
+ requestError = error;
}
- } 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 rows = outcomes.flatMap((outcome): TaskBatchChangedRow[] => outcome.tasks ?? []);
const unprocessed = ids.length - updated.length - skipped.length - failed.length;
const failedCount = failed.length + Math.max(unprocessed, 0);
+ if (updated.length === 0) overlay.rollback();
+ else {
+ overlay.commit(confirmedTaskPatches(patch, updated, rows));
+ refreshInBackground();
+ }
+
+ // Rows still needing attention come back selected — unless the user has
+ // moved on: any selection change since the click (even one undone
+ // since), or leaving the list (a scope or page change clears it). A row the overlay hid (deleted,
+ // archived, or moved to a status the view hides) is only shown again
+ // once the rollback renders; the store selects it on the list's next
+ // prune, if the list then shows it.
+ const restoreSelection = (pending: readonly string[]) =>
+ useTaskSelectionStore.getState().restore(pending, revision);
+
if (requestError && updated.length === 0) {
toast.error(
requestError instanceof Error && requestError.message
? requestError.message
: t('taskList.bulk.result.error'),
);
+ restoreSelection(ids);
return;
}
@@ -123,29 +125,41 @@ export const useTaskBatchActions = () => {
title: t('taskList.bulk.followUpFailed.title'),
});
}
+ // Whatever the batch changed can be undone — from the toast, or with
+ // ⌘/Ctrl+Z while the list is on screen (also after the toast is gone).
+ const reverts = outcomes.flatMap((outcome) => outcome.reverts ?? []);
+ const undoEntry =
+ updated.length === 0
+ ? undefined
+ : action.kind === 'delete'
+ ? pushUndoEntry({ kind: 'restore', taskIds: updated })
+ : reverts.length > 0
+ ? pushUndoEntry({ kind: 'revert', reverts })
+ : undefined;
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;
+ const options = {
+ ...(undoEntry && {
+ actions: [
+ {
+ label: t('taskList.bulk.undo.action'),
+ onClick: () => void undo(undoEntry),
+ variant: 'text' as const,
+ },
+ ],
+ // Long enough to read the result and reach the button.
+ duration: 8000,
+ }),
+ title: message,
+ };
+ if (failedCount > 0) toast.warning(options);
+ else toast.success(options);
+
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();
+ restoreSelection(ids.filter((id) => !done.has(id)));
}
},
- [refreshTaskList, t],
+ [beginOptimistic, refreshInBackground, t, undo],
);
return { run, running };
diff --git a/src/features/Settings/trash/features/typeMeta.ts b/src/features/Settings/trash/features/typeMeta.ts
index 8741ad9eed6..9e978ffe2de 100644
--- a/src/features/Settings/trash/features/typeMeta.ts
+++ b/src/features/Settings/trash/features/typeMeta.ts
@@ -5,6 +5,7 @@ import {
GitBranchIcon,
HashIcon,
LayoutDashboardIcon,
+ ListTodoIcon,
MessageSquareIcon,
} from 'lucide-react';
@@ -15,6 +16,7 @@ export const TRASH_TYPE_ICON: Record<TrashResourceType, typeof HashIcon> = {
channelThread: GitBranchIcon,
dashboard: LayoutDashboardIcon,
message: MessageSquareIcon,
+ task: ListTodoIcon,
topic: HashIcon,
widget: ChartNoAxesColumnIcon,
};
@@ -23,6 +25,7 @@ export const TRASH_TYPE_ICON: Record<TrashResourceType, typeof HashIcon> = {
export const TRASH_TYPE_ORDER: TrashResourceType[] = [
'topic',
'agent',
+ 'task',
'message',
'widget',
'dashboard',
diff --git a/src/services/task.ts b/src/services/task.ts
index 2be854f69b9..fa96a783d03 100644
--- a/src/services/task.ts
+++ b/src/services/task.ts
@@ -199,6 +199,15 @@ class TaskService {
batchDelete = async (ids: string[]) => lambdaClient.task.batchDelete.mutate({ ids });
+ /** Undo of a batch status / field / archive change (the `reverts` it returned). */
+ batchRevert = async (
+ reverts: Parameters<typeof lambdaClient.task.batchRevert.mutate>[0]['reverts'],
+ ) => lambdaClient.task.batchRevert.mutate({ reverts });
+
+ /** Undo of a batch delete: restore the tasks from the recycle bin. */
+ batchRestoreDeleted = async (ids: string[]) =>
+ lambdaClient.task.batchRestoreDeleted.mutate({ ids });
+
delete = async (id: string) => lambdaClient.task.delete.mutate({ id });
archive = async (id: string, archived: boolean) =>
diff --git a/src/store/task/slices/list/action.test.ts b/src/store/task/slices/list/action.test.ts
index b3a5df10c08..66689dc21a1 100644
--- a/src/store/task/slices/list/action.test.ts
+++ b/src/store/task/slices/list/action.test.ts
@@ -4,6 +4,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import { createReplicaState } from '@/libs/replica';
import { useTaskStore } from '../../store';
+import { taskGroupListQueryKey, taskListQueryKey } from './projection';
// Mock task service
vi.mock('@/services/task', () => ({
@@ -541,12 +542,12 @@ describe('TaskListSliceAction', () => {
});
it('walks every page with a keyset cursor and merges them', async () => {
- const rows = dataset(230);
+ const rows = dataset(730);
serve(() => rows);
const result = await runFetcher({ complete: true });
- expect(taskServiceList).toHaveBeenCalledTimes(3);
+ expect(taskServiceList).toHaveBeenCalledTimes(2);
expect(taskServiceList).toHaveBeenNthCalledWith(
1,
expect.not.objectContaining({ after: expect.anything() }),
@@ -554,16 +555,12 @@ describe('TaskListSliceAction', () => {
expect(taskServiceList).toHaveBeenNthCalledWith(
2,
expect.objectContaining({
- after: { at: rows[99].createdAt, seq: rows[99].seq },
- limit: 100,
+ after: { at: rows[499].createdAt, seq: rows[499].seq },
+ limit: 500,
}),
);
- expect(taskServiceList).toHaveBeenNthCalledWith(
- 3,
- expect.objectContaining({ after: { at: rows[199].createdAt, seq: rows[199].seq } }),
- );
- expect(result.data).toHaveLength(230);
- expect(result.total).toBe(230);
+ expect(result.data).toHaveLength(730);
+ expect(result.total).toBe(730);
});
it('issues a single request when the first page already holds everything', async () => {
@@ -579,12 +576,12 @@ describe('TaskListSliceAction', () => {
// never see the last live row; the cursor keeps walking from the last row
// it holds, so nothing live is skipped.
it('does not skip a row when a task is deleted between two pages', async () => {
- let rows = dataset(101);
+ let rows = dataset(501);
serve(() => rows);
vi.mocked(taskServiceList).mockImplementationOnce(async (params: any) => {
const page = rows.slice(0, params.limit);
rows = rows.filter((r) => r.seq !== 50); // deleted after page one was read
- return { data: page, success: true, total: 101 } as any;
+ return { data: page, success: true, total: 501 } as any;
});
const result = await runFetcher({ complete: true });
@@ -592,7 +589,7 @@ describe('TaskListSliceAction', () => {
const ids = result.data.map((r) => r.id);
expect(new Set(ids).size).toBe(ids.length);
expect(ids).toContain('t1'); // the last live row, which an offset walk drops
- expect(result.total).toBe(101);
+ expect(result.total).toBe(501);
});
it('stops at the row ceiling and keeps the real total so the UI can say so', async () => {
@@ -600,7 +597,7 @@ describe('TaskListSliceAction', () => {
const result = await runFetcher({ complete: true });
- expect(taskServiceList).toHaveBeenCalledTimes(10);
+ expect(taskServiceList).toHaveBeenCalledTimes(2);
expect(result.data).toHaveLength(1000);
expect(result.total).toBe(1500);
});
@@ -617,3 +614,128 @@ describe('TaskListSliceAction', () => {
});
});
});
+
+describe('internal_beginCollectionTasksOptimistic', () => {
+ const task = (id: string, status = 'backlog', extra: Record<string, unknown> = {}) =>
+ ({ id, identifier: id.toUpperCase(), priority: 0, status, ...extra }) as any;
+ const listKey = (includeArchived?: boolean) =>
+ taskListQueryKey({ allAgents: true, includeArchived, visibility: 'all' } as any);
+ const boardKey = taskGroupListQueryKey({ groupBy: 'status', visibility: 'all' } as any);
+ const seed = () =>
+ useTaskStore.setState({
+ taskGroupListMap: {
+ [boardKey]: {
+ groupBy: 'status',
+ groups: [
+ { key: 'backlog', tasks: [task('a'), task('b'), task('c')], total: 3 },
+ { key: 'done', tasks: [], total: 0 },
+ ],
+ } as any,
+ },
+ taskListMap: {
+ [listKey()]: { items: [task('a'), task('b'), task('c')], total: 3 },
+ [listKey(true)]: { items: [task('a'), task('b')], total: 2 },
+ },
+ });
+ const items = (key: string) => useTaskStore.getState().taskListMap[key].items;
+ const column = (key: string) =>
+ useTaskStore
+ .getState()
+ .taskGroupListMap[boardKey].groups.find((group) => group.key === key)!
+ .tasks.map((t) => t.id);
+
+ it('patches every selected row in every loaded list and board at once', () => {
+ seed();
+ useTaskStore
+ .getState()
+ .internal_beginCollectionTasksOptimistic(['a', 'b'], (t) => ({ ...t, status: 'completed' }));
+
+ expect(items(listKey()).map((t) => t.status)).toEqual(['completed', 'completed', 'backlog']);
+ expect(items(listKey(true)).map((t) => t.status)).toEqual(['completed', 'completed']);
+ // The status board moves the cards.
+ expect(column('backlog')).toEqual(['c']);
+ expect(column('done')).toEqual(['a', 'b']);
+ });
+
+ it('removes rows only where the patch says so, by collection', () => {
+ seed();
+ useTaskStore
+ .getState()
+ .internal_beginCollectionTasksOptimistic(['a'], (t, query) =>
+ query.includeArchived ? { ...t, archivedAt: new Date() } : undefined,
+ );
+
+ expect(items(listKey()).map((t) => t.id)).toEqual(['b', 'c']);
+ expect(useTaskStore.getState().taskListMap[listKey()].total).toBe(2);
+ expect(items(listKey(true)).map((t) => t.id)).toEqual(['a', 'b']);
+ expect(items(listKey(true))[0].archivedAt).toBeInstanceOf(Date);
+ });
+
+ it('commit keeps only the rows the server changed, with its values', () => {
+ seed();
+ const patch = (t: any) => ({ ...t, status: 'completed' });
+ const overlay = useTaskStore
+ .getState()
+ .internal_beginCollectionTasksOptimistic(['a', 'b'], patch);
+
+ overlay.commit(new Map([['a', (t: any) => ({ ...patch(t), completedAt: 'server' })]]));
+
+ expect(items(listKey()).map((t) => [t.id, t.status])).toEqual([
+ ['a', 'completed'],
+ ['b', 'backlog'],
+ ['c', 'backlog'],
+ ]);
+ expect((items(listKey())[0] as any).completedAt).toBe('server');
+ expect(column('backlog')).toEqual(['b', 'c']);
+ expect(column('done')).toEqual(['a']);
+ });
+
+ it('rollback restores every collection exactly', () => {
+ seed();
+ const before = useTaskStore.getState();
+ const overlay = useTaskStore
+ .getState()
+ .internal_beginCollectionTasksOptimistic(['a', 'b', 'c'], () => undefined);
+ expect(items(listKey())).toEqual([]);
+
+ overlay.rollback();
+
+ expect(useTaskStore.getState().taskListMap).toEqual(before.taskListMap);
+ expect(useTaskStore.getState().taskGroupListMap).toEqual(before.taskGroupListMap);
+ });
+
+ it('leaves collections that hold none of the rows untouched', () => {
+ seed();
+ const untouched = useTaskStore.getState().taskListMap[listKey(true)];
+ useTaskStore
+ .getState()
+ .internal_beginCollectionTasksOptimistic(['c'], (t) => ({ ...t, priority: 3 }));
+
+ expect(useTaskStore.getState().taskListMap[listKey(true)]).toBe(untouched);
+ });
+});
+
+describe('internal_beginCollectionTasksOptimistic query shape', () => {
+ it("tells the patch each collection's assignee scope", () => {
+ const row = { id: 'a', identifier: 'A', status: 'backlog' } as any;
+ const agentKey = taskListQueryKey({ agentId: 'alpha', visibility: 'all' } as any);
+ const mineKey = taskListQueryKey({ scope: 'assigned', visibility: 'all' } as any);
+ useTaskStore.setState({
+ taskListMap: {
+ [agentKey]: { items: [row], total: 1 },
+ [mineKey]: { items: [row], total: 1 },
+ },
+ });
+ const seen: unknown[] = [];
+ useTaskStore.getState().internal_beginCollectionTasksOptimistic(['a'], (t, query) => {
+ seen.push(query);
+ return t;
+ });
+ expect(seen).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ agentId: 'alpha', includeArchived: false }),
+ expect.objectContaining({ includeArchived: false, scope: 'assigned' }),
+ ]),
+ );
+ });
+});
diff --git a/src/store/task/slices/list/action.ts b/src/store/task/slices/list/action.ts
index 818562d1307..c61ab3e157a 100644
--- a/src/store/task/slices/list/action.ts
+++ b/src/store/task/slices/list/action.ts
@@ -51,12 +51,13 @@ const filterToServerVisibility = (
};
/**
- * `complete` mode paging. The server caps one `task.list` page at 100 rows, so
- * the full list is assembled from consecutive pages; the ceiling bounds the
- * fan-out for very large workspaces (10 requests) — past it the store keeps
- * the real `total` so the list can say it is showing a subset.
+ * `complete` mode paging. The server caps one `task.list` page at 500 rows, so
+ * the full list is assembled from consecutive pages — sequential round trips,
+ * so the page is as large as the server allows; the ceiling bounds the fan-out
+ * for very large workspaces (2 requests) — past it the store keeps the real
+ * `total` so the list can say it is showing a subset.
*/
-export const COMPLETE_TASK_LIST_PAGE_SIZE = 100;
+export const COMPLETE_TASK_LIST_PAGE_SIZE = 500;
/** Page size of the Tasks page's paginated collections (scheduled, "My tasks"). */
export const TASK_COLLECTION_PAGE_SIZE = 50;
@@ -112,6 +113,51 @@ export interface TaskCollectionSyncResult extends ReplicaSyncResult {
queryKey?: string;
}
+/** What a batch overlay needs to know about the collection it patches. */
+export interface CollectionQueryShape {
+ /** The collection is one agent's tasks (assignee filter). */
+ agentId?: string;
+ /** The collection lists archived rows ("Show archived"); undefined when unknown. */
+ includeArchived?: boolean;
+ /** "My tasks" narrowing. */
+ scope?: 'assigned' | 'created';
+}
+
+/** A batch overlay's patch of one task; `undefined` takes the row out of the collection. */
+export type CollectionTasksPatch = (
+ task: CollectionTask,
+ query: CollectionQueryShape,
+) => CollectionTask | undefined;
+
+export interface CollectionTasksOptimistic {
+ /** Keep the rows in `keep` (id → final patch; default: every id, original patch). */
+ commit: (keep?: ReadonlyMap<string, CollectionTasksPatch>) => void;
+ rollback: () => void;
+}
+
+/**
+ * The query behind a list / board entry, read back from its key (the
+ * canonical JSON `stableQueryKey` writes). A key that does not parse — or a
+ * persisted row patched without its key — reports nothing.
+ */
+const collectionQueryShape = (queryKey?: string): CollectionQueryShape => {
+ if (!queryKey) return {};
+ try {
+ const query = JSON.parse(queryKey) as {
+ agentId?: unknown;
+ includeArchived?: unknown;
+ scope?: unknown;
+ };
+ return {
+ agentId: typeof query?.agentId === 'string' ? query.agentId : undefined,
+ includeArchived: query?.includeArchived === true,
+ scope: query?.scope === 'assigned' || query?.scope === 'created' ? query.scope : undefined,
+ };
+ } catch {
+ return {};
+ }
+};
+
type Setter = StoreSetter<TaskStore>;
export const createTaskListSlice = (set: Setter, get: () => TaskStore, _api?: unknown) =>
@@ -256,6 +302,95 @@ export class TaskListSliceActionImpl {
};
};
+ /**
+ * `internal_beginCollectionTaskOptimistic` for a whole selection (the list's
+ * batch actions): ONE overlay per loaded list / board that holds any of
+ * `ids`, applying `fn` to each of them — a 500-task batch is one store write
+ * per collection, not one per task. `fn` returning `undefined` takes the row
+ * out (delete, archive in a list that hides archived rows); it is told
+ * whether the collection shows archived rows.
+ *
+ * `commit(keep)` settles with the rows the server actually changed: `keep`
+ * maps those ids to their final patch (default: `fn` for every id), so a
+ * failed or skipped row falls back to its confirmed value while the others
+ * stay as shown until the refresh lands — persisted, unloaded lists and
+ * boards get the same change. `rollback` restores every collection exactly.
+ */
+ internal_beginCollectionTasksOptimistic = (
+ ids: readonly string[],
+ fn: CollectionTasksPatch,
+ ): CollectionTasksOptimistic => {
+ const wanted = new Set(ids);
+ const { taskGroupListMap, taskListMap } = this.#get();
+ const applyTo =
+ <TValue>(
+ entity: {
+ map: (data: TValue, id: string, fn: (task: any) => any) => TValue | undefined;
+ },
+ patches: ReadonlyMap<string, CollectionTasksPatch>,
+ query: CollectionQueryShape,
+ ) =>
+ (data: TValue): TValue => {
+ let next = data;
+ for (const [id, patch] of patches) {
+ // Task adapters drop a row, never the whole value; keep it if one did.
+ next = entity.map(next, id, (task: CollectionTask) => patch(task, query)) ?? next;
+ }
+ return next;
+ };
+ const all = new Map(ids.map((id) => [id, fn] as const));
+
+ const listKeys = Object.entries(taskListMap)
+ .filter(([, value]) => value.items.some((task) => wanted.has(task.id)))
+ .map(([key]) => key);
+ const groupKeys = Object.entries(taskGroupListMap)
+ .filter(([, value]) =>
+ value.groups.some((group) => group.tasks.some((task) => wanted.has(task.id))),
+ )
+ .map(([key]) => key);
+
+ const listTokens = listKeys.map((key) => ({
+ key,
+ token: this.#taskList.beginOptimistic(
+ key,
+ applyTo(taskListEntity, all, collectionQueryShape(key)),
+ ),
+ }));
+ const groupTokens = groupKeys.map((key) => ({
+ key,
+ token: this.#taskGroupList.beginOptimistic(
+ key,
+ applyTo(taskGroupListEntity, all, collectionQueryShape(key)),
+ ),
+ }));
+
+ let settled = false;
+ return {
+ commit: (keep = all) => {
+ if (settled) return;
+ settled = true;
+ for (const { key, token } of listTokens)
+ token.commit(applyTo(taskListEntity, keep, collectionQueryShape(key)));
+ for (const { key, token } of groupTokens)
+ token.commit(applyTo(taskGroupListEntity, keep, collectionQueryShape(key)));
+ if (keep.size === 0) return;
+ // Persisted lists and boards that are not loaded: one pass over the
+ // stored rows per resource, whatever the selection size.
+ void this.#taskList.patchStoredRows((data) =>
+ applyTo(taskListEntity, keep, collectionQueryShape())(data),
+ );
+ void this.#taskGroupList.patchStoredRows((data) =>
+ applyTo(taskGroupListEntity, keep, collectionQueryShape())(data),
+ );
+ },
+ rollback: () => {
+ if (settled) return;
+ settled = true;
+ for (const { token } of [...listTokens, ...groupTokens]) token.rollback();
+ },
+ };
+ };
+
/**
* Optimistic overlay on one board (a drag between columns): shows now,
* `commit` keeps it until the refresh lands, `rollback` restores the board.
@@ -551,7 +686,7 @@ export class TaskListSliceActionImpl {
}
: undefined;
const queryKey = query ? taskListQueryKey(query) : undefined;
- // No refetch on focus: a `complete` list walks up to ten pages per sync.
+ // No refetch on focus: a `complete` list walks up to two pages per sync.
const sync = this.#taskList.useSync(query, { enabled, revalidateOnFocus: false });
return this.#toSyncResult(
sync,