π€― 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(server,task): batch run subtasks in dependency order (#14418)
Arvin Xu11e6619a3cc6
diff --git a/src/features/AgentTasks/AgentTaskDetail/RunSubtasksPreview.tsx b/src/features/AgentTasks/AgentTaskDetail/RunSubtasksPreview.tsxnew file mode 100644index 00000000000..9e8381b9fec--- /dev/null+++ b/src/features/AgentTasks/AgentTaskDetail/RunSubtasksPreview.tsx@@ -0,0 +1,103 @@+import { Block, Flexbox, Text } from '@lobehub/ui';+import { Tag } from 'antd';+import { cssVar } from 'antd-style';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++interface SubtaskGraphPlan {+ alreadyDone: string[];+ blockedByCycle: string[];+ blockedExternally: string[];+ cycles: string[];+ ineligible: string[];+ layers: string[][];+ totalRunnable: number;+}++interface Props {+ plan: SubtaskGraphPlan;+}++const RunSubtasksPreview = memo<Props>(({ plan }) => {+ const { t } = useTranslation('chat');++ return (+ <Flexbox gap={12} style={{ paddingBlock: 8 }}>+ <Text fontSize={13} style={{ color: cssVar.colorTextSecondary }}>+ {t('taskDetail.runAll.description')}+ </Text>++ <Flexbox gap={8}>+ {plan.layers.map((layer, index) => {+ const hint =+ index === 0+ ? t('taskDetail.runAll.layerHint.first')+ : t('taskDetail.runAll.layerHint.next', { prev: index });+ return (+ <Block+ gap={6}+ key={`layer-${index}`}+ paddingBlock={8}+ paddingInline={12}+ variant={'outlined'}+ >+ <Flexbox horizontal align={'center'} gap={8} justify={'space-between'}>+ <Text fontSize={13} weight={600}>+ {t('taskDetail.runAll.layer', { index: index + 1 })}+ </Text>+ <Text fontSize={12} style={{ color: cssVar.colorTextDescription }}>+ {hint}+ </Text>+ </Flexbox>+ <Flexbox horizontal flex={'wrap'} gap={4}>+ {layer.map((id) => (+ <Tag key={id} style={{ marginInlineEnd: 0 }}>+ {id}+ </Tag>+ ))}+ </Flexbox>+ </Block>+ );+ })}+ </Flexbox>++ {(plan.alreadyDone.length > 0 ||+ plan.ineligible.length > 0 ||+ plan.blockedExternally.length > 0) && (+ <Flexbox gap={4}>+ {plan.alreadyDone.length > 0 && (+ <Text fontSize={12} style={{ color: cssVar.colorTextDescription }}>+ {t('taskDetail.runAll.skipped.alreadyDone', { count: plan.alreadyDone.length })}+ </Text>+ )}+ {plan.ineligible.length > 0 && (+ <Text fontSize={12} style={{ color: cssVar.colorTextDescription }}>+ {t('taskDetail.runAll.skipped.ineligible', { count: plan.ineligible.length })}+ </Text>+ )}+ {plan.blockedExternally.length > 0 && (+ <Text fontSize={12} style={{ color: cssVar.colorTextDescription }}>+ {t('taskDetail.runAll.skipped.blockedExternally', {+ count: plan.blockedExternally.length,+ })}+ </Text>+ )}+ </Flexbox>+ )}++ {plan.cycles.length > 0 && (+ <Block paddingBlock={8} paddingInline={12} variant={'outlined'}>+ <Text fontSize={12} style={{ color: cssVar.colorWarning }}>+ {t('taskDetail.runAll.cycleWarning', {+ members: [...plan.cycles, ...plan.blockedByCycle].join(', '),+ })}+ </Text>+ </Block>+ )}+ </Flexbox>+ );+});++RunSubtasksPreview.displayName = 'RunSubtasksPreview';++export default RunSubtasksPreview;diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskSubtasks.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskSubtasks.tsxindex e8041e12943..4b3b63f40bf 100644--- a/src/features/AgentTasks/AgentTaskDetail/TaskSubtasks.tsx+++ b/src/features/AgentTasks/AgentTaskDetail/TaskSubtasks.tsx@@ -1,14 +1,15 @@import type { TaskDetailSubtask } from '@lobechat/types';import { ActionIcon, Block, Flexbox, Icon, showContextMenu, Text } from '@lobehub/ui';-import { Button, ConfigProvider, Tree } from 'antd';+import { App, Button, ConfigProvider, Tree } from 'antd';import type { DataNode } from 'antd/es/tree';import { cssVar } from 'antd-style';-import { ChevronDown, ListTodoIcon, Plus } from 'lucide-react';+import { ChevronDown, ListTodoIcon, PlayCircle, Plus } from 'lucide-react';import type { Key, MouseEvent } from 'react';import { memo, useCallback, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';import { useNavigate } from 'react-router-dom';+import { taskService } from '@/services/task';import { useTaskStore } from '@/store/task';import { taskDetailSelectors } from '@/store/task/selectors';@@ -22,6 +23,7 @@ import TaskTriggerTag from '../features/TaskTriggerTag';import { useTaskContextMenuActions } from '../features/useTaskItemContextMenu';import AccordionArrowIcon from '../shared/AccordionArrowIcon';import { styles } from '../shared/style';+import RunSubtasksPreview from './RunSubtasksPreview';type TaskStatus = 'backlog' | 'canceled' | 'completed' | 'failed' | 'paused' | 'running';@@ -124,15 +126,18 @@ const toTreeData = (tree: TaskTreeNode[]): DataNode[] => {const TaskSubtasks = memo(() => {const { t } = useTranslation('chat');+ const { message, modal } = App.useApp();const navigate = useNavigate();const agentId = useTaskStore(taskDetailSelectors.activeTaskAgentId);const subtasks = useTaskStore(taskDetailSelectors.activeTaskSubtasks);const taskId = useTaskStore(taskDetailSelectors.activeTaskId);+ const runReadySubtasks = useTaskStore((s) => s.runReadySubtasks);const { buildItems, installKeyboardHandlers } = useTaskContextMenuActions();const [isCreating, setIsCreating] = useState(false);const [isExpanded, setIsExpanded] = useState(true);+ const [isPlanning, setIsPlanning] = useState(false);const handleNavigate = useCallback((identifier: string) => {@@ -181,6 +186,60 @@ const TaskSubtasks = memo(() => {const toggleCreating = useCallback(() => setIsCreating((prev) => !prev), []);+ const handleRunAll = useCallback(async () => {+ if (!taskId || isPlanning) return;+ setIsPlanning(true);+ try {+ const preview = await taskService.previewSubtaskLayers(taskId);+ const plan = preview.data;++ // No runnable layer AND nothing informative to show β just a toast.+ // If there are externally-blocked or cycled tasks, still open the modal+ // so the user understands why "Run all" can't start anything right now.+ const hasInformativeState =+ plan.blockedExternally.length > 0 ||+ plan.blockedByCycle.length > 0 ||+ plan.cycles.length > 0;+ if (plan.totalRunnable === 0 && !hasInformativeState) {+ message.info(t('taskDetail.runAll.empty'));+ return;+ }++ const canRun = plan.totalRunnable > 0;+ modal.confirm({+ cancelText: t('taskDetail.runAll.cancel'),+ centered: true,+ content: <RunSubtasksPreview plan={plan} />,+ okButtonProps: canRun ? undefined : { disabled: true },+ okText: t('taskDetail.runAll.confirm', { count: plan.totalRunnable }),+ onOk: async () => {+ if (!canRun) return;+ const res = await runReadySubtasks(taskId);+ const kicked = res.data.kickedOff.length;+ const failed = res.data.failed?.length ?? 0;+ if (failed > 0) {+ message.warning(+ t('taskDetail.runAll.partialFailure', {+ failed,+ ok: kicked,+ total: kicked + failed,+ }),+ );+ } else {+ message.success(t('taskDetail.runAll.kickedOff', { count: kicked }));+ }+ },+ title: t('taskDetail.runAll.title'),+ width: 520,+ });+ } catch (error) {+ console.error('[TaskSubtasks] Failed to plan subtasks:', error);+ message.error(t('taskDetail.updateFailed'));+ } finally {+ setIsPlanning(false);+ }+ }, [taskId, isPlanning, message, modal, t, runReadySubtasks]);+if (!taskId) return null;const hasSubtasks = subtasks.length > 0;@@ -217,12 +276,22 @@ const TaskSubtasks = memo(() => {onSubtaskClick={handleNavigate}/></Flexbox>- <ActionIcon- icon={Plus}- size="small"- title={t('taskDetail.addSubtask')}- onClick={toggleCreating}- />+ <Flexbox horizontal align="center" gap={4}>+ <ActionIcon+ disabled={isPlanning}+ icon={PlayCircle}+ loading={isPlanning}+ size="small"+ title={t('taskDetail.runAll')}+ onClick={handleRunAll}+ />+ <ActionIcon+ icon={Plus}+ size="small"+ title={t('taskDetail.addSubtask')}+ onClick={toggleCreating}+ />+ </Flexbox></Flexbox>{isExpanded && (<>diff --git a/src/locales/default/chat.ts b/src/locales/default/chat.tsindex 6f42e6e8fe8..0aca4437665 100644--- a/src/locales/default/chat.ts+++ b/src/locales/default/chat.ts@@ -626,6 +626,27 @@ export default {'taskDetail.subtasks': 'Subtasks','taskDetail.addSubtask': 'Add sub-task','taskDetail.subtaskInstructionPlaceholder': 'Describe the sub-task...',+ 'taskDetail.runAll': 'Run all',+ 'taskDetail.runAll.title': 'Run subtasks in dependency order',+ 'taskDetail.runAll.description':+ 'Subtasks will run layer by layer. Each layer waits for the previous one to finish. Tasks with no dependencies run in layer 1.',+ 'taskDetail.runAll.layer': 'Layer {{index}}',+ 'taskDetail.runAll.layerHint.first': 'Starts immediately',+ 'taskDetail.runAll.layerHint.next': 'Waits for layer {{prev}} to finish',+ 'taskDetail.runAll.skipped.alreadyDone':+ '{{count}} task(s) already completed or canceled β skipped',+ 'taskDetail.runAll.skipped.ineligible': '{{count}} task(s) running or scheduled β skipped',+ 'taskDetail.runAll.skipped.blockedExternally':+ '{{count}} task(s) waiting on a blocker outside this batch β will run automatically when unblocked',+ 'taskDetail.runAll.cycleWarning':+ 'Circular dependency detected. Tasks involved in or blocked by the cycle will not run: {{members}}',+ 'taskDetail.runAll.empty':+ 'Nothing to run β every subtask is already completed, in flight, or stuck in a cycle.',+ 'taskDetail.runAll.confirm': 'Run {{count}} subtask(s)',+ 'taskDetail.runAll.cancel': 'Cancel',+ 'taskDetail.runAll.kickedOff': 'Started {{count}} subtask(s); downstream layers will follow.',+ 'taskDetail.runAll.partialFailure': 'Started {{ok}} of {{total}} subtask(s); {{failed}} failed.',+ 'taskDetail.runAll.loading': 'Loading subtask plan...','taskDetail.reassignDisabled': 'Cannot reassign agent while task is running','taskDetail.titlePlaceholder': 'Enter task title...','taskDetail.topicDrawer.untitled': 'Untitled',diff --git a/src/server/routers/lambda/__tests__/integration/task.integration.test.ts b/src/server/routers/lambda/__tests__/integration/task.integration.test.tsindex 2d2f848a573..9b7540b00dd 100644--- a/src/server/routers/lambda/__tests__/integration/task.integration.test.ts+++ b/src/server/routers/lambda/__tests__/integration/task.integration.test.ts@@ -532,4 +532,197 @@ describe('Task Router Integration', () => {expect(found.data.error).toBeNull();});});++ describe('subtask layers + batch run', () => {+ it('previewSubtaskLayers groups subtasks by dependency level', async () => {+ const parent = await caller.create({ instruction: 'Book' });+ const ch1 = await caller.create({+ assigneeAgentId: testAgentId,+ instruction: 'Chapter 1',+ parentTaskId: parent.data.id,+ });+ const ch2 = await caller.create({+ assigneeAgentId: testAgentId,+ instruction: 'Chapter 2',+ parentTaskId: parent.data.id,+ });+ const ch3 = await caller.create({+ assigneeAgentId: testAgentId,+ instruction: 'Chapter 3',+ parentTaskId: parent.data.id,+ });+ // ch3 depends on ch1 and ch2+ await caller.addDependency({ dependsOnId: ch1.data.id, taskId: ch3.data.id });+ await caller.addDependency({ dependsOnId: ch2.data.id, taskId: ch3.data.id });++ const result = await caller.previewSubtaskLayers({ id: parent.data.id });+ expect(result.data.layers).toHaveLength(2);+ expect(result.data.layers[0].sort()).toEqual([ch1.data.identifier, ch2.data.identifier]);+ expect(result.data.layers[1]).toEqual([ch3.data.identifier]);+ expect(result.data.totalRunnable).toBe(3);+ expect(result.data.cycles).toEqual([]);+ });++ it('previewSubtaskLayers reports cycles instead of layering them', async () => {+ const parent = await caller.create({ instruction: 'Cyclic' });+ const a = await caller.create({+ instruction: 'A',+ parentTaskId: parent.data.id,+ });+ const b = await caller.create({+ instruction: 'B',+ parentTaskId: parent.data.id,+ });+ await caller.addDependency({ dependsOnId: a.data.id, taskId: b.data.id });+ await caller.addDependency({ dependsOnId: b.data.id, taskId: a.data.id });++ const result = await caller.previewSubtaskLayers({ id: parent.data.id });+ expect(result.data.layers).toEqual([]);+ expect(result.data.cycles.sort()).toEqual([a.data.identifier, b.data.identifier]);+ });++ it('runReadySubtasks kicks off the first layer only', async () => {+ const parent = await caller.create({ instruction: 'Book' });+ const ch1 = await caller.create({+ assigneeAgentId: testAgentId,+ instruction: 'Chapter 1',+ parentTaskId: parent.data.id,+ });+ const ch2 = await caller.create({+ assigneeAgentId: testAgentId,+ instruction: 'Chapter 2',+ parentTaskId: parent.data.id,+ });+ const ch3 = await caller.create({+ assigneeAgentId: testAgentId,+ instruction: 'Chapter 3',+ parentTaskId: parent.data.id,+ });+ await caller.addDependency({ dependsOnId: ch1.data.id, taskId: ch3.data.id });+ await caller.addDependency({ dependsOnId: ch2.data.id, taskId: ch3.data.id });++ const result = await caller.runReadySubtasks({ id: parent.data.id });+ expect(result.success).toBe(true);+ expect(result.data.kickedOff?.sort()).toEqual([ch1.data.identifier, ch2.data.identifier]);+ // ch3 stays in backlog because layer 2 only fires after layer 1 completes+ const ch3After = await caller.find({ id: ch3.data.id });+ expect(ch3After.data.status).toBe('backlog');+ // The kicked-off tasks should now be running+ const ch1After = await caller.find({ id: ch1.data.id });+ expect(ch1After.data.status).toBe('running');+ });++ it('runReadySubtasks returns noop when nothing is runnable', async () => {+ const parent = await caller.create({ instruction: 'Empty' });+ const result = await caller.runReadySubtasks({ id: parent.data.id });+ expect(result.success).toBe(true);+ expect(result.data.kickedOff).toEqual([]);+ expect(result.data.skipped).toEqual({ reason: 'nothing-runnable' });+ });++ it('previewSubtaskLayers holds back dependents of in-flight subtasks (does not free them)', async () => {+ const parent = await caller.create({ instruction: 'Inflight blocker' });+ const ch1 = await caller.create({+ assigneeAgentId: testAgentId,+ instruction: 'Chapter 1',+ parentTaskId: parent.data.id,+ });+ const ch2 = await caller.create({+ assigneeAgentId: testAgentId,+ instruction: 'Chapter 2',+ parentTaskId: parent.data.id,+ });+ await caller.addDependency({ dependsOnId: ch1.data.id, taskId: ch2.data.id });++ // Kick ch1 off β now in `running` state+ await caller.run({ id: ch1.data.id });++ const result = await caller.previewSubtaskLayers({ id: parent.data.id });+ // ch1 is in flight (ineligible). ch2 must NOT appear in layers β its+ // upstream is still running.+ expect(result.data.layers).toEqual([]);+ expect(result.data.ineligible).toEqual([ch1.data.identifier]);+ expect(result.data.blockedExternally).toEqual([ch2.data.identifier]);+ });++ it('runReadySubtasks does not start a subtask whose blocker is still running', async () => {+ const parent = await caller.create({ instruction: 'Inflight runReady' });+ const ch1 = await caller.create({+ assigneeAgentId: testAgentId,+ instruction: 'Chapter 1',+ parentTaskId: parent.data.id,+ });+ const ch2 = await caller.create({+ assigneeAgentId: testAgentId,+ instruction: 'Chapter 2',+ parentTaskId: parent.data.id,+ });+ await caller.addDependency({ dependsOnId: ch1.data.id, taskId: ch2.data.id });++ await caller.run({ id: ch1.data.id });+ mockExecAgent.mockClear();++ const result = await caller.runReadySubtasks({ id: parent.data.id });+ // No layers β runReadySubtasks falls through to the "nothing-runnable" branch.+ expect(result.data.kickedOff).toEqual([]);+ expect(mockExecAgent).not.toHaveBeenCalled();+ const ch2After = await caller.find({ id: ch2.data.id });+ expect(ch2After.data.status).toBe('backlog');+ });++ it('previewSubtaskLayers respects a cross-scope blocker (dep outside the subtree)', async () => {+ // External blocker lives outside `parent`'s descendant tree+ const externalBlocker = await caller.create({+ assigneeAgentId: testAgentId,+ instruction: 'External blocker',+ });+ const parent = await caller.create({ instruction: 'Cross-scope' });+ const ch1 = await caller.create({+ assigneeAgentId: testAgentId,+ instruction: 'Chapter 1',+ parentTaskId: parent.data.id,+ });+ // ch1 depends on a task that is NOT a descendant of parent+ await caller.addDependency({ dependsOnId: externalBlocker.data.id, taskId: ch1.data.id });++ // External is still backlog β blocks ch1+ const blocked = await caller.previewSubtaskLayers({ id: parent.data.id });+ expect(blocked.data.layers).toEqual([]);+ expect(blocked.data.blockedExternally).toEqual([ch1.data.identifier]);++ // Mark external completed β cascade fires β ch1 is auto-kicked off.+ // This proves the blocker classification *and* the existing cascade hook+ // co-operate end-to-end across the scope boundary.+ await caller.updateStatus({ id: externalBlocker.data.id, status: 'completed' });+ const ch1After = await caller.find({ id: ch1.data.id });+ expect(ch1After.data.status).toBe('running');+ });++ it('updateStatus(completed) triggers cascade kickoff for unlocked downstream', async () => {+ const parent = await caller.create({ instruction: 'Cascade' });+ const ch1 = await caller.create({+ assigneeAgentId: testAgentId,+ instruction: 'Chapter 1',+ parentTaskId: parent.data.id,+ });+ const ch2 = await caller.create({+ assigneeAgentId: testAgentId,+ instruction: 'Chapter 2',+ parentTaskId: parent.data.id,+ });+ await caller.addDependency({ dependsOnId: ch1.data.id, taskId: ch2.data.id });++ // Kick off layer 1 (just ch1)+ await caller.run({ id: ch1.data.id });++ // Mark ch1 completed β ch2 should auto-run (status 'running' + topic created)+ const completed = await caller.updateStatus({ id: ch1.data.id, status: 'completed' });+ expect(completed.unlocked).toEqual([ch2.data.identifier]);++ const ch2After = await caller.find({ id: ch2.data.id });+ expect(ch2After.data.status).toBe('running');+ // Verify the runner was actually invoked, not just the status flipped+ expect(mockExecAgent).toHaveBeenCalled();+ });+ });});diff --git a/src/server/routers/lambda/task.ts b/src/server/routers/lambda/task.tsindex 151367ae00a..1b2fc360a6d 100644--- a/src/server/routers/lambda/task.ts+++ b/src/server/routers/lambda/task.ts@@ -12,6 +12,7 @@ import { authedProcedure, router } from '@/libs/trpc/lambda';import { serverDatabase } from '@/libs/trpc/lambda/middleware';import { AiAgentService } from '@/server/services/aiAgent';import { TaskService } from '@/server/services/task';+import { TaskGraphService } from '@/server/services/taskGraph';import { TaskLifecycleService } from '@/server/services/taskLifecycle';import { TaskReviewService } from '@/server/services/taskReview';import { TaskRunnerService } from '@/server/services/taskRunner';@@ -983,6 +984,85 @@ export const taskRouter = router({}}),+ previewSubtaskLayers: taskProcedure.input(idInput).query(async ({ input, ctx }) => {+ try {+ const parent = await resolveOrThrow(ctx.taskModel, input.id);+ const graph = new TaskGraphService(ctx.serverDB, ctx.userId);+ const { plan } = await graph.planForParent(parent.id);+ return { data: plan, success: true };+ } catch (error) {+ if (error instanceof TRPCError) throw error;+ console.error('[task:previewSubtaskLayers]', error);+ throw new TRPCError({+ cause: error,+ code: 'INTERNAL_SERVER_ERROR',+ message: 'Failed to plan subtask layers',+ });+ }+ }),++ runReadySubtasks: taskProcedure.input(idInput).mutation(async ({ input, ctx }) => {+ try {+ const parent = await resolveOrThrow(ctx.taskModel, input.id);+ const graph = new TaskGraphService(ctx.serverDB, ctx.userId);+ const { descendants, plan } = await graph.planForParent(parent.id);++ if (plan.layers.length === 0) {+ return {+ data: {+ kickedOff: [],+ plan,+ skipped: { reason: 'nothing-runnable' as const },+ },+ success: true,+ };+ }++ // Layer 0 is the only wave we kick off here. Subsequent layers fire+ // automatically through `TaskRunnerService.cascadeOnCompletion` as+ // each upstream finishes.+ const firstLayer = plan.layers[0];+ const identifierToId = new Map(descendants.map((d) => [d.identifier, d.id]));+ const runner = new TaskRunnerService(ctx.serverDB, ctx.userId);++ const kickedOff: string[] = [];+ const failed: { error: string; identifier: string }[] = [];++ const settled = await Promise.allSettled(+ firstLayer.map(async (identifier) => {+ const id = identifierToId.get(identifier);+ if (!id) throw new Error(`Subtask ${identifier} not found`);+ await runner.runTask({ taskId: id });+ return identifier;+ }),+ );++ for (const [index, result] of settled.entries()) {+ const identifier = firstLayer[index];+ if (result.status === 'fulfilled') {+ kickedOff.push(identifier);+ } else {+ const message =+ result.reason instanceof Error ? result.reason.message : 'Failed to start task';+ failed.push({ error: message, identifier });+ }+ }++ return {+ data: { failed, kickedOff, plan },+ success: failed.length === 0,+ };+ } catch (error) {+ if (error instanceof TRPCError) throw error;+ console.error('[task:runReadySubtasks]', error);+ throw new TRPCError({+ cause: error,+ code: 'INTERNAL_SERVER_ERROR',+ message: 'Failed to run subtasks',+ });+ }+ }),+updateStatus: taskProcedure.input(z.object({@@ -1058,26 +1138,13 @@ export const taskRouter = router({allSubtasksDone = await model.areAllSubtasksCompleted(task.parentTaskId);}- // 3. Unlock tasks blocked by this one- const unlockedTasks = await model.getUnlockedTasks(task.id);- for (const ut of unlockedTasks) {- // Check beforeIds checkpoint on parent before starting- let shouldPause = false;- if (ut.parentTaskId) {- const parentTask = await model.findById(ut.parentTaskId);- if (parentTask && model.shouldPauseBeforeStart(parentTask, ut.identifier)) {- shouldPause = true;- }- }-- if (shouldPause) {- await model.updateStatus(ut.id, 'paused');- paused.push(ut.identifier);- } else {- await model.updateStatus(ut.id, 'running', { startedAt: new Date() });- unlocked.push(ut.identifier);- }- }+ // 3. Unlock tasks blocked by this one and actually kick them off.+ // The runner creates a topic + enqueues to QStash; status transitions+ // happen inside `runTask`, so callers don't need to flip it manually.+ const runner = new TaskRunnerService(ctx.serverDB, ctx.userId);+ const cascade = await runner.cascadeOnCompletion(task.id);+ unlocked.push(...cascade.started);+ paused.push(...cascade.paused);}return {diff --git a/src/server/services/brief/index.test.ts b/src/server/services/brief/index.test.tsindex f17713bf598..a23b223e4f8 100644--- a/src/server/services/brief/index.test.ts+++ b/src/server/services/brief/index.test.ts@@ -20,6 +20,13 @@ vi.mock('@/database/models/task', () => ({TaskModel: vi.fn(),}));+// Avoid pulling the real TaskRunnerService (which drags ModelRuntime) into the+// dynamic import the brief service performs after auto-completing a task.+const cascadeOnCompletion = vi.fn().mockResolvedValue({ failed: [], paused: [], started: [] });+vi.mock('@/server/services/taskRunner', () => ({+ TaskRunnerService: vi.fn().mockImplementation(() => ({ cascadeOnCompletion })),+}));+describe('BriefService', () => {const db = {} as LobeChatDatabase;const userId = 'user-1';@@ -38,6 +45,7 @@ describe('BriefService', () => {findById: vi.fn(),findByIds: vi.fn(),getTreeAgentIdsForTaskIds: vi.fn(),+ getUnlockedTasks: vi.fn(),updateStatus: vi.fn(),};@@ -46,6 +54,8 @@ describe('BriefService', () => {(AgentModel as any).mockImplementation(() => mockAgentModel);(BriefModel as any).mockImplementation(() => mockBriefModel);(TaskModel as any).mockImplementation(() => mockTaskModel);+ // Default: no downstream tasks unlocked. Specific tests can override.+ mockTaskModel.getUnlockedTasks.mockResolvedValue([]);});describe('enrichBriefsWithAgents', () => {@@ -201,6 +211,9 @@ describe('BriefService', () => {expect(mockTaskModel.updateStatus).toHaveBeenCalledWith('task-1', 'completed', {error: null,});+ // Brief approval must trigger downstream kickoff via the runner so+ // dependents don't sit in `backlog` waiting for a manual nudge.+ expect(cascadeOnCompletion).toHaveBeenCalledWith('task-1');});it('should NOT complete the task when approving a decision brief (mid-execution checkpoint)', async () => {diff --git a/src/server/services/brief/index.ts b/src/server/services/brief/index.tsindex 4ce368eba9c..526637a58d5 100644--- a/src/server/services/brief/index.ts+++ b/src/server/services/brief/index.ts@@ -22,9 +22,13 @@ export type BriefWithAgents = BriefItem & {export class BriefService {private agentModel: AgentModel;private briefModel: BriefModel;+ private db: LobeChatDatabase;private taskModel: TaskModel;+ private userId: string;constructor(db: LobeChatDatabase, userId: string) {+ this.db = db;+ this.userId = userId;this.agentModel = new AgentModel(db, userId);this.briefModel = new BriefModel(db, userId);this.taskModel = new TaskModel(db, userId);@@ -107,6 +111,14 @@ export class BriefService {const task = await this.taskModel.findById(brief.taskId);if (task && task.status !== 'scheduled') {await this.taskModel.updateStatus(brief.taskId, 'completed', { error: null });+ // Cascade to downstream tasks whose dependencies are now satisfied.+ // Without this, dependents stay in `backlog` until the user manually+ // triggers them β defeating the point of the dependency edge.+ // Lazy-loaded to avoid pulling ModelRuntime into BriefService's+ // import graph (TaskRunner β TaskLifecycle β ModelRuntime).+ const { TaskRunnerService } = await import('@/server/services/taskRunner');+ const runner = new TaskRunnerService(this.db, this.userId);+ await runner.cascadeOnCompletion(brief.taskId);}}diff --git a/src/server/services/taskGraph/index.test.ts b/src/server/services/taskGraph/index.test.tsnew file mode 100644index 00000000000..9bc89f175e8--- /dev/null+++ b/src/server/services/taskGraph/index.test.ts@@ -0,0 +1,173 @@+import { describe, expect, it } from 'vitest';++import { planSubtaskLayers, type SubtaskNode } from './index';++const node = (identifier: string, status: string, dependsOn: string[] = []): SubtaskNode => ({+ dependsOn,+ identifier,+ status,+});++describe('planSubtaskLayers', () => {+ it('returns an empty plan when there are no nodes', () => {+ const plan = planSubtaskLayers([]);+ expect(plan.layers).toEqual([]);+ expect(plan.totalRunnable).toBe(0);+ expect(plan.cycles).toEqual([]);+ });++ it('puts independent runnable tasks into a single layer', () => {+ const plan = planSubtaskLayers([+ node('T-1', 'backlog'),+ node('T-2', 'backlog'),+ node('T-3', 'backlog'),+ ]);+ expect(plan.layers).toEqual([['T-1', 'T-2', 'T-3']]);+ expect(plan.totalRunnable).toBe(3);+ });++ it('respects a linear dependency chain', () => {+ const plan = planSubtaskLayers([+ node('T-1', 'backlog'),+ node('T-2', 'backlog', ['T-1']),+ node('T-3', 'backlog', ['T-2']),+ ]);+ expect(plan.layers).toEqual([['T-1'], ['T-2'], ['T-3']]);+ });++ it('groups diamond dependencies into the right layers', () => {+ const plan = planSubtaskLayers([+ node('T-1', 'backlog'),+ node('T-2', 'backlog', ['T-1']),+ node('T-3', 'backlog', ['T-1']),+ node('T-4', 'backlog', ['T-2', 'T-3']),+ ]);+ expect(plan.layers).toEqual([['T-1'], ['T-2', 'T-3'], ['T-4']]);+ });++ it('skips already-completed tasks and treats their dependents as roots', () => {+ const plan = planSubtaskLayers([+ node('T-1', 'completed'),+ node('T-2', 'backlog', ['T-1']),+ node('T-3', 'backlog', ['T-2']),+ ]);+ expect(plan.layers).toEqual([['T-2'], ['T-3']]);+ expect(plan.alreadyDone).toEqual(['T-1']);+ });++ it('marks running / scheduled tasks as ineligible (not in layers)', () => {+ const plan = planSubtaskLayers([+ node('T-1', 'running'),+ node('T-2', 'backlog'),+ node('T-3', 'scheduled'),+ ]);+ expect(plan.layers).toEqual([['T-2']]);+ expect(plan.ineligible.sort()).toEqual(['T-1', 'T-3']);+ });++ it('treats failed and paused as runnable (allows re-run)', () => {+ const plan = planSubtaskLayers([node('T-1', 'failed'), node('T-2', 'paused', ['T-1'])]);+ expect(plan.layers).toEqual([['T-1'], ['T-2']]);+ });++ it('detects a simple two-node cycle', () => {+ const plan = planSubtaskLayers([+ node('T-1', 'backlog', ['T-2']),+ node('T-2', 'backlog', ['T-1']),+ ]);+ expect(plan.layers).toEqual([]);+ expect(plan.cycles.sort()).toEqual(['T-1', 'T-2']);+ });++ it('separates nodes blocked by a cycle from cycle members', () => {+ const plan = planSubtaskLayers([+ node('T-1', 'backlog', ['T-2']),+ node('T-2', 'backlog', ['T-1']),+ node('T-3', 'backlog', ['T-1']),+ ]);+ expect(plan.cycles.sort()).toEqual(['T-1', 'T-2']);+ expect(plan.blockedByCycle).toEqual(['T-3']);+ expect(plan.layers).toEqual([]);+ });++ it('still places acyclic branches when other branches contain cycles', () => {+ const plan = planSubtaskLayers([+ node('A', 'backlog', ['B']),+ node('B', 'backlog', ['A']),+ node('C', 'backlog'),+ node('D', 'backlog', ['C']),+ ]);+ expect(plan.layers).toEqual([['C'], ['D']]);+ expect(plan.cycles.sort()).toEqual(['A', 'B']);+ });++ it('drops dependency edges to canceled upstreams (treated as already done)', () => {+ const plan = planSubtaskLayers([node('T-1', 'canceled'), node('T-2', 'backlog', ['T-1'])]);+ expect(plan.layers).toEqual([['T-2']]);+ expect(plan.alreadyDone).toEqual(['T-1']);+ });++ it('holds back a dependent of an in-flight (running) descendant β does not free it to layer 1', () => {+ const plan = planSubtaskLayers([node('T-1', 'running'), node('T-2', 'backlog', ['T-1'])]);+ // T-2 must NOT be kicked off; T-1 is still running and the dependency is unsatisfied.+ expect(plan.layers).toEqual([]);+ expect(plan.blockedExternally).toEqual(['T-2']);+ expect(plan.ineligible).toEqual(['T-1']);+ });++ it('holds back a dependent of a scheduled descendant', () => {+ const plan = planSubtaskLayers([node('T-1', 'scheduled'), node('T-2', 'backlog', ['T-1'])]);+ expect(plan.layers).toEqual([]);+ expect(plan.blockedExternally).toEqual(['T-2']);+ });++ it('propagates external blockage transitively through in-batch downstream', () => {+ const plan = planSubtaskLayers([+ node('T-0', 'running'),+ node('T-1', 'backlog', ['T-0']), // blocked by T-0+ node('T-2', 'backlog', ['T-1']), // transitively blocked+ node('T-3', 'backlog'), // independent, free to run+ ]);+ expect(plan.layers).toEqual([['T-3']]);+ expect(plan.blockedExternally.sort()).toEqual(['T-1', 'T-2']);+ });++ it('treats an out-of-scope upstream that is still running as a blocker', () => {+ const plan = planSubtaskLayers(+ [node('T-2', 'backlog', ['EXT-1'])],+ new Map([['EXT-1', 'running']]),+ );+ expect(plan.layers).toEqual([]);+ expect(plan.blockedExternally).toEqual(['T-2']);+ });++ it('treats an out-of-scope upstream as satisfied when it is completed', () => {+ const plan = planSubtaskLayers(+ [node('T-2', 'backlog', ['EXT-1'])],+ new Map([['EXT-1', 'completed']]),+ );+ expect(plan.layers).toEqual([['T-2']]);+ expect(plan.blockedExternally).toEqual([]);+ });++ it('treats an unknown upstream identifier as a blocker', () => {+ // No external status provided β caller doesn't know what GHOST-9 is.+ const plan = planSubtaskLayers([node('T-2', 'backlog', ['GHOST-9'])]);+ expect(plan.layers).toEqual([]);+ expect(plan.blockedExternally).toEqual(['T-2']);+ });++ it('mixes satisfied + in-batch + external dependencies on the same node', () => {+ const plan = planSubtaskLayers(+ [+ node('T-1', 'completed'),+ node('T-2', 'backlog'),+ node('T-3', 'backlog', ['T-1', 'T-2', 'EXT-1']),+ ],+ new Map([['EXT-1', 'running']]),+ );+ // T-3 has T-1 (done) + T-2 (in-batch) + EXT-1 (external blocker) β overall blocked.+ expect(plan.layers).toEqual([['T-2']]);+ expect(plan.blockedExternally).toEqual(['T-3']);+ });+});diff --git a/src/server/services/taskGraph/index.ts b/src/server/services/taskGraph/index.tsnew file mode 100644index 00000000000..3ccafbe1808--- /dev/null+++ b/src/server/services/taskGraph/index.ts@@ -0,0 +1,307 @@+import type { TaskItem } from '@lobechat/types';++import { TaskModel } from '@/database/models/task';+import type { LobeChatDatabase } from '@/database/type';++export type SubtaskRunnableStatus = 'backlog' | 'paused' | 'failed';++const RUNNABLE_STATUSES: ReadonlySet<string> = new Set<SubtaskRunnableStatus>([+ 'backlog',+ 'paused',+ 'failed',+]);+/** Statuses that satisfy a `blocks` dependency β the upstream is "done enough". */+const TERMINAL_STATUSES: ReadonlySet<string> = new Set(['completed', 'canceled']);++/** Sentinel status used when an upstream task referenced by a dependency edge+ * cannot be located (deleted, hard-removed, etc.). Treated as a blocker so the+ * dependent doesn't get prematurely kicked off. */+const UNKNOWN_STATUS = '__unknown__';++export interface SubtaskGraphPlan {+ /** Tasks that already finished (completed / canceled) and are skipped. */+ alreadyDone: string[];+ /** Tasks blocked by an unbroken cycle and therefore unreachable. */+ blockedByCycle: string[];+ /**+ * Tasks waiting on a dependency we cannot satisfy in this batch β either an+ * in-flight task (running / scheduled / etc.) or a task outside this subtree.+ * They will be picked up later through the normal cascade once the blocker+ * completes; surfacing them here lets the UI explain why they're not in any+ * layer.+ */+ blockedExternally: string[];+ /** Identifiers participating in at least one dependency cycle. */+ cycles: string[];+ /**+ * Descendants whose own status excludes them from this batch (running /+ * scheduled / etc.). Distinct from `blockedExternally`, which describes a+ * runnable task held back by *some other* task.+ */+ ineligible: string[];+ /** Topologically sorted layers of runnable tasks. Layer N waits on layer N-1. */+ layers: string[][];+ /** Total runnable tasks across all layers. */+ totalRunnable: number;+}++export interface SubtaskNode {+ /** Tasks this one depends on (must be `completed` first). */+ dependsOn: string[];+ identifier: string;+ status: string;+}++/**+ * Group runnable subtasks into topological layers using Kahn's algorithm.+ *+ * Edge classification (per dependency):+ * - upstream is `completed` / `canceled` β satisfied, edge dropped+ * - upstream is runnable AND in this batch β tracked as in-batch edge+ * - anything else (in-flight descendant, out-of-scope task, unknown) β+ * treated as an *external blocker*. The dependent is excluded from layers+ * and surfaced via `blockedExternally`. Crucially we never silently drop+ * such an edge β that would let the dependent run before its blocker.+ *+ * `externalStatuses` lets the caller pass in statuses for upstream identifiers+ * that aren't represented in `nodes` (e.g. dependencies on tasks outside the+ * current subtree). Identifiers missing from both `nodes` and `externalStatuses`+ * are treated as unknown / blocking.+ */+export const planSubtaskLayers = (+ nodes: SubtaskNode[],+ externalStatuses: ReadonlyMap<string, string> = new Map(),+): SubtaskGraphPlan => {+ const alreadyDone: string[] = [];+ const ineligible: string[] = [];+ const runnableSet = new Set<string>();+ const statusByIdentifier = new Map<string, string>();++ for (const node of nodes) {+ statusByIdentifier.set(node.identifier, node.status);+ if (TERMINAL_STATUSES.has(node.status)) {+ alreadyDone.push(node.identifier);+ } else if (RUNNABLE_STATUSES.has(node.status)) {+ runnableSet.add(node.identifier);+ } else {+ ineligible.push(node.identifier);+ }+ }++ const resolveDepStatus = (depIdentifier: string): string =>+ statusByIdentifier.get(depIdentifier) ?? externalStatuses.get(depIdentifier) ?? UNKNOWN_STATUS;++ type EdgeKind = 'satisfied' | 'in-batch' | 'external';+ const classifyEdge = (depIdentifier: string): EdgeKind => {+ const status = resolveDepStatus(depIdentifier);+ if (TERMINAL_STATUSES.has(status)) return 'satisfied';+ if (runnableSet.has(depIdentifier)) return 'in-batch';+ // Runnable status outside this batch, in-flight (running/scheduled), or+ // unknown β all block until something else completes them.+ return 'external';+ };++ // Seed externally-blocked set with runnable nodes that have any external dep.+ const externallyBlocked = new Set<string>();+ const inBatchUpstream = new Map<string, string[]>(); // node β its in-batch upstream deps+ const inBatchDownstream = new Map<string, string[]>(); // upstream β in-batch dependents+ for (const id of runnableSet) {+ inBatchUpstream.set(id, []);+ inBatchDownstream.set(id, []);+ }++ for (const node of nodes) {+ if (!runnableSet.has(node.identifier)) continue;+ for (const dep of node.dependsOn) {+ const kind = classifyEdge(dep);+ if (kind === 'satisfied') continue;+ if (kind === 'external') {+ externallyBlocked.add(node.identifier);+ continue;+ }+ // in-batch+ inBatchUpstream.get(node.identifier)!.push(dep);+ inBatchDownstream.get(dep)!.push(node.identifier);+ }+ }++ // Propagate external blockage through in-batch edges: anything downstream of+ // an externally-blocked node is itself blocked (its blocker won't finish in+ // this batch either).+ const blockQueue = [...externallyBlocked];+ while (blockQueue.length > 0) {+ const id = blockQueue.shift()!;+ for (const child of inBatchDownstream.get(id) ?? []) {+ if (!externallyBlocked.has(child)) {+ externallyBlocked.add(child);+ blockQueue.push(child);+ }+ }+ }++ // Eligible = runnable AND not externally blocked. Run Kahn over this subset.+ const eligibleSet = new Set<string>();+ for (const id of runnableSet) if (!externallyBlocked.has(id)) eligibleSet.add(id);++ const inDegree = new Map<string, number>();+ for (const id of eligibleSet) {+ const upstream = inBatchUpstream.get(id) ?? [];+ inDegree.set(id, upstream.filter((u) => eligibleSet.has(u)).length);+ }++ const layers: string[][] = [];+ let frontier = [...eligibleSet].filter((id) => (inDegree.get(id) ?? 0) === 0);+ const placed = new Set<string>();++ while (frontier.length > 0) {+ const layer = [...frontier].sort();+ layers.push(layer);+ for (const id of layer) placed.add(id);++ const nextFrontier: string[] = [];+ for (const id of layer) {+ for (const child of inBatchDownstream.get(id) ?? []) {+ if (!eligibleSet.has(child)) continue;+ const remaining = (inDegree.get(child) ?? 0) - 1;+ inDegree.set(child, remaining);+ if (remaining === 0) nextFrontier.push(child);+ }+ }+ frontier = nextFrontier;+ }++ const unplaced = [...eligibleSet].filter((id) => !placed.has(id));+ const cycles = findCycleMembers(unplaced, inBatchDownstream);+ const blockedByCycle = unplaced.filter((id) => !cycles.includes(id));++ const totalRunnable = layers.reduce((sum, layer) => sum + layer.length, 0);++ return {+ alreadyDone: alreadyDone.sort(),+ blockedByCycle: blockedByCycle.sort(),+ blockedExternally: [...externallyBlocked].sort(),+ cycles: cycles.sort(),+ ineligible: ineligible.sort(),+ layers,+ totalRunnable,+ };+};++/**+ * Identify nodes that lie on a cycle inside the residual subgraph.+ * Nodes left in `unplaced` are either on a cycle or downstream of one;+ * we walk forward from each candidate and flag those that can reach themselves.+ */+const findCycleMembers = (unplaced: string[], downstream: Map<string, string[]>): string[] => {+ const candidates = new Set(unplaced);+ const cycleMembers = new Set<string>();++ for (const start of unplaced) {+ if (cycleMembers.has(start)) continue;+ const stack = [start];+ const visited = new Set<string>();+ while (stack.length > 0) {+ const node = stack.pop()!;+ for (const child of downstream.get(node) ?? []) {+ if (!candidates.has(child)) continue;+ if (child === start) {+ cycleMembers.add(start);+ break;+ }+ if (!visited.has(child)) {+ visited.add(child);+ stack.push(child);+ }+ }+ if (cycleMembers.has(start)) break;+ }+ }++ return [...cycleMembers];+};++export class TaskGraphService {+ private taskModel: TaskModel;++ constructor(db: LobeChatDatabase, userId: string) {+ this.taskModel = new TaskModel(db, userId);+ }++ /**+ * Build a layered execution plan for the descendants of a parent task.+ * Returns layers in dependency order plus diagnostics (cycles, skipped, etc.).+ *+ * Cross-scope dependencies (a descendant depending on a task outside this+ * subtree) are resolved by fetching the upstream's status; if it's not yet+ * `completed`/`canceled` the dependent is recorded as `blockedExternally`+ * rather than placed in a layer.+ */+ async planForParent(parentTaskId: string): Promise<{+ descendants: TaskItem[];+ plan: SubtaskGraphPlan;+ }> {+ const descendants = await this.taskModel.findAllDescendants(parentTaskId);+ if (descendants.length === 0) {+ return {+ descendants: [],+ plan: {+ alreadyDone: [],+ blockedByCycle: [],+ blockedExternally: [],+ cycles: [],+ ineligible: [],+ layers: [],+ totalRunnable: 0,+ },+ };+ }++ const ids = descendants.map((d) => d.id);+ const deps = await this.taskModel.getDependenciesByTaskIds(ids);+ const idToIdentifier = new Map(descendants.map((d) => [d.id, d.identifier]));++ // Fetch upstream tasks referenced by `blocks` deps that aren't in this+ // subtree, so we know whether they're done or still in flight.+ const externalUpstreamIds = new Set<string>();+ for (const dep of deps) {+ if (dep.type !== 'blocks') continue;+ if (!idToIdentifier.has(dep.dependsOnId)) externalUpstreamIds.add(dep.dependsOnId);+ }+ const externalUpstreams =+ externalUpstreamIds.size > 0 ? await this.taskModel.findByIds([...externalUpstreamIds]) : [];+ const allIdToIdentifier = new Map(idToIdentifier);+ const externalStatusByIdentifier = new Map<string, string>();+ for (const upstream of externalUpstreams) {+ allIdToIdentifier.set(upstream.id, upstream.identifier);+ externalStatusByIdentifier.set(upstream.identifier, upstream.status);+ }++ const dependsOnByIdentifier = new Map<string, string[]>();+ let missingCounter = 0;+ for (const dep of deps) {+ if (dep.type !== 'blocks') continue;+ const taskIdentifier = idToIdentifier.get(dep.taskId);+ if (!taskIdentifier) continue;++ let upstreamIdentifier = allIdToIdentifier.get(dep.dependsOnId);+ if (!upstreamIdentifier) {+ // Upstream task no longer exists. Synthesize a placeholder identifier+ // (with no recorded status) so the dependent is treated as externally+ // blocked rather than silently freed.+ upstreamIdentifier = `__missing:${missingCounter++}`;+ }++ const list = dependsOnByIdentifier.get(taskIdentifier) ?? [];+ list.push(upstreamIdentifier);+ dependsOnByIdentifier.set(taskIdentifier, list);+ }++ const nodes: SubtaskNode[] = descendants.map((d) => ({+ dependsOn: dependsOnByIdentifier.get(d.identifier) ?? [],+ identifier: d.identifier,+ status: d.status,+ }));++ return { descendants, plan: planSubtaskLayers(nodes, externalStatusByIdentifier) };+ }+}diff --git a/src/server/services/taskLifecycle/index.ts b/src/server/services/taskLifecycle/index.tsindex daf35575277..64e5a567f17 100644--- a/src/server/services/taskLifecycle/index.ts+++ b/src/server/services/taskLifecycle/index.ts@@ -552,6 +552,7 @@ export class TaskLifecycleService {type: 'result',});await this.taskModel.updateStatus(taskId, 'completed', { error: null });+ await this.cascadeAfterAutoComplete(taskId);return true;}@@ -587,4 +588,20 @@ export class TaskLifecycleService {return false;}}++ /**+ * Trigger downstream task kickoff after this task auto-completes via judge.+ *+ * Lazy-imports `TaskRunnerService` to break the runner β lifecycle import+ * cycle (the runner already constructs a lifecycle for its own hooks).+ */+ private async cascadeAfterAutoComplete(completedTaskId: string): Promise<void> {+ try {+ const { TaskRunnerService } = await import('@/server/services/taskRunner');+ const runner = new TaskRunnerService(this.db, this.userId);+ await runner.cascadeOnCompletion(completedTaskId);+ } catch (e) {+ console.warn('[TaskLifecycle] dependency cascade failed:', e);+ }+ }}diff --git a/src/server/services/taskRunner/index.ts b/src/server/services/taskRunner/index.tsindex 93fb2c1daef..e2660574f04 100644--- a/src/server/services/taskRunner/index.ts+++ b/src/server/services/taskRunner/index.ts@@ -1,6 +1,6 @@import { TaskIdentifier as TaskSkillIdentifier } from '@lobechat/builtin-skills';import { BriefIdentifier } from '@lobechat/builtin-tool-brief';-import type { ExecAgentResult } from '@lobechat/types';+import type { ExecAgentResult, TaskItem } from '@lobechat/types';import { TRPCError } from '@trpc/server';import debug from 'debug';@@ -226,4 +226,73 @@ export class TaskRunnerService {throw error;}}++ /**+ * Result of cascading kickoff after a task transitions to `completed`.+ * Mirrors the legacy unlock-only response so callers can keep their+ * payload shape unchanged.+ */+ static cascadeEmpty(): CascadeResult {+ return { failed: [], paused: [], started: [] };+ }++ /**+ * After a task transitions to `completed`, find downstream tasks whose+ * dependencies are now fully met and *actually run them*.+ *+ * Why this matters: the legacy code path flipped unlocked tasks to `running`+ * in the DB but never created a topic β so they appeared running while no+ * agent execution was in flight. This method bridges the gap.+ *+ * - Honors parent `beforeIds` checkpoints by leaving such tasks `paused`.+ * - If `runTask` throws (e.g. no assignee), the task is left in `paused`+ * 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);+ if (unlocked.length === 0) return TaskRunnerService.cascadeEmpty();++ const result: CascadeResult = { failed: [], paused: [], started: [] };++ for (const task of unlocked) {+ if (await this.shouldHoldForCheckpoint(task)) {+ await this.taskModel.updateStatus(task.id, 'paused');+ result.paused.push(task.identifier);+ continue;+ }++ try {+ await this.runTask({ taskId: task.id });+ result.started.push(task.identifier);+ } catch (error) {+ const message = error instanceof Error ? error.message : 'Failed to start task';+ log('cascadeOnCompletion: runTask failed for %s: %s', task.identifier, message);+ // Best-effort: mark as paused so the user can see why it didn't run.+ try {+ await this.taskModel.updateStatus(task.id, 'paused', { error: message });+ } catch {+ /* ignore β surfaced via failed list */+ }+ result.failed.push({ error: message, identifier: task.identifier });+ }+ }++ return result;+ }++ private async shouldHoldForCheckpoint(task: TaskItem): Promise<boolean> {+ if (!task.parentTaskId) return false;+ const parent = await this.taskModel.findById(task.parentTaskId);+ if (!parent) return false;+ return this.taskModel.shouldPauseBeforeStart(parent, task.identifier);+ }+}++export interface CascadeResult {+ /** Tasks where kickoff threw and were marked paused with an error. */+ failed: { error: string; identifier: string }[];+ /** Tasks held back by a parent's `beforeIds` checkpoint. */+ paused: string[];+ /** Tasks that were successfully kicked off (topic created). */+ started: string[];}diff --git a/src/services/__tests__/task.test.ts b/src/services/__tests__/task.test.tsindex 5396735a8fe..1b770ab8198 100644--- a/src/services/__tests__/task.test.ts+++ b/src/services/__tests__/task.test.ts@@ -30,9 +30,11 @@ vi.mock('@/libs/trpc/client', () => ({groupList: { query: vi.fn() },list: { query: vi.fn() },pinDocument: { mutate: vi.fn() },+ previewSubtaskLayers: { query: vi.fn() },removeDependency: { mutate: vi.fn() },reorderSubtasks: { mutate: vi.fn() },run: { mutate: vi.fn() },+ runReadySubtasks: { mutate: vi.fn() },runReview: { mutate: vi.fn() },unpinDocument: { mutate: vi.fn() },update: { mutate: vi.fn() },@@ -146,6 +148,16 @@ describe('TaskService', () => {expect(lambdaClient.task.cancelTopic.mutate).toHaveBeenCalledWith({ topicId: 'tpc_1' });});+ it('previewSubtaskLayers should call task.previewSubtaskLayers.query', async () => {+ await taskService.previewSubtaskLayers('T-1');+ expect(lambdaClient.task.previewSubtaskLayers.query).toHaveBeenCalledWith({ id: 'T-1' });+ });++ it('runReadySubtasks should call task.runReadySubtasks.mutate', async () => {+ await taskService.runReadySubtasks('T-1');+ expect(lambdaClient.task.runReadySubtasks.mutate).toHaveBeenCalledWith({ id: 'T-1' });+ });+it('pinDocument should pass all params', async () => {await taskService.pinDocument('T-1', 'doc_1', 'user');expect(lambdaClient.task.pinDocument.mutate).toHaveBeenCalledWith({diff --git a/src/services/task.ts b/src/services/task.tsindex c67cbb11518..00923c0918b 100644--- a/src/services/task.ts+++ b/src/services/task.ts@@ -92,6 +92,10 @@ class TaskService {run = async (id: string, params?: { continueTopicId?: string; prompt?: string }) =>lambdaClient.task.run.mutate({ id, ...params });+ previewSubtaskLayers = async (id: string) => lambdaClient.task.previewSubtaskLayers.query({ id });++ runReadySubtasks = async (id: string) => lambdaClient.task.runReadySubtasks.mutate({ id });+addComment = async (id: string, content: string, opts?: { briefId?: string; topicId?: string }) =>lambdaClient.task.addComment.mutate({ content, id, ...opts });diff --git a/src/store/task/slices/lifecycle/action.ts b/src/store/task/slices/lifecycle/action.tsindex 298f9e12a0a..c64f037e211 100644--- a/src/store/task/slices/lifecycle/action.ts+++ b/src/store/task/slices/lifecycle/action.ts@@ -52,6 +52,13 @@ export class TaskLifecycleSliceActionImpl {}};+ runReadySubtasks = async (parentTaskId: string) => {+ const result = await taskService.runReadySubtasks(parentTaskId);+ await this.#get().internal_refreshTaskDetail(parentTaskId);+ await this.#get().refreshTaskList();+ return result;+ };+updateTaskStatus = async (id: string | undefined,status: TaskStatus,