Skip to content

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

πŸ› fix(task): auto-complete successful subtasks (#18591)

Arvin Xu84bcfba74961
diff --git a/apps/server/src/services/taskLifecycle/index.ts b/apps/server/src/services/taskLifecycle/index.ts
index f889a98a145..35427e1dbb9 100644
--- a/apps/server/src/services/taskLifecycle/index.ts
+++ b/apps/server/src/services/taskLifecycle/index.ts
@@ -239,11 +239,12 @@ export class TaskLifecycleService {
// 'scheduled' to wait for the next tick. They never auto-pause
// on success β€” only `reason === 'error'` below puts them in
// 'paused' for human attention.
- // - Non-automation tasks fall back to the legacy "pause for user
- // review" behavior: a 'result' brief from the agent is a
- // *proposal* of completion, and the user must explicitly approve
- // via the brief action to transition to 'completed'. Auto-complete
- // only happens via the Judge path above.
+ // - Subtasks complete immediately. Their parent owns the broader
+ // delivery decision, so pausing every successful child for a second
+ // user review stalls an otherwise autonomous task graph. Completing
+ // the child also unlocks its downstream siblings.
+ // - Root non-automation tasks keep the legacy "pause for user review"
+ // behavior: their result is the user-facing delivery boundary.
// "Let go" for verify-bound runs: when a confirmed verify plan exists for
// this op, delivery acceptance is decided asynchronously by Verify
// (driveTaskFromVerify completes / pauses the task on settle), so we must
@@ -275,6 +276,15 @@ export class TaskLifecycleService {
// failed β€” the live `error` alone would silently self-heal.
await this.recordAutomationRecovery(currentTask);
await this.taskModel.updateStatus(taskId, 'scheduled', { error: null });
+ } else if (!verifyBound && currentTask.parentTaskId) {
+ const checkpoint = this.taskModel.getCheckpointConfig(currentTask);
+ if (checkpoint.topic?.after) {
+ await this.taskModel.updateStatusIfCurrent(taskId, 'running', 'paused', {
+ error: null,
+ });
+ } else {
+ await this.completeSubtask(currentTask);
+ }
} else if (!verifyBound && this.taskModel.shouldPauseOnTopicComplete(currentTask)) {
await this.taskModel.updateStatus(taskId, 'paused', { error: null });
}
@@ -499,6 +509,40 @@ export class TaskLifecycleService {
if (finalTask) await this.maybeRearmHeartbeat(finalTask, reason);
}
+ /**
+ * Settle a successful child task and advance its sibling dependency graph.
+ *
+ * This mirrors the completion side effects of TaskService.updateStatus
+ * without importing TaskService here (TaskRunner already depends on this
+ * lifecycle service). The dynamic import keeps that module cycle out of
+ * initialization while preserving the runner's single cascade implementation.
+ */
+ private async completeSubtask(task: TaskItem): Promise<void> {
+ const completedTask = await this.taskModel.updateStatusIfCurrent(
+ task.id,
+ 'running',
+ 'completed',
+ {
+ completedAt: new Date(),
+ error: null,
+ },
+ );
+ if (!completedTask) {
+ log('subtask=%s no longer running β€” skipping completion cascade', task.identifier);
+ return;
+ }
+
+ const parentTask = await this.taskModel.findById(completedTask.parentTaskId!);
+ if (parentTask && this.taskModel.shouldPauseAfterComplete(parentTask, task.identifier)) {
+ await this.taskModel.updateStatus(parentTask.id, 'paused');
+ }
+
+ const { TaskRunnerService } = await import('@/server/services/taskRunner');
+ await new TaskRunnerService(this.db, this.userId, this.workspaceId).cascadeOnCompletion(
+ task.id,
+ );
+ }
+
/**
* Deliver the finished task's result back to the conversation that created
* it. Always best-effort: a bridge failure must never affect task status, so
diff --git a/apps/server/src/services/taskLifecycle/onTopicComplete.test.ts b/apps/server/src/services/taskLifecycle/onTopicComplete.test.ts
index 70844bc21d4..a8eff70ac7c 100644
--- a/apps/server/src/services/taskLifecycle/onTopicComplete.test.ts
+++ b/apps/server/src/services/taskLifecycle/onTopicComplete.test.ts
@@ -9,6 +9,14 @@ const fakeScheduler = {
scheduleNextTopic: vi.fn().mockResolvedValue('msg-new'),
};
+const { cascadeOnCompletion } = vi.hoisted(() => ({
+ cascadeOnCompletion: vi.fn().mockResolvedValue({ failed: [], paused: [], started: [] }),
+}));
+
+vi.mock('@/server/services/taskRunner', () => ({
+ TaskRunnerService: vi.fn(() => ({ cascadeOnCompletion })),
+}));
+
vi.mock('@/server/services/taskScheduler', () => ({
createTaskSchedulerModule: () => fakeScheduler,
}));
@@ -67,6 +75,7 @@ const baseTask = (overrides: Partial<TaskItem> = {}): TaskItem =>
describe('TaskLifecycleService.onTopicComplete', () => {
let service: TaskLifecycleService;
let updateStatus: ReturnType<typeof vi.fn>;
+ let updateStatusIfCurrent: ReturnType<typeof vi.fn>;
let updateContext: ReturnType<typeof vi.fn>;
let findById: ReturnType<typeof vi.fn>;
let updateHeartbeat: ReturnType<typeof vi.fn>;
@@ -78,10 +87,12 @@ describe('TaskLifecycleService.onTopicComplete', () => {
fakeScheduler.scheduleNextTopic.mockClear().mockResolvedValue('msg-new');
notifyCompleted.mockReset().mockResolvedValue(undefined);
notifyFailed.mockReset().mockResolvedValue(undefined);
+ cascadeOnCompletion.mockReset().mockResolvedValue({ failed: [], paused: [], started: [] });
service = new TaskLifecycleService({} as any, 'user-1');
updateStatus = vi.fn().mockResolvedValue(null);
+ updateStatusIfCurrent = vi.fn();
updateContext = vi.fn().mockResolvedValue(null);
findById = vi.fn();
updateHeartbeat = vi.fn().mockResolvedValue(undefined);
@@ -92,10 +103,12 @@ describe('TaskLifecycleService.onTopicComplete', () => {
const taskModel = (service as any).taskModel;
taskModel.updateStatus = updateStatus;
+ taskModel.updateStatusIfCurrent = updateStatusIfCurrent;
taskModel.updateContext = updateContext;
taskModel.findById = findById;
taskModel.updateHeartbeat = updateHeartbeat;
taskModel.getReviewConfig = getReviewConfig;
+ taskModel.getCheckpointConfig = vi.fn().mockReturnValue({});
// Default checkpoint behavior: pause after topic complete
taskModel.shouldPauseOnTopicComplete = vi.fn().mockReturnValue(true);
// Avoid generateHandoff side effects by skipping when lastAssistantContent is undefined
@@ -258,6 +271,99 @@ describe('TaskLifecycleService.onTopicComplete', () => {
expect(updateStatus).not.toHaveBeenCalledWith('task-1', 'scheduled', expect.anything());
});
+ it('successful subtask β†’ completes and unlocks downstream tasks instead of pausing', async () => {
+ const task = baseTask({ automationMode: null, parentTaskId: 'parent-task' });
+ const parentTask = baseTask({ id: 'parent-task', identifier: 'TASK-0' });
+ updateStatusIfCurrent.mockResolvedValue(task);
+ findById
+ .mockResolvedValueOnce(task)
+ .mockResolvedValueOnce(parentTask)
+ .mockResolvedValue(task);
+ (service as any).taskModel.shouldPauseAfterComplete = vi.fn().mockReturnValue(false);
+
+ await service.onTopicComplete({
+ operationId: 'op-1',
+ reason: 'done',
+ taskId: 'task-1',
+ taskIdentifier: 'TASK-1',
+ topicId: 'topic-1',
+ });
+
+ expect(updateStatusIfCurrent).toHaveBeenCalledWith('task-1', 'running', 'completed', {
+ completedAt: expect.any(Date),
+ error: null,
+ });
+ expect(updateStatus).not.toHaveBeenCalledWith('task-1', 'paused', expect.anything());
+ expect(cascadeOnCompletion).toHaveBeenCalledWith('task-1');
+ });
+
+ it('successful subtask still honors an explicit parent after-completion checkpoint', async () => {
+ const task = baseTask({ automationMode: null, parentTaskId: 'parent-task' });
+ const parentTask = baseTask({ id: 'parent-task', identifier: 'TASK-0' });
+ updateStatusIfCurrent.mockResolvedValue(task);
+ findById
+ .mockResolvedValueOnce(task)
+ .mockResolvedValueOnce(parentTask)
+ .mockResolvedValue(task);
+ (service as any).taskModel.shouldPauseAfterComplete = vi.fn().mockReturnValue(true);
+
+ await service.onTopicComplete({
+ operationId: 'op-1',
+ reason: 'done',
+ taskId: 'task-1',
+ taskIdentifier: 'TASK-1',
+ topicId: 'topic-1',
+ });
+
+ expect(updateStatusIfCurrent).toHaveBeenCalledWith('task-1', 'running', 'completed', {
+ completedAt: expect.any(Date),
+ error: null,
+ });
+ expect(updateStatus).toHaveBeenCalledWith('parent-task', 'paused');
+ expect(cascadeOnCompletion).toHaveBeenCalledWith('task-1');
+ });
+
+ it('successful subtask with an explicit topic-after checkpoint β†’ pauses for review', async () => {
+ const task = baseTask({ automationMode: null, parentTaskId: 'parent-task' });
+ findById.mockResolvedValue(task);
+ (service as any).taskModel.getCheckpointConfig = vi
+ .fn()
+ .mockReturnValue({ topic: { after: true } });
+
+ await service.onTopicComplete({
+ operationId: 'op-1',
+ reason: 'done',
+ taskId: 'task-1',
+ taskIdentifier: 'TASK-1',
+ topicId: 'topic-1',
+ });
+
+ expect(updateStatusIfCurrent).toHaveBeenCalledWith('task-1', 'running', 'paused', {
+ error: null,
+ });
+ expect(cascadeOnCompletion).not.toHaveBeenCalled();
+ });
+
+ it('late successful callback does not overwrite a child that is no longer running', async () => {
+ const task = baseTask({ automationMode: null, parentTaskId: 'parent-task' });
+ findById.mockResolvedValue(task);
+ updateStatusIfCurrent.mockResolvedValue(null);
+
+ await service.onTopicComplete({
+ operationId: 'op-1',
+ reason: 'done',
+ taskId: 'task-1',
+ taskIdentifier: 'TASK-1',
+ topicId: 'topic-1',
+ });
+
+ expect(updateStatusIfCurrent).toHaveBeenCalledWith('task-1', 'running', 'completed', {
+ completedAt: expect.any(Date),
+ error: null,
+ });
+ expect(cascadeOnCompletion).not.toHaveBeenCalled();
+ });
+
it('non-automation task with shouldPauseOnTopicComplete=false β†’ no status update', async () => {
const task = baseTask({ automationMode: null });
findById.mockResolvedValue(task);
diff --git a/packages/database/src/models/__tests__/task.test.ts b/packages/database/src/models/__tests__/task.test.ts
index d080e75047f..cf21f083a58 100644
--- a/packages/database/src/models/__tests__/task.test.ts
+++ b/packages/database/src/models/__tests__/task.test.ts
@@ -736,6 +736,21 @@ describe('TaskModel', () => {
expect(updated!.status).toBe('running');
expect(updated!.startedAt).toBeDefined();
});
+
+ it('should update status only when the current status matches', async () => {
+ const model = new TaskModel(serverDB, userId);
+ const task = await model.create({ instruction: 'Test' });
+ await model.updateStatus(task.id, 'running');
+
+ const completed = await model.updateStatusIfCurrent(task.id, 'running', 'completed', {
+ completedAt: new Date(),
+ });
+ const staleUpdate = await model.updateStatusIfCurrent(task.id, 'running', 'failed');
+
+ expect(completed?.status).toBe('completed');
+ expect(staleUpdate).toBeNull();
+ expect((await model.findById(task.id))?.status).toBe('completed');
+ });
});
describe('heartbeat', () => {
diff --git a/packages/database/src/models/task.ts b/packages/database/src/models/task.ts
index fe406f66740..e1aa2adb335 100644
--- a/packages/database/src/models/task.ts
+++ b/packages/database/src/models/task.ts
@@ -898,6 +898,22 @@ export class TaskModel {
return this.update(id, { status, ...extra });
}
+ /** Atomically transition a task only while it still has the expected status. */
+ async updateStatusIfCurrent(
+ id: string,
+ currentStatus: string,
+ status: string,
+ extra?: { completedAt?: Date; error?: string | null; startedAt?: Date },
+ ): Promise<TaskItem | null> {
+ const [task] = await this.db
+ .update(tasks)
+ .set({ status, updatedAt: new Date(), ...extra })
+ .where(and(eq(tasks.id, id), eq(tasks.status, currentStatus), this.ownership()))
+ .returning();
+
+ return task ?? null;
+ }
+
async batchUpdateStatus(ids: string[], status: string): Promise<number> {
const result = await this.db
.update(tasks)