🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(tasks): cascade terminal status to subtasks (#19158)
Arvin Xu02e41c2c8c5e
diff --git a/apps/server/src/routers/lambda/__tests__/integration/task.integration.test.ts b/apps/server/src/routers/lambda/__tests__/integration/task.integration.test.tsindex fe024284856..02a9b89feba 100644--- a/apps/server/src/routers/lambda/__tests__/integration/task.integration.test.ts+++ b/apps/server/src/routers/lambda/__tests__/integration/task.integration.test.ts@@ -5,6 +5,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { AcceptanceModel } from '@/database/models/acceptance';import { TaskModel } from '@/database/models/task';+import { TaskTopicModel } from '@/database/models/taskTopic';import { taskRouter } from '../../task';import {@@ -1079,6 +1080,127 @@ describe('Task Router Integration', () => {});});+ describe('updateStatusCascade', () => {+ it('updates the task family atomically without rewriting failed subtasks', async () => {+ const parent = await caller.create({ instruction: 'Parent' });+ const open = await caller.create({+ instruction: 'Open',+ parentTaskId: parent.data.id,+ });+ const failed = await caller.create({+ instruction: 'Failed',+ parentTaskId: parent.data.id,+ });+ await caller.updateStatus({ error: 'Needs attention', id: failed.data.id, status: 'failed' });++ const result = await caller.updateStatusCascade({+ id: parent.data.identifier,+ status: 'completed',+ });++ expect(result.data.updatedSubtasks).toEqual([open.data.identifier]);+ expect((await caller.find({ id: parent.data.id })).data.status).toBe('completed');+ expect((await caller.find({ id: open.data.id })).data.status).toBe('completed');+ expect((await caller.find({ id: failed.data.id })).data).toMatchObject({+ error: 'Needs attention',+ status: 'failed',+ });+ });++ it('does not start a dependent sibling while completing the whole family', async () => {+ const parent = await caller.create({ instruction: 'Parent' });+ const first = await caller.create({+ assigneeAgentId: testAgentId,+ instruction: 'First',+ parentTaskId: parent.data.id,+ });+ const dependent = await caller.create({+ assigneeAgentId: testAgentId,+ instruction: 'Dependent',+ parentTaskId: parent.data.id,+ });+ await caller.addDependency({ dependsOnId: first.data.id, taskId: dependent.data.id });+ mockExecAgent.mockClear();++ await caller.updateStatusCascade({ id: parent.data.id, status: 'completed' });++ expect(mockExecAgent).not.toHaveBeenCalled();+ expect((await caller.find({ id: first.data.id })).data.status).toBe('completed');+ expect((await caller.find({ id: dependent.data.id })).data.status).toBe('completed');+ });++ it('starts an external dependent unlocked by the family completion', async () => {+ const parent = await caller.create({ instruction: 'Parent' });+ const sub = await caller.create({ instruction: 'Sub', parentTaskId: parent.data.id });+ const external = await caller.create({+ assigneeAgentId: testAgentId,+ instruction: 'External',+ });+ await caller.addDependency({ dependsOnId: sub.data.id, taskId: external.data.id });+ mockExecAgent.mockClear();++ const result = await caller.updateStatusCascade({ id: parent.data.id, status: 'completed' });++ expect(result.data.unlocked).toEqual([external.data.identifier]);+ expect(mockExecAgent).toHaveBeenCalledTimes(1);+ expect((await caller.find({ id: external.data.id })).data.status).toBe('running');+ });++ it('persists successful interrupts before surfacing a partial interrupt failure', async () => {+ const parent = await caller.create({ instruction: 'Parent' });+ const subA = await caller.create({+ assigneeAgentId: testAgentId,+ instruction: 'A',+ parentTaskId: parent.data.id,+ });+ const subB = await caller.create({+ assigneeAgentId: testAgentId,+ instruction: 'B',+ parentTaskId: parent.data.id,+ });++ const topicA = await createTestTopic(serverDB, userId, 'tpc_cascade_a');+ const topicB = await createTestTopic(serverDB, userId, 'tpc_cascade_b');+ mockExecAgent.mockResolvedValueOnce({+ operationId: 'op_cascade_a',+ success: true,+ topicId: topicA,+ });+ mockExecAgent.mockResolvedValueOnce({+ operationId: 'op_cascade_b',+ success: true,+ topicId: topicB,+ });+ await caller.run({ id: subA.data.id });+ await caller.run({ id: subB.data.id });++ mockInterruptTask.mockImplementation(async ({ operationId }: { operationId: string }) => {+ if (operationId === 'op_cascade_a') throw new Error('gateway unreachable');+ return { success: true };+ });++ await expect(+ caller.updateStatusCascade({ id: parent.data.id, status: 'canceled' }),+ ).rejects.toThrow('Failed to update task family status');++ // No status was cascaded — the family is untouched.+ expect((await caller.find({ id: parent.data.id })).data.status).toBe('backlog');+ expect((await caller.find({ id: subA.data.id })).data.status).toBe('running');+ expect((await caller.find({ id: subB.data.id })).data.status).toBe('running');++ // But the interrupt that did succeed is persisted: B's topic is no+ // longer recorded as running, while A's (failed interrupt) still is.+ const topicModel = new TaskTopicModel(serverDB, userId);+ const [aTopic] = await topicModel.findByTaskId(subA.data.id);+ const [bTopic] = await topicModel.findByTaskId(subB.data.id);+ expect(aTopic!.status).toBe('running');+ expect(bTopic!.status).toBe('canceled');++ // clearAllMocks does not restore implementations — undo the override.+ mockInterruptTask.mockImplementation(async () => ({ success: true }));+ });+ });+describe('list participants', () => {it('should populate participants from assignee agent', async () => {const { agents } = await import('@/database/schemas');diff --git a/apps/server/src/routers/lambda/task.ts b/apps/server/src/routers/lambda/task.tsindex 4808cb4ddf0..5e0e82bdbaa 100644--- a/apps/server/src/routers/lambda/task.ts+++ b/apps/server/src/routers/lambda/task.ts@@ -1735,6 +1735,28 @@ export const taskRouter = router({}}),+ updateStatusCascade: taskProcedureWrite+ .input(+ z.object({+ id: z.string(),+ status: z.enum(['canceled', 'completed']),+ }),+ )+ .mutation(async ({ input, ctx }) => {+ try {+ const result = await ctx.taskService.updateStatusCascade(input);+ return { data: result, message: `Task family ${input.status}`, success: true };+ } catch (error) {+ if (error instanceof TRPCError) throw error;+ console.error('[task:updateStatusCascade]', error);+ throw new TRPCError({+ cause: error,+ code: 'INTERNAL_SERVER_ERROR',+ message: 'Failed to update task family status',+ });+ }+ }),+// Cross-workspace task *transfer* is intentionally not supported anymore:// moving a task drags its whole subtree plus history (dependencies,// documents, comments) out of the workspace. Use `copyTaskToWorkspace`,diff --git a/apps/server/src/services/task/index.ts b/apps/server/src/services/task/index.tsindex 28d585afe48..60d95830f03 100644--- a/apps/server/src/services/task/index.ts+++ b/apps/server/src/services/task/index.ts@@ -1,5 +1,6 @@import { randomUUID } from 'node:crypto';+import { UNFINISHED_TASK_STATUSES } from '@lobechat/builtin-tool-task';import { TASK_ASSIGNEE_PERMISSION_CODES } from '@lobechat/const/rbac';import type {TaskContext,@@ -89,6 +90,13 @@ export interface UpdateStatusResult {unlocked: string[];}+export interface UpdateStatusCascadeResult {+ paused: string[];+ task: TaskItem;+ unlocked: string[];+ updatedSubtasks: string[];+}+export interface RunReadySubtasksResult {failed: { error: string; identifier: string }[];kickedOff: string[];@@ -530,6 +538,97 @@ export class TaskService {};}+ /**+ * Transition a parent and every currently unfinished direct subtask as one+ * database transaction. Completion side effects run only after the whole+ * family has reached the target status, so dependency edges cannot start a+ * sibling in the middle of the cascade.+ */+ async updateStatusCascade(input: {+ id: string;+ status: 'canceled' | 'completed';+ }): Promise<UpdateStatusCascadeResult> {+ const resolved = await this.resolveOrThrow(input.id);+ const subtasks = await this.taskModel.findSubtasks(resolved.id);+ const unfinishedStatuses = new Set<string>(UNFINISHED_TASK_STATUSES);+ const openSubtasks = subtasks.filter((task) => unfinishedStatuses.has(task.status));+ // Freeze the cascade to this snapshot: both the interrupt pass and the+ // status update operate on the same id set, so a subtask created or+ // transitioned after the confirmation dialog is never rewritten.+ const targetTasks = [resolved, ...openSubtasks];+ const targetIds = targetTasks.map((task) => task.id);++ const aiAgentService = new AiAgentService(this.db, this.userId, {+ workspaceId: this.workspaceId,+ });++ const runningTopics = await this.taskTopicModel.findRunningByTaskIds(targetIds);+ if (runningTopics.length > 0) {+ const settled = await Promise.allSettled(+ runningTopics.map(async (topic) => {+ if (topic.operationId) {+ await aiAgentService.interruptTask({ operationId: topic.operationId });+ }+ }),+ );+ const failure = settled.find((result) => result.status === 'rejected');+ if (failure) {+ // Persist the interrupts that did succeed before surfacing the error,+ // so an actually-stopped operation is not left recorded as running.+ for (const [index, topic] of runningTopics.entries()) {+ if (settled[index].status !== 'fulfilled' || !topic.topicId) continue;+ await this.taskTopicModel+ .cancelIfRunning(topic.taskId, topic.topicId)+ .catch(() => undefined);+ }+ throw failure.reason;+ }+ }++ const completedAt = new Date();+ let updatedTasks: TaskItem[] = [];+ let canceledTopics: Awaited<ReturnType<TaskTopicModel['cancelRunningByTaskIds']>> = [];+ await this.db.transaction(async (tx) => {+ const taskModel = new TaskModel(tx, this.userId, this.workspaceId);+ const taskTopicModel = new TaskTopicModel(tx, this.userId, this.workspaceId);++ // Cancel by the frozen id set rather than the pre-read topic list, so a+ // topic that started between the snapshot and this transaction is still+ // closed together with the status update.+ canceledTopics = await taskTopicModel.cancelRunningByTaskIds(targetIds);+ updatedTasks = await taskModel.updateStatusForIds(targetIds, input.status, { completedAt });+ });++ // Best-effort: stop any operation discovered only inside the transaction.+ const interruptedOperationIds = new Set(runningTopics.map((topic) => topic.operationId));+ await Promise.allSettled(+ canceledTopics+ .filter((topic) => topic.operationId && !interruptedOperationIds.has(topic.operationId))+ .map((topic) => aiAgentService.interruptTask({ operationId: topic.operationId! })),+ );++ const task = updatedTasks.find(({ id }) => id === resolved.id);+ if (!task) throw new TRPCError({ code: 'NOT_FOUND', message: 'Task not found' });++ const unlocked: string[] = [];+ const paused: string[] = [];+ if (input.status === 'completed') {+ const runner = new TaskRunnerService(this.db, this.userId, this.workspaceId);+ const cascade = await runner.cascadeOnCompletionMany(updatedTasks.map(({ id }) => id));+ unlocked.push(...cascade.started);+ paused.push(...cascade.paused);+ }++ return {+ paused,+ task,+ unlocked,+ updatedSubtasks: updatedTasks+ .filter(({ parentTaskId }) => parentTaskId === resolved.id)+ .map(({ identifier }) => identifier),+ };+ }+/*** Compute the subtask execution plan for `idOrIdentifier` without* actually kicking anything off.diff --git a/apps/server/src/services/taskRunner/index.ts b/apps/server/src/services/taskRunner/index.tsindex 93bf812563f..0503503e83a 100644--- a/apps/server/src/services/taskRunner/index.ts+++ b/apps/server/src/services/taskRunner/index.ts@@ -326,7 +326,17 @@ export class TaskRunnerService {* with the error recorded — the same fallback used by the runner itself.*/async cascadeOnCompletion(completedTaskId: string): Promise<CascadeResult> {- const unlocked = await this.taskModel.getUnlockedTasks(completedTaskId);+ return this.cascadeOnCompletionMany([completedTaskId]);+ }++ /**+ * Batched variant of {@link cascadeOnCompletion} for family-wide status+ * cascades: dependents are discovered across all completed ids in one pass,+ * so completing N tasks costs a constant number of discovery queries instead+ * of N dependency walks.+ */+ async cascadeOnCompletionMany(completedTaskIds: string[]): Promise<CascadeResult> {+ const unlocked = await this.taskModel.getUnlockedTasksForMany(completedTaskIds);if (unlocked.length === 0) return TaskRunnerService.cascadeEmpty();const result: CascadeResult = { failed: [], paused: [], started: [] };diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex 0b312503eb2..8152f60b0b3 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -1675,6 +1675,13 @@"taskDetail.status.paused": "Pending review","taskDetail.status.running": "In progress","taskDetail.status.scheduled": "Scheduled",+ "taskDetail.statusCascade.applyFailed": "Could not update the task status. Try again.",+ "taskDetail.statusCascade.cancel": "Cancel",+ "taskDetail.statusCascade.description": "This task still has {{count}} open subtask(s). Update them to {{status}} too?",+ "taskDetail.statusCascade.loadFailed": "Could not check the subtask statuses. Try again.",+ "taskDetail.statusCascade.parentOnly": "Update parent only",+ "taskDetail.statusCascade.title": "Update open subtasks too?",+ "taskDetail.statusCascade.updateAll": "Update all","taskDetail.stopTask": "Stop task","taskDetail.subIssueOf": "Sub-issue of","taskDetail.subtaskInstructionPlaceholder": "Describe the sub-task...",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex 3ad191b05c8..10a40741af4 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -1675,6 +1675,13 @@"taskDetail.status.paused": "待审阅","taskDetail.status.running": "进行中","taskDetail.status.scheduled": "已排期",+ "taskDetail.statusCascade.applyFailed": "任务状态更新失败,请重试。",+ "taskDetail.statusCascade.cancel": "取消",+ "taskDetail.statusCascade.description": "此任务仍有 {{count}} 个未结束的子任务。是否也将它们更新为“{{status}}”?",+ "taskDetail.statusCascade.loadFailed": "无法检查子任务状态,请重试。",+ "taskDetail.statusCascade.parentOnly": "仅更新父任务",+ "taskDetail.statusCascade.title": "同时更新未结束的子任务?",+ "taskDetail.statusCascade.updateAll": "全部更新","taskDetail.stopTask": "停止任务","taskDetail.subIssueOf": "隶属于","taskDetail.subtaskInstructionPlaceholder": "描述这个子任务…",diff --git a/packages/database/src/models/__tests__/task.test.ts b/packages/database/src/models/__tests__/task.test.tsindex 8dff20054de..5c29a294a87 100644--- a/packages/database/src/models/__tests__/task.test.ts+++ b/packages/database/src/models/__tests__/task.test.ts@@ -1874,6 +1874,95 @@ describe('TaskModel', () => {});});+ describe('updateStatusForIds', () => {+ it('updates exactly the frozen id set in one statement', async () => {+ const model = new TaskModel(serverDB, userId);+ const parent = await model.create({ instruction: 'Parent' });+ const open = await model.create({ instruction: 'Open', parentTaskId: parent.id });+ const failed = await model.create({ instruction: 'Failed', parentTaskId: parent.id });+ await model.updateStatus(failed.id, 'failed', { error: 'Needs attention' });++ const updated = await model.updateStatusForIds([parent.id, open.id], 'completed', {+ completedAt: new Date(),+ });++ expect(updated.map(({ id }) => id).sort()).toEqual([open.id, parent.id].sort());+ expect((await model.findById(parent.id))!.status).toBe('completed');+ expect((await model.findById(open.id))!.status).toBe('completed');+ expect(await model.findById(failed.id)).toMatchObject({+ error: 'Needs attention',+ status: 'failed',+ });+ });++ it('does not touch an open subtask outside the frozen id set', async () => {+ const model = new TaskModel(serverDB, userId);+ const parent = await model.create({ instruction: 'Parent' });+ const snapshotted = await model.create({+ instruction: 'Snapshotted',+ parentTaskId: parent.id,+ });+ // Simulates a subtask created (or started) after the caller's snapshot:+ // still unfinished, but absent from the frozen id set.+ const late = await model.create({ instruction: 'Late', parentTaskId: parent.id });+ await model.updateStatus(late.id, 'running');++ await model.updateStatusForIds([parent.id, snapshotted.id], 'canceled');++ expect((await model.findById(parent.id))!.status).toBe('canceled');+ expect((await model.findById(snapshotted.id))!.status).toBe('canceled');+ expect((await model.findById(late.id))!.status).toBe('running');+ });++ it('returns an empty list for an empty id set', async () => {+ const model = new TaskModel(serverDB, userId);+ await expect(model.updateStatusForIds([], 'completed')).resolves.toEqual([]);+ });+ });++ describe('getUnlockedTasksForMany', () => {+ it('discovers dependents unlocked by any of the completed tasks in one pass', async () => {+ const model = new TaskModel(serverDB, userId);+ const a = await model.create({ instruction: 'A' });+ const b = await model.create({ instruction: 'B' });+ const unlockedByA = await model.create({ instruction: 'Unlocked by A' });+ const unlockedByBoth = await model.create({ instruction: 'Unlocked by A and B' });+ const stillBlocked = await model.create({ instruction: 'Still blocked' });+ const blocker = await model.create({ instruction: 'Blocker' });++ await model.addDependency(unlockedByA.id, a.id);+ await model.addDependency(unlockedByBoth.id, a.id);+ await model.addDependency(unlockedByBoth.id, b.id);+ await model.addDependency(stillBlocked.id, a.id);+ await model.addDependency(stillBlocked.id, blocker.id);++ await model.updateStatus(a.id, 'completed');+ await model.updateStatus(b.id, 'completed');++ const unlocked = await model.getUnlockedTasksForMany([a.id, b.id]);++ expect(unlocked.map(({ id }) => id).sort()).toEqual(+ [unlockedByA.id, unlockedByBoth.id].sort(),+ );+ });++ it('skips dependents that are no longer in backlog', async () => {+ const model = new TaskModel(serverDB, userId);+ const done = await model.create({ instruction: 'Done' });+ const started = await model.create({ instruction: 'Already started' });+ await model.addDependency(started.id, done.id);+ await model.updateStatus(done.id, 'completed');+ await model.updateStatus(started.id, 'running');++ await expect(model.getUnlockedTasksForMany([done.id])).resolves.toEqual([]);+ });++ it('returns an empty list for an empty id set', async () => {+ const model = new TaskModel(serverDB, userId);+ await expect(model.getUnlockedTasksForMany([])).resolves.toEqual([]);+ });+ });+describe('updateContext', () => {it('should deep merge into context jsonb', async () => {const model = new TaskModel(serverDB, userId);diff --git a/packages/database/src/models/__tests__/taskTopic.test.ts b/packages/database/src/models/__tests__/taskTopic.test.tsindex 35201d73c55..30a97d33c46 100644--- a/packages/database/src/models/__tests__/taskTopic.test.ts+++ b/packages/database/src/models/__tests__/taskTopic.test.ts@@ -180,6 +180,40 @@ describe('TaskTopicModel', () => {});});+ describe('cancelRunningByTaskIds', () => {+ it('cancels running topics across the given tasks and stamps completedAt', async () => {+ const taskModel = new TaskModel(serverDB, userId);+ const topicModel = new TaskTopicModel(serverDB, userId);+ const taskA = await taskModel.create({ instruction: 'A' });+ const taskB = await taskModel.create({ instruction: 'B' });+ const taskOutside = await taskModel.create({ instruction: 'Outside' });+ await createTopic('tpc_bulk_a');+ await createTopic('tpc_bulk_b');+ await createTopic('tpc_bulk_done');+ await createTopic('tpc_bulk_outside');++ await topicModel.add(taskA.id, 'tpc_bulk_a', { seq: 1 });+ await topicModel.add(taskB.id, 'tpc_bulk_b', { seq: 1 });+ await topicModel.add(taskB.id, 'tpc_bulk_done', { seq: 2 });+ await topicModel.updateStatus(taskB.id, 'tpc_bulk_done', 'completed');+ await topicModel.add(taskOutside.id, 'tpc_bulk_outside', { seq: 1 });++ const canceled = await topicModel.cancelRunningByTaskIds([taskA.id, taskB.id]);++ expect(canceled.map(({ topicId }) => topicId).sort()).toEqual(['tpc_bulk_a', 'tpc_bulk_b']);+ expect((await getTopic('tpc_bulk_a')).completedAt).toBeInstanceOf(Date);+ expect((await getTopic('tpc_bulk_b')).completedAt).toBeInstanceOf(Date);++ const outside = await topicModel.findByTaskId(taskOutside.id);+ expect(outside[0]!.status).toBe('running');+ });++ it('returns an empty list for an empty id set', async () => {+ const topicModel = new TaskTopicModel(serverDB, userId);+ await expect(topicModel.cancelRunningByTaskIds([])).resolves.toEqual([]);+ });+ });+describe('timeoutRunning', () => {it('should timeout running topics only', async () => {const taskModel = new TaskModel(serverDB, userId);diff --git a/packages/database/src/models/task.ts b/packages/database/src/models/task.tsindex 2b2a970f53f..b30fe8ea9c7 100644--- a/packages/database/src/models/task.ts+++ b/packages/database/src/models/task.ts@@ -1213,6 +1213,25 @@ export class TaskModel {return result.length;}+ /**+ * Update a frozen set of task ids in one SQL statement so the family cannot+ * be left partially transitioned. Callers pass the exact ids they snapshotted+ * (and the user confirmed); a task that changes status concurrently is never+ * pulled into the update by a status re-query.+ */+ async updateStatusForIds(+ ids: string[],+ status: string,+ extra?: { completedAt?: Date; error?: string | null; startedAt?: Date },+ ): Promise<TaskItem[]> {+ if (ids.length === 0) return [];+ return this.db+ .update(tasks)+ .set({ status, updatedAt: new Date(), ...extra })+ .where(and(inArray(tasks.id, ids), this.ownership()))+ .returning();+ }+// ========== Config ==========/**@@ -1493,25 +1512,53 @@ export class TaskModel {// Find tasks that are now unblocked after a dependency completesasync getUnlockedTasks(completedTaskId: string): Promise<TaskItem[]> {- // Find all tasks that depend on the completed task- const dependents = await this.getDependents(completedTaskId);- const unlocked: TaskItem[] = [];+ return this.getUnlockedTasksForMany([completedTaskId]);+ }- for (const dep of dependents) {- if (dep.type !== 'blocks') continue;+ /**+ * Batched variant of {@link getUnlockedTasks}: discover every task unblocked+ * by any of `completedTaskIds` with a constant number of queries instead of+ * one dependency walk per completed task.+ */+ async getUnlockedTasksForMany(completedTaskIds: string[]): Promise<TaskItem[]> {+ if (completedTaskIds.length === 0) return [];- // Check if ALL dependencies of this task are now completed- const allDone = await this.areAllDependenciesCompleted(dep.taskId);- if (!allDone) continue;+ // All tasks that depend on any of the completed tasks+ const dependents = await this.db+ .select({ taskId: taskDependencies.taskId })+ .from(taskDependencies)+ .where(+ and(+ inArray(taskDependencies.dependsOnId, completedTaskIds),+ eq(taskDependencies.type, 'blocks'),+ this.depsOwnership(),+ ),+ );+ const dependentIds = [...new Set(dependents.map(({ taskId }) => taskId))];+ if (dependentIds.length === 0) return [];- // Get the task itself — only unlock if it's in backlog- const task = await this.findById(dep.taskId);- if (task && task.status === 'backlog') {- unlocked.push(task);- }- }+ // Of those, which still have at least one incomplete blocking dependency+ const blocked = await this.db+ .selectDistinct({ taskId: taskDependencies.taskId })+ .from(taskDependencies)+ .innerJoin(tasks, eq(taskDependencies.dependsOnId, tasks.id))+ .where(+ and(+ inArray(taskDependencies.taskId, dependentIds),+ eq(taskDependencies.type, 'blocks'),+ ne(tasks.status, 'completed'),+ this.depsOwnership(),+ ),+ );+ const blockedIds = new Set(blocked.map(({ taskId }) => taskId));+ const unlockedIds = dependentIds.filter((id) => !blockedIds.has(id));+ if (unlockedIds.length === 0) return [];- return unlocked;+ // Only unlock tasks still waiting in backlog+ return this.db+ .select()+ .from(tasks)+ .where(and(inArray(tasks.id, unlockedIds), eq(tasks.status, 'backlog'), this.ownership()));}// Check if all subtasks of a parent task are completeddiff --git a/packages/database/src/models/taskTopic.ts b/packages/database/src/models/taskTopic.tsindex 3ecc41aee1f..f5e61e70ed1 100644--- a/packages/database/src/models/taskTopic.ts+++ b/packages/database/src/models/taskTopic.ts@@ -119,6 +119,34 @@ export class TaskTopicModel {return updated;}+ /**+ * Cancel every still-running topic under the given tasks in one statement,+ * returning the rows that were actually flipped. Used by the family status+ * cascade so a topic that started after the caller's snapshot is still+ * marked canceled inside the same transaction as the status update.+ */+ async cancelRunningByTaskIds(taskIds: string[]): Promise<TaskTopicItem[]> {+ if (taskIds.length === 0) return [];++ const canceled = await this.db+ .update(taskTopics)+ .set({ status: 'canceled' })+ .where(+ and(+ inArray(taskTopics.taskId, taskIds),+ eq(taskTopics.status, 'running'),+ this.ownership(),+ ),+ )+ .returning();++ for (const topic of canceled) {+ if (topic.topicId) await this.markTopicEnded(topic.topicId, 'canceled');+ }++ return canceled;+ }+async updateOperationId(taskId: string, topicId: string, operationId?: string): Promise<void> {await this.db.update(taskTopics)diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex f3aef846349..e79670a70dc 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -1599,6 +1599,14 @@ export default {'taskDetail.status.paused': 'Pending review','taskDetail.status.running': 'In progress','taskDetail.status.scheduled': 'Scheduled',+ 'taskDetail.statusCascade.applyFailed': 'Could not update the task status. Try again.',+ 'taskDetail.statusCascade.cancel': 'Cancel',+ 'taskDetail.statusCascade.description':+ 'This task still has {{count}} open subtask(s). Update them to {{status}} too?',+ 'taskDetail.statusCascade.loadFailed': 'Could not check the subtask statuses. Try again.',+ 'taskDetail.statusCascade.parentOnly': 'Update parent only',+ 'taskDetail.statusCascade.title': 'Update open subtasks too?',+ 'taskDetail.statusCascade.updateAll': 'Update all','taskDetail.subtasks': 'Subtasks','taskDetail.addSubtask': 'Add sub-task','taskDetail.subtaskInstructionPlaceholder': 'Describe the sub-task...',diff --git a/src/features/AgentTasks/AgentTaskList/KanbanBoard.tsx b/src/features/AgentTasks/AgentTaskList/KanbanBoard.tsxindex 3eb16f15790..be76e398c84 100644--- a/src/features/AgentTasks/AgentTaskList/KanbanBoard.tsx+++ b/src/features/AgentTasks/AgentTaskList/KanbanBoard.tsx@@ -27,6 +27,7 @@ import type { TaskListItem } from '@/store/task/slices/list/initialState';import { createTaskModal } from '../CreateTaskModal';import type { TaskItemRouteScope } from '../features/AgentTaskItem';import AgentTaskItem from '../features/AgentTaskItem';+import { useTaskStatusChange } from '../features/useTaskStatusChange';import { taskDetailPath } from '../shared/taskDetailPath';import HiddenColumnsPanel from './HiddenColumnsPanel';import {@@ -92,7 +93,7 @@ const KanbanBoard = memo<KanbanBoardProps>(({ agentId, options, projectId, route[isQueryScopeCurrent, taskGroups],);const updateTask = useTaskStore((s) => s.updateTask);- const updateTaskStatus = useTaskStore((s) => s.updateTaskStatus);+ const changeTaskStatus = useTaskStatusChange();const hiddenColumns = useGlobalStore(systemStatusSelectors.taskKanbanHiddenColumns);const hiddenPanelCollapsed = useGlobalStore(systemStatusSelectors.taskKanbanHiddenPanelCollapsed);@@ -149,7 +150,10 @@ const KanbanBoard = memo<KanbanBoardProps>(({ agentId, options, projectId, routetry {if (groupBy === 'status' && column.targetStatus) {- await updateTaskStatus(task.identifier, column.targetStatus);+ const changed = await changeTaskStatus(task.identifier, column.targetStatus);+ if (!changed) {+ useTaskStore.setState({ taskGroups: prevGroups }, false, 'kanban/cancelMove');+ }} else if ((groupBy === 'assignee' || groupBy === 'member') && assigneeUpdate) {await updateTask(task.identifier, assigneeUpdate);} else if (groupBy === 'priority') {@@ -159,7 +163,7 @@ const KanbanBoard = memo<KanbanBoardProps>(({ agentId, options, projectId, routeuseTaskStore.setState({ taskGroups: prevGroups }, false, 'kanban/revertMove');}},- [canEditTask, columns, groupBy, updateTask, updateTaskStatus],+ [canEditTask, changeTaskStatus, columns, groupBy, updateTask],);const handleDragCancel = useCallback(() => {diff --git a/src/features/AgentTasks/features/TaskStatusCascadeModal.tsx b/src/features/AgentTasks/features/TaskStatusCascadeModal.tsxnew file mode 100644index 00000000000..19278cc32f4--- /dev/null+++ b/src/features/AgentTasks/features/TaskStatusCascadeModal.tsx@@ -0,0 +1,208 @@+'use client';++import type { TaskStatus } from '@lobechat/types';+import { Flexbox, Icon } from '@lobehub/ui';+import { Button, createModal, ScrollArea, Text, toast, useModalContext } from '@lobehub/ui/base-ui';+import { createStaticStyles, cssVar } from 'antd-style';+import { useEffect, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { STATUS_META } from './taskStatusMeta';++const styles = createStaticStyles(({ css }) => ({+ actions: css`+ padding: 16px;+ border-block-start: 1px solid ${cssVar.colorBorderSecondary};+ `,+ content: css`+ padding-block: 20px 16px;+ padding-inline: 20px;+ `,+ list: css`+ max-height: 280px;+ margin-block-start: 8px;+ border: 1px solid ${cssVar.colorBorderSecondary};+ border-radius: ${cssVar.borderRadius};++ > [role='presentation'] > [role='presentation'] {+ gap: 0;+ }+ `,+ row: css`+ padding-block: 6px;+ padding-inline: 12px;++ &:not(:last-child) {+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};+ }+ `,+}));++interface TaskStatusCascadeModalContentProps {+ onApply: (includeSubtasks: boolean) => Promise<void>;+ onCancel: () => void;+ subtasks: TaskStatusCascadeItem[];+ targetStatus: TaskStatus;+}++export interface TaskStatusCascadeItem {+ identifier: string;+ name?: string | null;+ status?: string;+}++/**+ * Apply-and-close flow shared by the modal buttons: on failure the modal stays+ * open with an error toast so the user can retry or cancel explicitly, instead+ * of the rejection being silently discarded.+ */+export const useCascadeApply = (onApply: (includeSubtasks: boolean) => Promise<void>) => {+ const { t } = useTranslation('chat');+ const { close } = useModalContext();+ const [loadingAction, setLoadingAction] = useState<'all' | 'parent' | null>(null);++ const handleApply = async (includeSubtasks: boolean) => {+ setLoadingAction(includeSubtasks ? 'all' : 'parent');+ try {+ await onApply(includeSubtasks);+ close();+ } catch (error) {+ console.error('[TaskStatusCascadeModal] Failed to apply status change:', error);+ toast.error(t('taskDetail.statusCascade.applyFailed'));+ } finally {+ setLoadingAction(null);+ }+ };++ return { handleApply, loadingAction };+};++const TaskStatusCascadeModalContent = ({+ onApply,+ onCancel,+ subtasks,+ targetStatus,+}: TaskStatusCascadeModalContentProps) => {+ const { t } = useTranslation('chat');+ const { close, setCanDismissByClickOutside } = useModalContext();+ const { handleApply, loadingAction } = useCascadeApply(onApply);++ useEffect(() => {+ setCanDismissByClickOutside(!loadingAction);+ }, [loadingAction, setCanDismissByClickOutside]);++ useEffect(() => {+ if (!loadingAction) return;+ const preventEscapeDismiss = (event: KeyboardEvent) => {+ if (event.key !== 'Escape') return;+ event.preventDefault();+ event.stopPropagation();+ };+ window.addEventListener('keydown', preventEscapeDismiss, true);+ return () => window.removeEventListener('keydown', preventEscapeDismiss, true);+ }, [loadingAction]);++ const handleCancel = () => {+ onCancel();+ close();+ };++ return (+ <Flexbox>+ <Flexbox className={styles.content} gap={8}>+ <Text as={'h3'} weight={'bold'}>+ {t('taskDetail.statusCascade.title')}+ </Text>+ <Text color={cssVar.colorTextSecondary}>+ {t('taskDetail.statusCascade.description', {+ count: subtasks.length,+ status: t(`taskDetail.status.${targetStatus}`),+ })}+ </Text>+ <ScrollArea className={styles.list}>+ {subtasks.map((task) => {+ const status = task.status as TaskStatus | undefined;+ const meta = status ? STATUS_META[status] : STATUS_META.backlog;++ return (+ <Flexbox+ horizontal+ align={'center'}+ className={styles.row}+ gap={10}+ key={task.identifier}+ >+ <Icon color={meta.color} icon={meta.icon} size={16} />+ <Flexbox flex={1}>+ <Text ellipsis>{task.name || task.identifier}</Text>+ </Flexbox>+ <Text color={cssVar.colorTextTertiary}>+ {t(`taskDetail.status.${status ?? 'backlog'}`, { defaultValue: meta.label })}+ </Text>+ </Flexbox>+ );+ })}+ </ScrollArea>+ </Flexbox>+ <Flexbox horizontal className={styles.actions} gap={8} justify={'space-between'}>+ <Button disabled={!!loadingAction} onClick={handleCancel}>+ {t('taskDetail.statusCascade.cancel')}+ </Button>+ <Flexbox horizontal gap={8}>+ <Button+ disabled={!!loadingAction}+ loading={loadingAction === 'parent'}+ onClick={() => void handleApply(false)}+ >+ {t('taskDetail.statusCascade.parentOnly')}+ </Button>+ <Button+ disabled={!!loadingAction}+ loading={loadingAction === 'all'}+ type={'primary'}+ onClick={() => void handleApply(true)}+ >+ {t('taskDetail.statusCascade.updateAll')}+ </Button>+ </Flexbox>+ </Flexbox>+ </Flexbox>+ );+};++interface CreateTaskStatusCascadeModalOptions {+ onApply: (includeSubtasks: boolean) => Promise<void>;+ subtasks: TaskStatusCascadeItem[];+ targetStatus: TaskStatus;+}++export const createTaskStatusCascadeModal = ({+ onApply,+ subtasks,+ targetStatus,+}: CreateTaskStatusCascadeModalOptions): Promise<boolean> =>+ new Promise((resolve) => {+ let applied = false;+ createModal({+ content: (+ <TaskStatusCascadeModalContent+ subtasks={subtasks}+ targetStatus={targetStatus}+ onCancel={() => resolve(false)}+ onApply={async (includeSubtasks) => {+ await onApply(includeSubtasks);+ applied = true;+ resolve(true);+ }}+ />+ ),+ maskClosable: true,+ footer: null,+ onOpenChangeComplete: (open) => {+ if (!open && !applied) resolve(false);+ },+ styles: { content: { padding: 0 } },+ title: false,+ width: 'min(92vw, 620px)',+ });+ });diff --git a/src/features/AgentTasks/features/TaskStatusTag.tsx b/src/features/AgentTasks/features/TaskStatusTag.tsxindex fc1f23ea606..eb24b57ca5a 100644--- a/src/features/AgentTasks/features/TaskStatusTag.tsx+++ b/src/features/AgentTasks/features/TaskStatusTag.tsx@@ -1,43 +1,18 @@import type { TaskStatus } from '@lobechat/types';import { type DropdownItem, DropdownMenu, Icon, type MenuInfo, Tooltip } from '@lobehub/ui';import { createStaticStyles, cssVar } from 'antd-style';-import type { LucideIcon } from 'lucide-react';import { Loader2Icon } from 'lucide-react';import type { ReactNode } from 'react';import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';-import { TASK_STATUS_VISUALS } from '@/components/ExecutionStatus';import { usePermission } from '@/hooks/usePermission';-import { useTaskStore } from '@/store/task';import { renderMenuExtra } from './menuExtra';+import { STATUS_META, USER_SELECTABLE_STATUSES } from './taskStatusMeta';+import { useTaskStatusChange } from './useTaskStatusChange';-interface StatusMeta {- color: string;- icon: LucideIcon;- label: string;- labelKey: string;-}--// Icons/colors come from the shared execution-status visuals; this map only-// adds the task-specific labels.-export const STATUS_META: Record<TaskStatus, StatusMeta> = {- backlog: { ...TASK_STATUS_VISUALS.backlog, label: 'Backlog', labelKey: 'status.backlog' },- canceled: { ...TASK_STATUS_VISUALS.canceled, label: 'Canceled', labelKey: 'status.canceled' },- completed: { ...TASK_STATUS_VISUALS.completed, label: 'Completed', labelKey: 'status.completed' },- failed: { ...TASK_STATUS_VISUALS.failed, label: 'Failed', labelKey: 'status.failed' },- paused: { ...TASK_STATUS_VISUALS.paused, label: 'Pending review', labelKey: 'status.paused' },- running: { ...TASK_STATUS_VISUALS.running, label: 'Running', labelKey: 'status.running' },- scheduled: { ...TASK_STATUS_VISUALS.scheduled, label: 'Scheduled', labelKey: 'status.scheduled' },-};--export const USER_SELECTABLE_STATUSES: TaskStatus[] = [- 'backlog',- 'paused',- 'completed',- 'canceled',-];+export { STATUS_META, USER_SELECTABLE_STATUSES } from './taskStatusMeta';const styles = createStaticStyles(({ css, cssVar }) => ({trigger: css`@@ -76,7 +51,7 @@ const TaskStatusTag = memo<TaskStatusTagProps>(const [open, setOpen] = useState(false);const { t } = useTranslation('chat');const { allowed: canEditTask, reason } = usePermission('create_content');- const updateTaskStatus = useTaskStore((s) => s.updateTaskStatus);+ const changeTaskStatus = useTaskStatusChange();const displayStatus = status ?? 'backlog';const meta = STATUS_META[displayStatus];@@ -93,12 +68,12 @@ const TaskStatusTag = memo<TaskStatusTagProps>(setLoading(true);try {- await updateTaskStatus(taskIdentifier, nextStatus);+ await changeTaskStatus(taskIdentifier, nextStatus);} finally {setLoading(false);}},- [canEditTask, displayStatus, onChange, taskIdentifier, updateTaskStatus],+ [canEditTask, changeTaskStatus, displayStatus, onChange, taskIdentifier],);const handleStatusChangeRef = useRef(handleStatusChange);diff --git a/src/features/AgentTasks/features/taskStatusMeta.ts b/src/features/AgentTasks/features/taskStatusMeta.tsnew file mode 100644index 00000000000..d588a89047a--- /dev/null+++ b/src/features/AgentTasks/features/taskStatusMeta.ts@@ -0,0 +1,28 @@+import type { TaskStatus } from '@lobechat/types';+import type { LucideIcon } from 'lucide-react';++import { TASK_STATUS_VISUALS } from '@/components/ExecutionStatus';++interface StatusMeta {+ color: string;+ icon: LucideIcon;+ label: string;+ labelKey: string;+}++export const STATUS_META: Record<TaskStatus, StatusMeta> = {+ backlog: { ...TASK_STATUS_VISUALS.backlog, label: 'Backlog', labelKey: 'status.backlog' },+ canceled: { ...TASK_STATUS_VISUALS.canceled, label: 'Canceled', labelKey: 'status.canceled' },+ completed: { ...TASK_STATUS_VISUALS.completed, label: 'Completed', labelKey: 'status.completed' },+ failed: { ...TASK_STATUS_VISUALS.failed, label: 'Failed', labelKey: 'status.failed' },+ paused: { ...TASK_STATUS_VISUALS.paused, label: 'Pending review', labelKey: 'status.paused' },+ running: { ...TASK_STATUS_VISUALS.running, label: 'Running', labelKey: 'status.running' },+ scheduled: { ...TASK_STATUS_VISUALS.scheduled, label: 'Scheduled', labelKey: 'status.scheduled' },+};++export const USER_SELECTABLE_STATUSES: TaskStatus[] = [+ 'backlog',+ 'paused',+ 'completed',+ 'canceled',+];diff --git a/src/features/AgentTasks/features/useCascadeApply.test.ts b/src/features/AgentTasks/features/useCascadeApply.test.tsnew file mode 100644index 00000000000..3f83b9c5a3f--- /dev/null+++ b/src/features/AgentTasks/features/useCascadeApply.test.ts@@ -0,0 +1,44 @@+import { act, renderHook, waitFor } from '@testing-library/react';+import { describe, expect, it, vi } from 'vitest';++import { useCascadeApply } from './TaskStatusCascadeModal';++const toastError = vi.hoisted(() => vi.fn());+const modalContext = vi.hoisted(() => ({+ close: vi.fn(),+ setCanDismissByClickOutside: vi.fn(),+}));++vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ toast: { error: toastError },+ useModalContext: () => modalContext,+}));++vi.mock('react-i18next', () => ({+ useTranslation: () => ({ t: (key: string) => key }),+}));++describe('useCascadeApply', () => {+ it('keeps the modal open with an error toast on apply failure, then closes on retry success', async () => {+ vi.spyOn(console, 'error').mockImplementation(() => {});+ const onApply = vi+ .fn()+ .mockRejectedValueOnce(new Error('network error'))+ .mockResolvedValueOnce(undefined);++ const { result } = renderHook(() => useCascadeApply(onApply));++ // First attempt fails: the rejection is surfaced instead of discarded,+ // and the modal is not closed so the user can retry or cancel.+ await act(() => result.current.handleApply(true));+ expect(toastError).toHaveBeenCalledWith('taskDetail.statusCascade.applyFailed');+ expect(modalContext.close).not.toHaveBeenCalled();+ await waitFor(() => expect(result.current.loadingAction).toBeNull());++ // Retry succeeds: the modal closes.+ await act(() => result.current.handleApply(true));+ expect(onApply).toHaveBeenCalledTimes(2);+ expect(modalContext.close).toHaveBeenCalledTimes(1);+ });+});diff --git a/src/features/AgentTasks/features/useTaskItemContextMenu.tsx b/src/features/AgentTasks/features/useTaskItemContextMenu.tsxindex 36ed156642e..08630747e15 100644--- a/src/features/AgentTasks/features/useTaskItemContextMenu.tsx+++ b/src/features/AgentTasks/features/useTaskItemContextMenu.tsx@@ -27,7 +27,8 @@ import { useTaskStore } from '@/store/task';import { taskDetailPath } from '../shared/taskDetailPath';import { renderMenuExtra } from './menuExtra';import { PRIORITY_META } from './TaskPriorityTag';-import { STATUS_META, USER_SELECTABLE_STATUSES } from './TaskStatusTag';+import { STATUS_META, USER_SELECTABLE_STATUSES } from './taskStatusMeta';+import { useTaskStatusChange } from './useTaskStatusChange';const PRIORITY_LEVELS = [0, 1, 2, 3, 4];@@ -63,7 +64,7 @@ export const useTaskContextMenuActions = (const activeWorkspaceSlug = useActiveWorkspaceSlug();const { allowed: canEditTask } = usePermission('create_content');- const updateTaskStatus = useTaskStore((s) => s.updateTaskStatus);+ const changeTaskStatus = useTaskStatusChange();const updateTask = useTaskStore((s) => s.updateTask);const refreshTaskList = useTaskStore((s) => s.refreshTaskList);const deleteTask = useTaskStore((s) => s.deleteTask);@@ -106,7 +107,7 @@ export const useTaskContextMenuActions = (domEvent.stopPropagation();if (!canEditTask) return;if (status === currentStatus) return;- void updateTaskStatus(task.identifier, status);+ void changeTaskStatus(task.identifier, status);},} as ContextMenuItem;});@@ -275,7 +276,7 @@ export const useTaskContextMenuActions = (event.stopPropagation();const nextStatus = USER_SELECTABLE_STATUSES[idx];if (nextStatus !== currentStatus) {- void updateTaskStatus(task.identifier, nextStatus);+ void changeTaskStatus(task.identifier, nextStatus);}closeContextMenu();cleanup();@@ -303,7 +304,7 @@ export const useTaskContextMenuActions = (t,appOrigin,activeWorkspaceSlug,- updateTaskStatus,+ changeTaskStatus,updateTask,refreshTaskList,deleteTask,diff --git a/src/features/AgentTasks/features/useTaskStatusChange.test.ts b/src/features/AgentTasks/features/useTaskStatusChange.test.tsnew file mode 100644index 00000000000..05c29ee0967--- /dev/null+++ b/src/features/AgentTasks/features/useTaskStatusChange.test.ts@@ -0,0 +1,143 @@+import { renderHook } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { useTaskStatusChange } from './useTaskStatusChange';++const mocks = vi.hoisted(() => ({+ createCascadeModal: vi.fn(),+ getSubtasks: vi.fn(),+ refreshTaskDetail: vi.fn(),+ refreshTaskList: vi.fn(),+ toastError: vi.fn(),+ updateStatusCascade: vi.fn(),+ updateTaskStatus: vi.fn(),+}));++vi.mock('@/services/task', () => ({+ taskService: {+ getSubtasks: mocks.getSubtasks,+ updateStatusCascade: mocks.updateStatusCascade,+ },+}));++vi.mock('@/store/task', () => ({+ useTaskStore: (+ selector: (state: {+ internal_refreshTaskDetail: typeof mocks.refreshTaskDetail;+ refreshTaskList: typeof mocks.refreshTaskList;+ updateTaskStatus: typeof mocks.updateTaskStatus;+ }) => unknown,+ ) =>+ selector({+ internal_refreshTaskDetail: mocks.refreshTaskDetail,+ refreshTaskList: mocks.refreshTaskList,+ updateTaskStatus: mocks.updateTaskStatus,+ }),+}));++vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ toast: { error: mocks.toastError },+}));++vi.mock('./TaskStatusCascadeModal', () => ({+ createTaskStatusCascadeModal: mocks.createCascadeModal,+}));++vi.mock('react-i18next', () => ({+ useTranslation: () => ({ t: (key: string) => key }),+}));++describe('useTaskStatusChange', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.refreshTaskDetail.mockResolvedValue(undefined);+ mocks.refreshTaskList.mockResolvedValue(undefined);+ mocks.updateStatusCascade.mockResolvedValue(undefined);+ mocks.updateTaskStatus.mockResolvedValue('T-1');+ });++ it('updates non-terminal statuses without inspecting subtasks', async () => {+ const { result } = renderHook(() => useTaskStatusChange());++ await expect(result.current('T-1', 'paused')).resolves.toBe(true);++ expect(mocks.getSubtasks).not.toHaveBeenCalled();+ expect(mocks.updateTaskStatus).toHaveBeenCalledWith('T-1', 'paused');+ });++ it('updates a terminal status directly when there are no open subtasks', async () => {+ mocks.getSubtasks.mockResolvedValue({+ data: [+ { identifier: 'T-2', status: 'completed' },+ { identifier: 'T-3', status: 'canceled' },+ ],+ });+ const { result } = renderHook(() => useTaskStatusChange());++ await expect(result.current('T-1', 'completed')).resolves.toBe(true);++ expect(mocks.createCascadeModal).not.toHaveBeenCalled();+ expect(mocks.updateTaskStatus).toHaveBeenCalledWith('T-1', 'completed');+ });++ it('updates every open subtask before the parent when the user chooses update all', async () => {+ mocks.getSubtasks.mockResolvedValue({+ data: [+ { identifier: 'T-2', name: 'Open', status: 'backlog' },+ { identifier: 'T-3', name: 'Already done', status: 'completed' },+ { identifier: 'T-4', name: 'Running', status: 'running' },+ { identifier: 'T-5', name: 'Failed', status: 'failed' },+ ],+ });+ mocks.createCascadeModal.mockImplementation(async ({ onApply }) => {+ await onApply(true);+ return true;+ });+ const { result } = renderHook(() => useTaskStatusChange());++ await expect(result.current('T-1', 'completed')).resolves.toBe(true);++ expect(mocks.createCascadeModal).toHaveBeenCalledWith(+ expect.objectContaining({+ subtasks: [+ expect.objectContaining({ identifier: 'T-2' }),+ expect.objectContaining({ identifier: 'T-4' }),+ ],+ targetStatus: 'completed',+ }),+ );+ expect(mocks.updateStatusCascade).toHaveBeenCalledWith('T-1', 'completed');+ expect(mocks.updateTaskStatus).not.toHaveBeenCalled();+ expect(mocks.refreshTaskDetail).toHaveBeenCalledWith('T-1');+ expect(mocks.refreshTaskList).toHaveBeenCalledTimes(1);+ });++ it('leaves subtasks unchanged when the user chooses parent only', async () => {+ mocks.getSubtasks.mockResolvedValue({+ data: [{ identifier: 'T-2', status: 'backlog' }],+ });+ mocks.createCascadeModal.mockImplementation(async ({ onApply }) => {+ await onApply(false);+ return true;+ });+ const { result } = renderHook(() => useTaskStatusChange());++ await result.current('T-1', 'canceled');++ expect(mocks.updateTaskStatus).toHaveBeenCalledTimes(1);+ expect(mocks.updateTaskStatus).toHaveBeenCalledWith('T-1', 'canceled');+ });++ it('does not update anything when the modal is dismissed', async () => {+ mocks.getSubtasks.mockResolvedValue({+ data: [{ identifier: 'T-2', status: 'backlog' }],+ });+ mocks.createCascadeModal.mockResolvedValue(false);+ const { result } = renderHook(() => useTaskStatusChange());++ await expect(result.current('T-1', 'completed')).resolves.toBe(false);++ expect(mocks.updateTaskStatus).not.toHaveBeenCalled();+ });+});diff --git a/src/features/AgentTasks/features/useTaskStatusChange.ts b/src/features/AgentTasks/features/useTaskStatusChange.tsnew file mode 100644index 00000000000..b85c5b5f394--- /dev/null+++ b/src/features/AgentTasks/features/useTaskStatusChange.ts@@ -0,0 +1,80 @@+'use client';++import { UNFINISHED_TASK_STATUSES } from '@lobechat/builtin-tool-task';+import type { TaskStatus } from '@lobechat/types';+import { toast } from '@lobehub/ui/base-ui';+import { useCallback } from 'react';+import { useTranslation } from 'react-i18next';++import { taskService } from '@/services/task';+import { useTaskStore } from '@/store/task';++import type { TaskStatusCascadeItem } from './TaskStatusCascadeModal';+import { createTaskStatusCascadeModal } from './TaskStatusCascadeModal';++type CascadeTargetStatus = 'canceled' | 'completed';++const CASCADE_TARGET_STATUSES = new Set<TaskStatus>(['canceled', 'completed']);+const UNFINISHED_SUBTASK_STATUSES = new Set<TaskStatus>(UNFINISHED_TASK_STATUSES);++const isCascadeTargetStatus = (status: TaskStatus): status is CascadeTargetStatus =>+ CASCADE_TARGET_STATUSES.has(status);++export const getOpenSubtasks = (subtasks: TaskStatusCascadeItem[]): TaskStatusCascadeItem[] =>+ subtasks.filter((task) => UNFINISHED_SUBTASK_STATUSES.has(task.status as TaskStatus));++export const useTaskStatusChange = () => {+ const { t } = useTranslation('chat');+ const refreshTaskDetail = useTaskStore((s) => s.internal_refreshTaskDetail);+ const refreshTaskList = useTaskStore((s) => s.refreshTaskList);+ const updateTaskStatus = useTaskStore((s) => s.updateTaskStatus);++ return useCallback(+ async (taskIdentifier: string, status: TaskStatus): Promise<boolean> => {+ if (!isCascadeTargetStatus(status)) {+ await updateTaskStatus(taskIdentifier, status);+ return true;+ }++ let openSubtasks: TaskStatusCascadeItem[];+ try {+ const result = await taskService.getSubtasks(taskIdentifier);+ openSubtasks = getOpenSubtasks(result.data);+ } catch (error) {+ console.error('[useTaskStatusChange] Failed to inspect subtasks:', error);+ toast.error(t('taskDetail.statusCascade.loadFailed'));+ throw error;+ }++ if (openSubtasks.length === 0) {+ await updateTaskStatus(taskIdentifier, status);+ return true;+ }++ return createTaskStatusCascadeModal({+ subtasks: openSubtasks,+ targetStatus: status,+ onApply: async (includeSubtasks) => {+ if (includeSubtasks) {+ await taskService.updateStatusCascade(taskIdentifier, status);+ const refreshResults = await Promise.allSettled([+ refreshTaskDetail(taskIdentifier),+ refreshTaskList(),+ ]);+ for (const refreshResult of refreshResults) {+ if (refreshResult.status === 'rejected') {+ console.error(+ '[useTaskStatusChange] Failed to refresh after status cascade:',+ refreshResult.reason,+ );+ }+ }+ return;+ }+ await updateTaskStatus(taskIdentifier, status);+ },+ });+ },+ [refreshTaskDetail, refreshTaskList, t, updateTaskStatus],+ );+};diff --git a/src/services/task.ts b/src/services/task.tsindex 39e472e0072..48a6b99df3c 100644--- a/src/services/task.ts+++ b/src/services/task.ts@@ -150,6 +150,9 @@ class TaskService {updateStatus = async (id: string, status: TaskStatus, error?: string) =>lambdaClient.task.updateStatus.mutate({ error, id, status });+ updateStatusCascade = async (id: string, status: 'canceled' | 'completed') =>+ lambdaClient.task.updateStatusCascade.mutate({ id, status });+run = async (id: string, params?: { continueTopicId?: string; prompt?: string }) =>lambdaClient.task.run.mutate({ id, ...params });