π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix(task): cascade-delete the underlying topics when a task is deleted (#20871)
Arvin Xu24a37a55c2ce
diff --git a/apps/server/src/services/task/index.test.ts b/apps/server/src/services/task/index.test.tsindex c9e78d85170..887d26d82af 100644--- a/apps/server/src/services/task/index.test.ts+++ b/apps/server/src/services/task/index.test.ts@@ -6,6 +6,7 @@ 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 { UserModel } from '@/database/models/user';import { WorkspaceMemberModel } from '@/database/models/workspaceMember';import type { LobeChatDatabase } from '@/database/type';@@ -43,6 +44,10 @@ vi.mock('@/database/models/taskTopic', () => ({TaskTopicModel: vi.fn(),}));+vi.mock('@/database/models/topic', () => ({+ TopicModel: vi.fn(),+}));+vi.mock('@/database/models/brief', () => ({BriefModel: vi.fn(),}));@@ -141,6 +146,10 @@ describe('TaskService', () => {timeoutRunning: vi.fn(),};+ const mockTopicModel = {+ batchDeleteIncludingTrashed: vi.fn().mockResolvedValue(undefined),+ };+const mockBriefModel = {findByTaskId: vi.fn(),};@@ -161,6 +170,7 @@ describe('TaskService', () => {resolveTaskAcceptance.mockResolvedValue(undefined);mockTaskTopicModel.findRunningByTaskIds.mockResolvedValue([]);mockTaskModel.getActivities.mockResolvedValue([]);+ mockTopicModel.batchDeleteIncludingTrashed.mockResolvedValue(undefined);(AgentModel as any).mockImplementation(function () {return mockAgentModel;});@@ -170,6 +180,9 @@ describe('TaskService', () => {(TaskTopicModel as any).mockImplementation(function () {return mockTaskTopicModel;});+ (TopicModel as any).mockImplementation(function () {+ return mockTopicModel;+ });(BriefModel as any).mockImplementation(function () {return mockBriefModel;});@@ -1548,6 +1561,7 @@ describe('TaskService', () => {(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 () => {@@ -1688,6 +1702,90 @@ describe('TaskService', () => {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.resolve.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.resolve.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.resolve.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.resolve.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', () => {diff --git a/apps/server/src/services/task/index.ts b/apps/server/src/services/task/index.tsindex fbdc5a18a5a..b32cccca03d 100644--- a/apps/server/src/services/task/index.ts+++ b/apps/server/src/services/task/index.ts@@ -400,19 +400,50 @@ export class TaskService {// seen here and wins; a run that records later finds the task gone and// 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).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);if (!(await taskModel.lockForUpdate(task.id))) return 'gone' as const;- const nowRunning = await new TaskTopicModel(- tx,- this.userId,- this.workspaceId,- ).findRunningByTaskIds([task.id]);+ const taskTopicModel = new TaskTopicModel(tx, this.userId, this.workspaceId);+ const nowRunning = await taskTopicModel.findRunningByTaskIds([task.id]);if (nowRunning.some((topic) => !handled.has(topic.operationId))) return 'conflict' as const;- return (await taskModel.deleteIfStatus(task.id, task.status))- ? ('deleted' as const)- : ('conflict' as const);++ // The row lock guarantees no run can record a topic between here and+ // the status CAS below, so this snapshot is the complete topic set.+ // `keepOperationId` spares the caller's own run: its topic must survive+ // with the operation, or the messages ON DELETE CASCADE would pull the+ // conversation out from under the still-running tool call.+ const allTopics = await taskTopicModel.findByTaskId(task.id);+ const topicIds = allTopics+ .filter(+ (topic) =>+ !topic.topicId ||+ !options.keepOperationId ||+ topic.operationId !== options.keepOperationId,+ )+ .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,+ );+ }+ return 'deleted' as const;});if (outcome === 'conflict') {throw new TRPCError({diff --git a/packages/builtin-tool-task/src/systemRole.ts b/packages/builtin-tool-task/src/systemRole.tsindex 7611937f147..62a21bbc16a 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+- **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 β always quote the identifier freshly returned by createTask/listTasks, never a remembered oneSchedule fields (setTaskSchedule):- **automationMode**: 'schedule' (cron-based) or 'heartbeat' (fixed interval). Pass null to disable automationdiff --git a/packages/database/src/models/__tests__/topic.test.ts b/packages/database/src/models/__tests__/topic.test.tsindex 74f93b9dcdf..b47a9a118ed 100644--- a/packages/database/src/models/__tests__/topic.test.ts+++ b/packages/database/src/models/__tests__/topic.test.ts@@ -1659,6 +1659,19 @@ describe('TopicModel', () => {expect(remaining.map((t) => t.id)).toEqual(['b3']);});+ it('batchDeleteIncludingTrashed also removes topics sitting in the recycle bin', async () => {+ await serverDB.insert(topics).values([+ { id: 'bt-live', title: 'live', userId },+ { id: 'bt-trash', isDeleted: true, title: 'trashed', userId },+ { id: 'bt-other', title: 'keep', userId },+ ]);++ await topicModel.batchDeleteIncludingTrashed(['bt-live', 'bt-trash']);++ const remaining = await serverDB.select().from(topics);+ expect(remaining.map((t) => t.id)).toEqual(['bt-other']);+ });+it('deleteAll removes only the calling user rows', async () => {await serverDB.insert(topics).values([{ id: 'mine-1', title: '1', userId },diff --git a/packages/database/src/models/topic.ts b/packages/database/src/models/topic.tsindex 84bcc3f8bd4..ae96979f00b 100644--- a/packages/database/src/models/topic.ts+++ b/packages/database/src/models/topic.ts@@ -1914,6 +1914,18 @@ export class TopicModel {.where(and(inArray(topics.id, ids), this.ownership(), this.notShareVisitor()));};+ /**+ * Hard delete by id that also reaches rows already in the recycle bin β+ * same ownership + share-visitor guards as {@link batchDelete}, scoped with+ * {@link trashScope} (`includeTrashed`) instead of {@link ownership}. For+ * cascade paths that own their id list: a linked topic sitting in the+ * recycle bin must not survive its parent's deletion and resurrect as a+ * sidebar orphan when the user later restores it.+ */+ batchDeleteIncludingTrashed = async (ids: string[]) => {+ return this.db.delete(topics).where(and(inArray(topics.id, ids), this.trashScope()));+ };+/*** Creator-facing "clear all my topics".*