From 4793e46c92d2cdad399d29f28d7bb1088bd4f251 Mon Sep 17 00:00:00 2001 From: Manash Pratim Bhuyan Date: Sun, 22 Nov 2026 19:01:14 +0530 Subject: [PATCH] fix(server): a thread awaiting a delegated task's result no longer reports completed early --- .../orchestration-v2/ProjectionStore.test.ts | 381 ++++++++++++++++++ .../src/orchestration-v2/ProjectionStore.ts | 190 +++++++-- apps/server/src/persistence/Migrations.ts | 2 + .../108_PendingSubagentDeliveryIndex.ts | 16 + .../reconcileV2PreviewMigration.test.ts | 2 + apps/web/src/components/ChatView.logic.ts | 1 + .../src/state/threadExecution.ts | 1 + ...chestrationV2PendingBackgroundWork.test.ts | 304 ++++++++++++++ .../orchestrationV2PendingBackgroundWork.ts | 73 +++- 9 files changed, 932 insertions(+), 38 deletions(-) create mode 100644 apps/server/src/persistence/Migrations/108_PendingSubagentDeliveryIndex.ts diff --git a/apps/server/src/orchestration-v2/ProjectionStore.test.ts b/apps/server/src/orchestration-v2/ProjectionStore.test.ts index 8df11001e241a..e0840af91a5ec 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.test.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.test.ts @@ -12131,4 +12131,385 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => { } }), ); + + it.effect( + "holds shell, awareness, and settlement pending background work while a finished delegated subagent awaits wake delivery", + () => + Effect.gen(function* () { + const store = yield* ProjectionStore.ProjectionStoreV2; + const threadId = ThreadId.make("thread:delegated-wake-gap"); + const childThreadId = ThreadId.make("thread:delegated-wake-gap:child"); + const runId = RunId.make("run:delegated-wake-gap:4"); + const rootNodeId = NodeId.make("node:delegated-wake-gap:root"); + const subagentId = NodeId.make("node:delegated-wake-gap:subagent"); + const itemId = TurnItemId.make("turn-item:delegated-wake-gap:subagent"); + const completedAt = DateTime.makeUnsafe("2026-11-22T12:24:58.666Z"); + const childFinishedAt = DateTime.makeUnsafe("2026-11-22T12:29:17.256Z"); + const deliveredAt = DateTime.makeUnsafe("2026-11-22T12:29:17.500Z"); + const thread = { + createdBy: "user" as const, + creationSource: "web" as const, + id: threadId, + projectId: ProjectId.make("project:delegated-wake-gap"), + title: "Review PRs", + providerInstanceId, + modelSelection, + runtimeMode: "full-access" as const, + interactionMode: "default" as const, + branch: null, + worktreePath: null, + activeProviderThreadId: null, + lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId }, + forkedFrom: null, + createdAt: completedAt, + updatedAt: completedAt, + archivedAt: null, + settledOverride: null, + settledAt: null, + lastVisitedAt: null, + deletedAt: null, + }; + const run = { + id: runId, + threadId, + ordinal: 4, + providerInstanceId, + modelSelection, + providerThreadId: null, + userMessageId: MessageId.make("message:delegated-wake-gap:4"), + rootNodeId, + activeAttemptId: null, + status: "completed" as const, + requestedAt: completedAt, + startedAt: completedAt, + completedAt, + checkpointId: null, + contextHandoffId: null, + delegatedCompletion: { + disposition: "open" as const, + nextGeneration: 2, + delivery: { + generation: 1, + messageId: MessageId.make("message:delegated-wake-gap:5"), + taskIds: [subagentId], + }, + }, + }; + const subagent = { + id: subagentId, + threadId, + runId, + parentNodeId: rootNodeId, + origin: "app_owned" as const, + createdBy: "agent" as const, + driver, + providerInstanceId, + providerThreadId: null, + childThreadId, + nativeTaskRef: null, + prompt: "Audit PRs", + title: "Audit PRs", + model: modelSelection.model, + modelSelection, + completionWake: "always" as const, + completionDelivery: { state: "claimed" as const, observedByRunId: null }, + status: "completed" as const, + result: "Looks good", + startedAt: completedAt, + completedAt: childFinishedAt, + updatedAt: childFinishedAt, + }; + yield* store.apply({ + id: EventId.make("event:delegated-wake-gap:thread"), + type: "thread.created", + threadId, + occurredAt: completedAt, + payload: thread, + }); + yield* store.apply({ + id: EventId.make("event:delegated-wake-gap:run"), + type: "run.created", + threadId, + runId, + driver, + providerInstanceId, + occurredAt: completedAt, + payload: run, + }); + yield* store.apply({ + id: EventId.make("event:delegated-wake-gap:turn-item"), + type: "turn-item.updated", + threadId, + runId, + nodeId: subagentId, + driver, + providerInstanceId, + occurredAt: childFinishedAt, + payload: { + id: itemId, + threadId, + runId, + nodeId: subagentId, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: 1, + type: "subagent", + subagentId, + origin: "app_owned", + driver, + providerInstanceId, + childThreadId, + prompt: "Audit PRs", + title: "Audit PRs", + result: "Looks good", + status: "completed", + startedAt: completedAt, + completedAt: childFinishedAt, + updatedAt: childFinishedAt, + }, + }); + yield* store.apply({ + id: EventId.make("event:delegated-wake-gap:subagent-claimed"), + type: "subagent.updated", + threadId, + runId, + nodeId: subagentId, + driver, + providerInstanceId, + occurredAt: childFinishedAt, + payload: subagent, + }); + + const expectedPending = [ + { + taskId: subagentId, + description: "Audit PRs", + kind: "subagent" as const, + childThreadId, + }, + ]; + const assertPending = Effect.fnUntraced(function* ( + expected: ReadonlyArray, + expectedPhase: "running" | "completed", + ) { + const shell = yield* store.getThreadShell(threadId); + const listed = (yield* store.getShellSnapshot()).threads.find( + (candidate) => candidate.id === threadId, + ); + const awareness = (yield* store.getAgentAwarenessSnapshot(threadId)).threads[0]; + const settlement = (yield* store.getSettlementCandidates(threadId))[0]; + const fromProjection = ProjectionStore.threadShellFromProjection( + yield* store.getThreadProjection(threadId), + ); + yield* assertShellIndexCoversShells(); + for (const candidate of [shell, listed, awareness, settlement, fromProjection]) { + assert.deepEqual(candidate?.pendingBackgroundTasks, expected); + } + assert.equal( + shell && + projectThreadAwarenessV2({ + environmentId: EnvironmentId.make("env:delegated-wake-gap"), + project: { title: "Project" }, + thread: shell, + })?.phase, + expectedPhase, + ); + }); + + // Between child completion and parent wake run creation, completion stays held. + yield* assertPending(expectedPending, "running"); + + // Verify the active shell index and shell subagent reads use the partial pending-delivery index. + const sql = yield* SqlClient.SqlClient; + const { statements, tracer } = traceSqlStatements(); + yield* store.listActiveShellIndex().pipe(Effect.withTracer(tracer)); + yield* store.getThreadShell(threadId).pipe(Effect.withTracer(tracer)); + const subagentQueries = statements.filter((query) => + query.includes("orchestration_v2_projection_subagents_pending_delivery_idx"), + ); + assert.isAtLeast(subagentQueries.length, 2); + for (const query of subagentQueries) { + const plan = (yield* sql.unsafe<{ readonly detail: string }>( + `EXPLAIN QUERY PLAN ${query}`, + )).map((row) => row.detail); + assert.isTrue( + plan.some((detail) => + detail.includes("orchestration_v2_projection_subagents_pending_delivery_idx"), + ), + plan.join("\n"), + ); + } + + // Provider-native subagents, stopped cohorts, and rolled-back runs are excluded in SQL. + const stoppedRunId = RunId.make("run:delegated-wake-gap:stopped"); + const rolledBackRunId = RunId.make("run:delegated-wake-gap:rolled-back"); + yield* store.apply({ + id: EventId.make("event:delegated-wake-gap:run-stopped"), + type: "run.created", + threadId, + runId: stoppedRunId, + driver, + providerInstanceId, + occurredAt: completedAt, + payload: { + ...run, + id: stoppedRunId, + ordinal: 2, + delegatedCompletion: { disposition: "stopped", nextGeneration: 1, delivery: null }, + }, + }); + yield* store.apply({ + id: EventId.make("event:delegated-wake-gap:run-rolled-back"), + type: "run.created", + threadId, + runId: rolledBackRunId, + driver, + providerInstanceId, + occurredAt: completedAt, + payload: { + ...run, + id: rolledBackRunId, + ordinal: 3, + status: "rolled_back", + delegatedCompletion: undefined, + }, + }); + for (const ignored of [ + { + id: NodeId.make("node:delegated-wake-gap:native"), + origin: "provider_native" as const, + runId, + }, + { + id: NodeId.make("node:delegated-wake-gap:stopped-sub"), + origin: "app_owned" as const, + runId: stoppedRunId, + }, + { + id: NodeId.make("node:delegated-wake-gap:rolled-back-sub"), + origin: "app_owned" as const, + runId: rolledBackRunId, + }, + ]) { + yield* store.apply({ + id: EventId.make(`event:delegated-wake-gap:${ignored.id}`), + type: "subagent.updated", + threadId, + runId: ignored.runId, + nodeId: ignored.id, + driver, + providerInstanceId, + occurredAt: childFinishedAt, + payload: { ...subagent, ...ignored, childThreadId: null }, + }); + } + yield* assertPending(expectedPending, "running"); + + // Once the wake run itself completes (before finalize marks the task delivered), the + // claimed task stops holding so the shell does not flash waiting or delay notifications. + const wakeRunId = RunId.make("run:delegated-wake-gap:5"); + const wakeMessageId = MessageId.make("message:delegated-wake-gap:5"); + yield* store.apply({ + id: EventId.make("event:delegated-wake-gap:wake-message"), + type: "message.updated", + threadId, + runId: wakeRunId, + driver, + providerInstanceId, + occurredAt: deliveredAt, + payload: { + id: wakeMessageId, + threadId, + runId: wakeRunId, + nodeId: null, + role: "user", + createdBy: "agent", + creationSource: "server", + text: "Delegated task finished.", + attachments: [], + streaming: false, + delegatedCompletion: { parentRunId: runId, generation: 1, taskIds: [subagentId] }, + createdAt: deliveredAt, + updatedAt: deliveredAt, + }, + }); + yield* store.apply({ + id: EventId.make("event:delegated-wake-gap:wake-run-completed"), + type: "run.created", + threadId, + runId: wakeRunId, + driver, + providerInstanceId, + occurredAt: deliveredAt, + payload: { + ...run, + id: wakeRunId, + ordinal: 5, + userMessageId: wakeMessageId, + status: "completed", + requestedAt: deliveredAt, + startedAt: deliveredAt, + completedAt: deliveredAt, + delegatedCompletion: undefined, + }, + }); + yield* assertPending([], "completed"); + + // A pending sibling result keeps holding across that completed wake run until finalize + // reserves the next wake. + const siblingId = NodeId.make("node:delegated-wake-gap:sibling"); + const siblingChildThreadId = ThreadId.make("thread:delegated-wake-gap:child-2"); + yield* store.apply({ + id: EventId.make("event:delegated-wake-gap:sibling-pending"), + type: "subagent.updated", + threadId, + runId, + nodeId: siblingId, + driver, + providerInstanceId, + occurredAt: deliveredAt, + payload: { + ...subagent, + id: siblingId, + title: "Second audit", + childThreadId: siblingChildThreadId, + completionDelivery: { state: "pending", observedByRunId: null }, + }, + }); + yield* assertPending( + [ + { + taskId: siblingId, + description: "Second audit", + kind: "subagent" as const, + childThreadId: siblingChildThreadId, + }, + ], + "running", + ); + + // Once delivered, the thread is free to complete. + yield* store.apply({ + id: EventId.make("event:delegated-wake-gap:sibling-delivered"), + type: "subagent.updated", + threadId, + runId, + nodeId: siblingId, + driver, + providerInstanceId, + occurredAt: deliveredAt, + payload: { + ...subagent, + id: siblingId, + title: "Second audit", + childThreadId: siblingChildThreadId, + completionDelivery: { state: "delivered", observedByRunId: null }, + updatedAt: deliveredAt, + }, + }); + yield* assertPending([], "completed"); + }), + ); }); diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index e930fa67e3836..41dd807489b1d 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -1921,6 +1921,7 @@ export function threadShellFromProjection( latestRun, providerThreads: projection.providerThreads, turnItems: projection.turnItems, + subagents: projection.thread.archivedAt === null ? projection.subagents : [], activeProviderThreadId: projection.thread.activeProviderThreadId, runs, pullRequests: projection.thread.pullRequests, @@ -8731,6 +8732,45 @@ export const layer: Layer.Layer = } `; + const selectShellPendingSubagentRows = (threadIds?: ReadonlyArray) => + sql` + SELECT s.thread_id, s.payload_json + FROM orchestration_v2_projection_subagents s + INDEXED BY orchestration_v2_projection_subagents_pending_delivery_idx + LEFT JOIN orchestration_v2_projection_runs r + ON r.run_id = s.run_id + WHERE s.origin = 'app_owned' + AND s.status IN ('completed', 'failed', 'cancelled', 'interrupted') + AND s.completion_delivery_state IN ('pending', 'claimed') + AND (s.run_id IS NULL OR r.run_id IS NULL OR ( + r.status <> 'rolled_back' + AND CASE WHEN json_valid(r.payload_json) + THEN COALESCE(json_extract(r.payload_json, '$.delegatedCompletion.disposition'), 'open') + ELSE 'open' END = 'open' + )) + AND NOT ( + s.completion_delivery_state = 'claimed' + AND r.run_id IS NOT NULL + AND json_valid(r.payload_json) + AND EXISTS ( + SELECT 1 + FROM json_each(r.payload_json, '$.delegatedCompletion.delivery.taskIds') delivered_task + WHERE delivered_task.value = s.subagent_id + ) + AND EXISTS ( + SELECT 1 + FROM orchestration_v2_projection_messages delivery_msg + JOIN orchestration_v2_projection_runs wake + ON wake.run_id = delivery_msg.run_id + WHERE delivery_msg.message_id = json_extract(r.payload_json, '$.delegatedCompletion.delivery.messageId') + AND json_valid(wake.payload_json) + AND json_extract(wake.payload_json, '$.userMessageId') = delivery_msg.message_id + AND wake.status NOT IN ('queued', 'cancelled') + ) + ) + ${threadIds === undefined ? sql`` : sql`AND s.thread_id IN (SELECT value FROM json_each(${encodeIdList(threadIds)}))`} + `; + const runMapsByThreadId = (input: { readonly runRows: ReadonlyArray; readonly itemCountRows: ReadonlyArray; @@ -8774,6 +8814,7 @@ export const layer: Layer.Layer = )(function* (input: { readonly providerThreadRows: ReadonlyArray; readonly pendingTurnItemRows: ReadonlyArray; + readonly pendingSubagentRows: ReadonlyArray; }) { const providerThreadsByThreadId = new Map< ThreadId, @@ -8807,7 +8848,19 @@ export const layer: Layer.Layer = pendingTurnItemsByThreadId.set(threadId, existing); } - return { providerThreadsByThreadId, pendingTurnItemsByThreadId }; + const pendingSubagentsByThreadId = new Map< + ThreadId, + Array + >(); + for (const row of input.pendingSubagentRows) { + const subagent = yield* decodeSubagentPayload(row.payload_json); + const threadId = ThreadId.make(row.thread_id); + const existing = pendingSubagentsByThreadId.get(threadId) ?? []; + existing.push(subagent); + pendingSubagentsByThreadId.set(threadId, existing); + } + + return { providerThreadsByThreadId, pendingTurnItemsByThreadId, pendingSubagentsByThreadId }; }); const getSettlementCandidates: ProjectionStoreV2Shape["getSettlementCandidates"] = (threadId) => @@ -8890,11 +8943,15 @@ export const layer: Layer.Layer = `; if (rows.length === 0) return []; const threadIds = rows.map((row) => ThreadId.make(row.thread_id)); - const { providerThreadsByThreadId, pendingTurnItemsByThreadId } = - yield* pendingBackgroundDataByThreadId({ - providerThreadRows: yield* selectShellProviderThreadRows(threadIds), - pendingTurnItemRows: yield* selectShellPendingTurnItemRows(threadIds), - }); + const { + providerThreadsByThreadId, + pendingTurnItemsByThreadId, + pendingSubagentsByThreadId, + } = yield* pendingBackgroundDataByThreadId({ + providerThreadRows: yield* selectShellProviderThreadRows(threadIds), + pendingTurnItemRows: yield* selectShellPendingTurnItemRows(threadIds), + pendingSubagentRows: yield* selectShellPendingSubagentRows(threadIds), + }); return yield* Effect.forEach(rows, (row) => Effect.gen(function* () { const thread = yield* decodeThreadPayload(row.payload_json); @@ -8941,6 +8998,10 @@ export const layer: Layer.Layer = : { id: latestRunId, ordinal: 0, status }, providerThreads: providerThreadsByThreadId.get(thread.id) ?? [], turnItems: pendingTurnItemsByThreadId.get(thread.id) ?? [], + subagents: + thread.archivedAt === null + ? (pendingSubagentsByThreadId.get(thread.id) ?? []) + : [], activeProviderThreadId: thread.activeProviderThreadId, hasActiveRun: false, pullRequests: thread.pullRequests, @@ -9040,6 +9101,10 @@ export const layer: Layer.Layer = ThreadId, ReadonlyArray >; + readonly pendingSubagentsByThreadId: ReadonlyMap< + ThreadId, + ReadonlyArray + >; }) { const { row, @@ -9048,6 +9113,7 @@ export const layer: Layer.Layer = shellItemCountsByThreadId, providerThreadsByThreadId, pendingTurnItemsByThreadId, + pendingSubagentsByThreadId, } = input; const thread = yield* decodeThreadPayload(row.payload_json); const latestUserAuthoredMessageAt = @@ -9153,6 +9219,8 @@ export const layer: Layer.Layer = }, providerThreads: providerThreadsByThreadId.get(thread.id) ?? [], turnItems: pendingTurnItemsByThreadId.get(thread.id) ?? [], + subagents: + thread.archivedAt === null ? (pendingSubagentsByThreadId.get(thread.id) ?? []) : [], activeProviderThreadId: thread.activeProviderThreadId, hasActiveRun: row.active_run_id !== null, pullRequests: thread.pullRequests, @@ -9263,6 +9331,7 @@ export const layer: Layer.Layer = sequenceRows, providerThreadRows, pendingTurnItemRows, + pendingSubagentRows, ] = yield* Effect.all([ readForThreadIds(selectShellRunRows, forkSourceIds), readForThreadIds(selectShellRunItemCounts, forkSourceIds), @@ -9284,6 +9353,7 @@ export const layer: Layer.Layer = ), ), ), + readForThreadIds(selectShellPendingSubagentRows), ]); return { targetThreadIds, @@ -9294,6 +9364,7 @@ export const layer: Layer.Layer = sequenceRows, providerThreadRows, pendingTurnItemRows, + pendingSubagentRows, }; }); @@ -9306,14 +9377,19 @@ export const layer: Layer.Layer = sequenceRows, providerThreadRows, pendingTurnItemRows, + pendingSubagentRows, }: Effect.Success>) { const { runsByThreadId, itemCountsByThreadId } = runMapsByThreadId({ runRows, itemCountRows, }); const shellItemCountsByThreadId = shellItemCountMap(shellItemCountRows); - const { providerThreadsByThreadId, pendingTurnItemsByThreadId } = - yield* pendingBackgroundDataByThreadId({ providerThreadRows, pendingTurnItemRows }); + const { providerThreadsByThreadId, pendingTurnItemsByThreadId, pendingSubagentsByThreadId } = + yield* pendingBackgroundDataByThreadId({ + providerThreadRows, + pendingTurnItemRows, + pendingSubagentRows, + }); const states = yield* Effect.forEach(threadRows, (row) => shellThreadStateFromRow({ row, @@ -9322,6 +9398,7 @@ export const layer: Layer.Layer = shellItemCountsByThreadId, providerThreadsByThreadId, pendingTurnItemsByThreadId, + pendingSubagentsByThreadId, }), ); const statesByThreadId = new Map(states.map((state) => [state.thread.id, state])); @@ -9389,36 +9466,56 @@ export const layer: Layer.Layer = const getAgentAwarenessSnapshot = Effect.fn("ProjectionStore.getAgentAwarenessSnapshot")( function* (threadId?: ThreadId) { - const { threadRows, providerThreadRows, pendingTurnItemRows, sequenceRows } = - yield* sql.withTransaction( - Effect.gen(function* () { - const threadRows = yield* selectShellThreadRows( - threadId, - threadId === undefined ? { location: "active", listedOnly: true } : {}, - ); - const ids = threadRows.map((row) => ThreadId.make(row.thread_id)); - const providerThreadRows = - ids.length === 0 ? [] : yield* selectShellProviderThreadRows(ids); - const pendingTurnItemRows = - ids.length === 0 - ? [] - : yield* selectShellPendingTurnItemRows( - ids, - threadRows.flatMap((row) => - row.active_run_id !== null && row.active_run_status === "running" - ? [row.active_run_id] - : [], - ), - ); - const sequenceRows = yield* sql<{ readonly snapshot_sequence: number | null }>` + const { + threadRows, + providerThreadRows, + pendingTurnItemRows, + pendingSubagentRows, + sequenceRows, + } = yield* sql.withTransaction( + Effect.gen(function* () { + const threadRows = yield* selectShellThreadRows( + threadId, + threadId === undefined ? { location: "active", listedOnly: true } : {}, + ); + const ids = threadRows.map((row) => ThreadId.make(row.thread_id)); + const providerThreadRows = + ids.length === 0 ? [] : yield* selectShellProviderThreadRows(ids); + const pendingTurnItemRows = + ids.length === 0 + ? [] + : yield* selectShellPendingTurnItemRows( + ids, + threadRows.flatMap((row) => + row.active_run_id !== null && row.active_run_status === "running" + ? [row.active_run_id] + : [], + ), + ); + const pendingSubagentRows = + ids.length === 0 ? [] : yield* selectShellPendingSubagentRows(ids); + const sequenceRows = yield* sql<{ readonly snapshot_sequence: number | null }>` SELECT MAX(sequence) AS snapshot_sequence FROM orchestration_events WHERE application_event_version = 2 AND aggregate_kind = 'thread' `; - return { threadRows, providerThreadRows, pendingTurnItemRows, sequenceRows }; - }), - ); - const { providerThreadsByThreadId, pendingTurnItemsByThreadId } = - yield* pendingBackgroundDataByThreadId({ providerThreadRows, pendingTurnItemRows }); + return { + threadRows, + providerThreadRows, + pendingTurnItemRows, + pendingSubagentRows, + sequenceRows, + }; + }), + ); + const { + providerThreadsByThreadId, + pendingTurnItemsByThreadId, + pendingSubagentsByThreadId, + } = yield* pendingBackgroundDataByThreadId({ + providerThreadRows, + pendingTurnItemRows, + pendingSubagentRows, + }); const threads = yield* Effect.forEach(threadRows, (row) => shellThreadStateFromRow({ row, @@ -9428,6 +9525,7 @@ export const layer: Layer.Layer = shellItemCountsByThreadId: new Map(), providerThreadsByThreadId, pendingTurnItemsByThreadId, + pendingSubagentsByThreadId, }).pipe( Effect.map((state): AgentAwarenessThread => ({ id: state.thread.id, @@ -9547,6 +9645,14 @@ export const layer: Layer.Layer = SELECT link_request.thread_id FROM orchestration_v2_projection_turn_items link_request WHERE link_request.type = 'link_request' AND link_request.status = 'waiting' ) + OR t.thread_id IN ( + SELECT subagent.thread_id + FROM orchestration_v2_projection_subagents subagent + INDEXED BY orchestration_v2_projection_subagents_pending_delivery_idx + WHERE subagent.origin = 'app_owned' + AND subagent.status IN ('completed', 'failed', 'cancelled', 'interrupted') + AND subagent.completion_delivery_state IN ('pending', 'claimed') + ) OR t.thread_id IN ( SELECT provider_thread.thread_id FROM orchestration_v2_projection_provider_threads provider_thread @@ -9782,6 +9888,7 @@ export const layer: Layer.Layer = shellItemCountRows, providerThreadRows, pendingTurnItemRows, + pendingSubagentRows, ] = yield* Effect.all([ forkSourceIds.length === 0 ? Effect.succeed([] as ReadonlyArray) @@ -9799,14 +9906,22 @@ export const layer: Layer.Layer = : [], ), ), + selectShellPendingSubagentRows(threadIds), ]); const { runsByThreadId, itemCountsByThreadId } = runMapsByThreadId({ runRows, itemCountRows, }); const shellItemCountsByThreadId = shellItemCountMap(shellItemCountRows); - const { providerThreadsByThreadId, pendingTurnItemsByThreadId } = - yield* pendingBackgroundDataByThreadId({ providerThreadRows, pendingTurnItemRows }); + const { + providerThreadsByThreadId, + pendingTurnItemsByThreadId, + pendingSubagentsByThreadId, + } = yield* pendingBackgroundDataByThreadId({ + providerThreadRows, + pendingTurnItemRows, + pendingSubagentRows, + }); const states = yield* Effect.forEach([...rowsByThreadId.values()], (row) => shellThreadStateFromRow({ @@ -9816,6 +9931,7 @@ export const layer: Layer.Layer = shellItemCountsByThreadId, providerThreadsByThreadId, pendingTurnItemsByThreadId, + pendingSubagentsByThreadId, }), ); const statesByThreadId = new Map(states.map((state) => [state.thread.id, state])); diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.ts index 2b767af21f52f..488671e2f93ed 100644 --- a/apps/server/src/persistence/Migrations.ts +++ b/apps/server/src/persistence/Migrations.ts @@ -115,6 +115,7 @@ import Migration0104 from "./Migrations/104_ProjectionProjectsTrackedFolders.ts" import Migration0105 from "./Migrations/105_TaskFolders.ts"; import Migration0106 from "./Migrations/106_WorktreePathKeyIndex.ts"; import Migration0107 from "./Migrations/107_DeferredSlashCommandIndex.ts"; +import Migration0108 from "./Migrations/108_PendingSubagentDeliveryIndex.ts"; const migrationEntries = [ [1, "OrchestrationEvents", Migration0001], @@ -225,6 +226,7 @@ const migrationEntries = [ [105, "TaskFolders", Migration0105], [106, "WorktreePathKeyIndex", Migration0106], [107, "DeferredSlashCommandIndex", Migration0107], + [108, "PendingSubagentDeliveryIndex", Migration0108], ] as const; export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const); diff --git a/apps/server/src/persistence/Migrations/108_PendingSubagentDeliveryIndex.ts b/apps/server/src/persistence/Migrations/108_PendingSubagentDeliveryIndex.ts new file mode 100644 index 0000000000000..a26ae4e1cf190 --- /dev/null +++ b/apps/server/src/persistence/Migrations/108_PendingSubagentDeliveryIndex.ts @@ -0,0 +1,16 @@ +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/sql/SqlClient"; + +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + // Covers ProjectionStore.listActiveShellIndex and selectShellPendingSubagentRows without + // scanning settled subagent history. + yield* sql` + CREATE INDEX IF NOT EXISTS orchestration_v2_projection_subagents_pending_delivery_idx + ON orchestration_v2_projection_subagents(thread_id) + WHERE origin = 'app_owned' + AND status IN ('completed', 'failed', 'cancelled', 'interrupted') + AND completion_delivery_state IN ('pending', 'claimed') + `; +}); diff --git a/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts b/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts index e7ec467f3ec0a..e42c1275599b1 100644 --- a/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts +++ b/apps/server/src/persistence/reconcileV2PreviewMigration.test.ts @@ -87,6 +87,7 @@ describe("V2 preview upgrade", () => { [105, "TaskFolders"], [106, "WorktreePathKeyIndex"], [107, "DeferredSlashCommandIndex"], + [108, "PendingSubagentDeliveryIndex"], ]); assert.deepStrictEqual(yield* runMigrations(), []); assert.deepStrictEqual(yield* sql`SELECT * FROM orchestration_v2_legacy_imports`, imports); @@ -217,6 +218,7 @@ describe("V2 preview upgrade", () => { [105, "TaskFolders"], [106, "WorktreePathKeyIndex"], [107, "DeferredSlashCommandIndex"], + [108, "PendingSubagentDeliveryIndex"], ]); }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))), ); diff --git a/apps/web/src/components/ChatView.logic.ts b/apps/web/src/components/ChatView.logic.ts index 160aed0a7093e..39d0f23d7b085 100644 --- a/apps/web/src/components/ChatView.logic.ts +++ b/apps/web/src/components/ChatView.logic.ts @@ -1664,6 +1664,7 @@ export function deriveThreadPendingBackgroundTasks(projection: ThreadStructure | turnItems: projection.turnItems.filter( (item) => item.runId === null || !liveRunIds.has(item.runId), ), + subagents: projection.thread.archivedAt === null ? projection.subagents : [], activeProviderThreadId: projection.thread.activeProviderThreadId, hasActiveRun: false, runs: projection.runs, diff --git a/packages/client-runtime/src/state/threadExecution.ts b/packages/client-runtime/src/state/threadExecution.ts index 7e5ad55dc53b2..e8b12309ff2cc 100644 --- a/packages/client-runtime/src/state/threadExecution.ts +++ b/packages/client-runtime/src/state/threadExecution.ts @@ -424,6 +424,7 @@ export function deriveThreadStructureRuntime( latestRun: latestRunProjection, providerThreads: projection.providerThreads, turnItems: projection.turnItems, + subagents: projection.thread.archivedAt === null ? projection.subagents : [], activeProviderThreadId: projection.thread.activeProviderThreadId, runs: projection.runs, pullRequests: projection.thread.pullRequests, diff --git a/packages/shared/src/orchestrationV2PendingBackgroundWork.test.ts b/packages/shared/src/orchestrationV2PendingBackgroundWork.test.ts index 5b8f67e1fae1a..bdc086b72a578 100644 --- a/packages/shared/src/orchestrationV2PendingBackgroundWork.test.ts +++ b/packages/shared/src/orchestrationV2PendingBackgroundWork.test.ts @@ -3,6 +3,7 @@ import { ProviderInstanceId, ProviderThreadId } from "@t3tools/contracts"; import { backgroundWorkHoldsCompletion, derivePendingBackgroundWork, + hasPendingBackgroundSubagent, monitorHoldsWakeCompletion, } from "./orchestrationV2PendingBackgroundWork.ts"; @@ -310,6 +311,309 @@ describe("derivePendingBackgroundWork", () => { }, ]); }); + + it("holds completion for finished app-owned subagents awaiting wake delivery without granting native caller access", () => { + const parentInstance = ProviderInstanceId.make("antigravity"); + const tasks = derivePendingBackgroundWork({ + latestRun: { id: "run-4" as never, ordinal: 4, status: "completed" }, + runs: [ + { + id: "run-4" as never, + ordinal: 4, + status: "completed", + userMessageId: "msg-4" as never, + delegatedCompletion: { + disposition: "open", + nextGeneration: 2, + delivery: { + generation: 1, + messageId: "msg-wake-pending" as never, + taskIds: ["node:claimed" as never], + }, + }, + }, + { + id: "run-with-started-wake" as never, + ordinal: 3, + status: "completed", + userMessageId: "msg-3" as never, + delegatedCompletion: { + disposition: "open", + nextGeneration: 2, + delivery: { + generation: 1, + messageId: "msg-wake-started" as never, + taskIds: ["node:claimed-started" as never], + }, + }, + }, + { + id: "run-wake-started" as never, + ordinal: 5, + status: "completed", + userMessageId: "msg-wake-started" as never, + }, + { + id: "run-with-cancelled-wake" as never, + ordinal: 2, + status: "completed", + userMessageId: "msg-2" as never, + delegatedCompletion: { + disposition: "open", + nextGeneration: 2, + delivery: { + generation: 1, + messageId: "msg-wake-cancelled" as never, + taskIds: ["node:claimed-cancelled" as never], + }, + }, + }, + { + id: "run-wake-cancelled" as never, + ordinal: 6, + status: "cancelled", + userMessageId: "msg-wake-cancelled" as never, + }, + { + id: "run-with-queued-wake" as never, + ordinal: 2, + status: "completed", + userMessageId: "msg-2-queued" as never, + delegatedCompletion: { + disposition: "open", + nextGeneration: 2, + delivery: { + generation: 1, + messageId: "msg-wake-queued" as never, + taskIds: ["node:claimed-queued" as never], + }, + }, + }, + { + id: "run-wake-queued" as never, + ordinal: 7, + status: "queued", + userMessageId: "msg-wake-queued" as never, + }, + { + id: "run-stopped" as never, + ordinal: 1, + status: "completed", + delegatedCompletion: { disposition: "stopped", nextGeneration: 1, delivery: null }, + }, + { id: "run-rolled-back" as never, ordinal: 0, status: "rolled_back" }, + ], + providerThreads: [], + turnItems: [ + { + id: "item-completed" as never, + type: "subagent", + status: "completed", + title: "Review PRs", + runId: "run-4", + childThreadId: "thread:child-1" as never, + }, + { + id: "item-remote-running" as never, + type: "subagent", + status: "running", + title: "Remote worker", + runId: "run-4", + childThreadId: null, + }, + { + id: "item-shared-running" as never, + type: "subagent", + status: "running", + title: "Follow-up task", + runId: "run-4", + childThreadId: "thread:child-shared" as never, + }, + ], + subagents: [ + { + id: "node:claimed" as never, + origin: "app_owned", + status: "completed", + title: "Review PRs", + prompt: "Audit PRs", + runId: "run-4" as never, + childThreadId: "thread:child-1" as never, + completionDelivery: { state: "claimed", observedByRunId: null }, + }, + // Once the dedicated wake run starts/completes, claimed stops holding before finalize lands. + { + id: "node:claimed-started" as never, + origin: "app_owned", + status: "completed", + title: "Already woken", + prompt: "Already woken", + runId: "run-with-started-wake" as never, + childThreadId: "thread:child-woken" as never, + completionDelivery: { state: "claimed", observedByRunId: null }, + }, + // A cancelled wake run never ran; the claimed delivery still owes a successor wake. + { + id: "node:claimed-cancelled" as never, + origin: "app_owned", + status: "completed", + title: "Cancelled wake", + prompt: "Cancelled wake", + runId: "run-with-cancelled-wake" as never, + childThreadId: "thread:child-cancelled-wake" as never, + completionDelivery: { state: "claimed", observedByRunId: null }, + }, + // A wake run that is still queued has not started yet, so the claimed delivery keeps holding. + { + id: "node:claimed-queued" as never, + origin: "app_owned", + status: "completed", + title: "Queued wake", + prompt: "Queued wake", + runId: "run-with-queued-wake" as never, + childThreadId: "thread:child-queued-wake" as never, + completionDelivery: { state: "claimed", observedByRunId: null }, + }, + // Pending sibling results keep holding even after another wake run completed. + { + id: "node:pending-failed" as never, + origin: "app_owned", + status: "failed", + title: null, + prompt: "Run flaky check", + runId: "run-with-started-wake" as never, + childThreadId: null, + completionDelivery: { state: "pending", observedByRunId: null }, + }, + // Active remote task is already represented by its running turn item; must not duplicate. + { + id: "node:remote-running" as never, + origin: "app_owned", + status: "running", + title: "Remote worker", + prompt: "Remote work", + runId: "run-4" as never, + childThreadId: null, + completionDelivery: { state: "pending", observedByRunId: null }, + }, + // Same child thread already has an active follow-up turn item; deduped by childThreadId. + { + id: "node:shared-claimed" as never, + origin: "app_owned", + status: "completed", + title: "Earlier task", + prompt: "Earlier work", + runId: "run-4" as never, + childThreadId: "thread:child-shared" as never, + completionDelivery: { state: "claimed", observedByRunId: null }, + }, + // Terminal delivery states, native/idle tasks, stopped cohorts, and rolled-back runs do not hold. + { + id: "node:delivered" as never, + origin: "app_owned", + status: "completed", + title: "Delivered", + prompt: "Delivered", + runId: "run-4" as never, + childThreadId: "thread:child-delivered" as never, + completionDelivery: { state: "delivered", observedByRunId: null }, + }, + { + id: "node:acknowledged" as never, + origin: "app_owned", + status: "completed", + title: "Acked", + prompt: "Acked", + runId: "run-4" as never, + childThreadId: "thread:child-acked" as never, + completionDelivery: { state: "acknowledged", observedByRunId: "run-4" as never }, + }, + { + id: "node:disposed" as never, + origin: "app_owned", + status: "completed", + title: "Disposed", + prompt: "Disposed", + runId: "run-4" as never, + childThreadId: "thread:child-disposed" as never, + completionDelivery: { state: "disposed", observedByRunId: null }, + }, + { + id: "node:untracked" as never, + origin: "app_owned", + status: "completed", + title: "Wait task", + prompt: "Wait task", + runId: "run-4" as never, + childThreadId: "thread:child-wait" as never, + }, + { + id: "node:native" as never, + origin: "provider_native", + status: "completed", + title: "Native", + prompt: "Native", + runId: "run-4" as never, + childThreadId: null, + completionDelivery: { state: "claimed", observedByRunId: null }, + }, + { + id: "node:stopped-cohort" as never, + origin: "app_owned", + status: "completed", + title: "Stopped", + prompt: "Stopped", + runId: "run-stopped" as never, + childThreadId: "thread:child-stopped" as never, + completionDelivery: { state: "claimed", observedByRunId: null }, + }, + { + id: "node:rolled-back" as never, + origin: "app_owned", + status: "completed", + title: "Rolled back", + prompt: "Rolled back", + runId: "run-rolled-back" as never, + childThreadId: "thread:child-rolled-back" as never, + completionDelivery: { state: "claimed", observedByRunId: null }, + }, + ], + }); + expect(tasks).toEqual([ + { taskId: "item-remote-running", description: "Remote worker", kind: "subagent" }, + { + taskId: "item-shared-running", + description: "Follow-up task", + kind: "subagent", + childThreadId: "thread:child-shared", + }, + { + taskId: "node:claimed", + description: "Review PRs", + kind: "subagent", + childThreadId: "thread:child-1", + }, + { + taskId: "node:claimed-cancelled", + description: "Cancelled wake", + kind: "subagent", + childThreadId: "thread:child-cancelled-wake", + }, + { + taskId: "node:claimed-queued", + description: "Queued wake", + kind: "subagent", + childThreadId: "thread:child-queued-wake", + }, + { + taskId: "node:pending-failed", + description: "Run flaky check", + kind: "subagent", + }, + ]); + expect(backgroundWorkHoldsCompletion(tasks)).toBe(true); + expect(hasPendingBackgroundSubagent(tasks, parentInstance)).toBe(false); + }); }); describe("derivePendingBackgroundWork kinds", () => { diff --git a/packages/shared/src/orchestrationV2PendingBackgroundWork.ts b/packages/shared/src/orchestrationV2PendingBackgroundWork.ts index cc8513fb64e60..8a9d301fd25e1 100644 --- a/packages/shared/src/orchestrationV2PendingBackgroundWork.ts +++ b/packages/shared/src/orchestrationV2PendingBackgroundWork.ts @@ -2,6 +2,7 @@ import type { OrchestrationV2PendingBackgroundTask, OrchestrationV2ProviderThread, OrchestrationV2Run, + OrchestrationV2Subagent, OrchestrationV2ThreadShell, OrchestrationV2TurnItem, ThreadId, @@ -140,7 +141,15 @@ export function monitorHoldsWakeCompletion( ); } -type PendingBackgroundWorkRun = Pick; +type PendingBackgroundWorkRun = Pick & { + readonly userMessageId?: OrchestrationV2Run["userMessageId"] | undefined; + readonly delegatedCompletion?: OrchestrationV2Run["delegatedCompletion"] | undefined; +}; + +type PendingBackgroundWorkSubagent = Pick< + OrchestrationV2Subagent, + "id" | "origin" | "status" | "title" | "prompt" | "runId" | "childThreadId" | "completionDelivery" +>; type PendingBackgroundWorkPullRequest = Pick< ThreadPullRequestLink, @@ -262,6 +271,7 @@ export function derivePendingBackgroundWork(input: { readonly latestRun: PendingBackgroundWorkRun | null | undefined; readonly providerThreads: ReadonlyArray; readonly turnItems: ReadonlyArray; + readonly subagents?: ReadonlyArray | undefined; readonly activeProviderThreadId?: string | null; readonly hasActiveRun?: boolean; /** Excludes rolled-back runs; optional only when the caller already filtered them, as SQL shell reads do. */ @@ -317,6 +327,67 @@ export function derivePendingBackgroundWork(input: { byTaskId.set(taskId, pendingTaskFromTurnItem(taskId, item)); } + // Publishing a delegated child's terminal result precedes scheduling its parent's wake run. + // Keep holding completion across that gap until the wake run actually starts (for claimed + // tasks) or its delivery is finalized/disposed. + if (input.subagents !== undefined && input.subagents.length > 0) { + const runsById = new Map(); + const startedRunMessageIds = new Set(); + for (const run of input.runs ?? []) { + runsById.set(String(run.id), run); + if ( + run.userMessageId !== undefined && + run.status !== "queued" && + run.status !== "cancelled" + ) { + startedRunMessageIds.add(String(run.userMessageId)); + } + } + for (const subagent of input.subagents) { + if ( + subagent.origin !== "app_owned" || + isOrchestrationV2WorkActive(subagent.status) || + subagent.status === "idle" + ) { + continue; + } + const deliveryState = subagent.completionDelivery?.state; + if (deliveryState !== "pending" && deliveryState !== "claimed") { + continue; + } + const ownerRun = subagent.runId === null ? undefined : runsById.get(String(subagent.runId)); + if ( + ownerRun !== undefined && + (ownerRun.status === "rolled_back" || + (ownerRun.delegatedCompletion !== undefined && + ownerRun.delegatedCompletion.disposition !== "open")) + ) { + continue; + } + const delivery = ownerRun?.delegatedCompletion?.delivery; + if ( + deliveryState === "claimed" && + delivery != null && + delivery.taskIds.includes(subagent.id) && + startedRunMessageIds.has(String(delivery.messageId)) + ) { + continue; + } + const taskId = String(subagent.id); + if (byTaskId.has(taskId)) { + continue; + } + const description = subagent.title?.trim() || subagent.prompt.trim() || undefined; + byTaskId.set(taskId, { + taskId, + ...(description === undefined ? {} : { description }), + // Omit providerInstanceId so hasPendingBackgroundSubagent never grants live-caller access. + kind: "subagent", + ...(subagent.childThreadId === null ? {} : { childThreadId: subagent.childThreadId }), + }); + } + } + for (const task of pullRequestWatchTasks(input.pullRequests)) byTaskId.set(task.taskId, task); // Follow-up tasks can share a child thread; the pending list counts agents, not messages.