TypeScript
fix(server): background subagents keep T3 tools after the parent turn ends (#19751)
maria11ce406d2cf1
diff --git a/apps/server/src/mcp/McpToolAccess.test.ts b/apps/server/src/mcp/McpToolAccess.test.tsindex 1613cc1112b..46371724119 100644--- a/apps/server/src/mcp/McpToolAccess.test.ts+++ b/apps/server/src/mcp/McpToolAccess.test.ts@@ -23,6 +23,17 @@ const supervisedThreadId = ThreadId.make("thread:supervised");const planThreadId = ThreadId.make("thread:plan");const fullAccessThreadId = ThreadId.make("thread:full-access");const endedThreadId = ThreadId.make("thread:ended");+const backgroundThreadId = ThreadId.make("thread:background");+const oldProviderThreadId = ThreadId.make("thread:old-provider-background");+const archivedThreadId = ThreadId.make("thread:archived-background");+const unknownOwnerThreadId = ThreadId.make("thread:unknown-background-owner");++const backgroundShell = (threadId: ThreadId, providerInstanceId: ProviderInstanceId) => ({+ ...liveThreadShell(threadId, { activeRunId: null }),+ pendingBackgroundTasks: [+ { taskId: "task:background", kind: "subagent" as const, providerInstanceId },+ ],+});const shells = new Map([[supervisedThreadId, liveThreadShell(supervisedThreadId, { runtimeMode: "approval-required" })],@@ -32,6 +43,22 @@ const shells = new Map([],[fullAccessThreadId, liveThreadShell(fullAccessThreadId)],[endedThreadId, liveThreadShell(endedThreadId, { activeRunId: null })],+ [backgroundThreadId, backgroundShell(backgroundThreadId, ProviderInstanceId.make("codex"))],+ [oldProviderThreadId, backgroundShell(oldProviderThreadId, ProviderInstanceId.make("claude"))],+ [+ archivedThreadId,+ {+ ...backgroundShell(archivedThreadId, ProviderInstanceId.make("codex")),+ archivedAt: liveThreadShell(archivedThreadId).updatedAt,+ },+ ],+ [+ unknownOwnerThreadId,+ {+ ...liveThreadShell(unknownOwnerThreadId, { activeRunId: null }),+ pendingBackgroundTasks: [{ taskId: "task:unknown", kind: "subagent" as const }],+ },+ ],]);const threadCaller = (threadId: ThreadId): McpInvocationContext.McpInvocationScope => ({@@ -189,6 +216,15 @@ const supervised = threadCaller(supervisedThreadId);const plan = threadCaller(planThreadId);const fullAccess = threadCaller(fullAccessThreadId);const ended = threadCaller(endedThreadId);+// Its turn ended, but a background subagent it started still runs.+const background = threadCaller(backgroundThreadId);+const oldProviderBackground = threadCaller(oldProviderThreadId);+const archivedBackground = threadCaller(archivedThreadId);+const unknownOwnerBackground = threadCaller(unknownOwnerThreadId);+const mismatchedProvider = {+ ...background,+ thread: { ...background.thread!, providerInstanceId: ProviderInstanceId.make("claude") },+};const supervisedClient = clientCaller("approval-required");const fullAccessClient = clientCaller("full-access");const readOnlyClient = clientCaller("read-only");@@ -208,10 +244,17 @@ it.effect.each([["reads_as_caller", fullAccessClient, {}, "thread_credential_required"],["acts_as_caller", supervised, {}, "ran"],["acts_as_caller", ended, {}, "parent_not_active"],+ ["acts_as_caller", background, {}, "ran"],+ ["acts_as_caller", oldProviderBackground, {}, "parent_not_active"],+ ["acts_as_caller", mismatchedProvider, {}, "parent_not_active"],+ ["acts_as_caller", archivedBackground, {}, "parent_not_active"],+ ["acts_as_caller", unknownOwnerBackground, {}, "parent_not_active"],["acts_as_caller", fullAccessClient, {}, "thread_credential_required"],["writes", supervised, {}, "ran"],["writes", ended, {}, "parent_not_active"],+ ["writes", background, {}, "ran"],+ ["writes", oldProviderBackground, {}, "parent_not_active"],["writes", supervisedClient, {}, "ran"],["writes", previewOnly, {}, "capability_denied"],["writes_environment", previewOnly, {}, "capability_denied"],diff --git a/apps/server/src/mcp/OrchestratorMcpService.activity.test.ts b/apps/server/src/mcp/OrchestratorMcpService.activity.test.tsindex 72497c5825f..12e7f7fd0d4 100644--- a/apps/server/src/mcp/OrchestratorMcpService.activity.test.ts+++ b/apps/server/src/mcp/OrchestratorMcpService.activity.test.ts@@ -27,6 +27,7 @@ import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";import type * as McpInvocationContext from "./McpInvocationContext.ts";import * as OrchestratorMcpService from "./OrchestratorMcpService.ts";+import { liveThreadShell } from "./McpToolAccess.testkit.ts";const layerOrchestratorService = OrchestratorMcpService.layer.pipe(Layer.provide(Layer.mock(ThreadLaunchService.ThreadLaunchService)({})),@@ -363,6 +364,7 @@ it("taskStatus returns task.providerInstanceId rather than the driver kind", asy});it("readThread and sendToThread reach threads in other projects", async () => {+ let parentShell: OrchestrationV2ThreadShell | null = null;let parentRuns: ReadonlyArray<unknown> = [makeRun({ id: RunId.make("run-parent-live"), ordinal: 1, status: "running" }),];@@ -435,7 +437,9 @@ it("readThread and sendToThread reach threads in other projects", async () => {Effect.succeed(threadId === foreignThreadId? (foreignProjection(threadId).thread as unknown as OrchestrationV2ThreadShell)- : null,+ : threadId === parentThreadId+ ? parentShell+ : null,),getTimelinePage: (threadId) =>Effect.succeed({@@ -528,5 +532,74 @@ it("readThread and sendToThread reach threads in other projects", async () => {.deleteScheduledTask(makeScope(), { scheduledTaskId: ScheduledTaskId.make("task-foreign") }).pipe(Effect.flip);expect(staleDelete.code).toBe("parent_not_active");++ // A background item keeps only its owning instance live, even after a switch.+ const backgroundTasks = [+ {+ taskId: "background-subagent",+ kind: "subagent" as const,+ providerInstanceId: parentInstanceId,+ },+ ];+ parentShell = {+ ...liveThreadShell(parentThreadId, { activeRunId: null }),+ pendingBackgroundTasks: backgroundTasks,+ };+ const backgroundSent = yield* service.sendToThread(makeScope(), {+ threadId: foreignThreadId,+ message: "background",+ });+ expect(backgroundSent.threadId).toBe(foreignThreadId);+ const delegate = yield* service+ .delegateTask(makeScope(), { task: "requires a run" })+ .pipe(Effect.flip);+ expect(delegate.code).toBe("parent_not_active");+ const create = yield* service+ .createThreads(makeScope(), { threads: [{ prompt: "requires a run" }] })+ .pipe(Effect.flip);+ expect(create.code).toBe("parent_not_active");+ const secret = yield* service+ .requestSecret(makeScope(), { label: "Secret", reason: "requires a run" })+ .pipe(Effect.flip);+ expect(secret.code).toBe("parent_not_active");++ parentShell = { ...parentShell, providerInstanceId: customCodexInstanceId };+ const switchedScope = {+ ...makeScope(),+ thread: { ...makeScope().thread!, providerInstanceId: customCodexInstanceId },+ };+ const switched = yield* service+ .sendToThread(switchedScope, { threadId: foreignThreadId, message: "wrong owner" })+ .pipe(Effect.flip);+ expect(switched.code).toBe("parent_not_active");+ const mismatched = yield* service+ .sendToThread(makeScope(), { threadId: foreignThreadId, message: "stale provider" })+ .pipe(Effect.flip);+ expect(mismatched.code).toBe("parent_not_active");++ // A fresh active run wins over the earlier inactive projection and empty roster.+ parentShell = liveThreadShell(parentThreadId);+ const restarted = yield* service.sendToThread(makeScope(), {+ threadId: foreignThreadId,+ message: "new run",+ });+ expect(restarted.threadId).toBe(foreignThreadId);++ parentShell = {+ ...parentShell,+ activeRunId: null,+ pendingBackgroundTasks: backgroundTasks,+ archivedAt: now,+ };+ const archived = yield* service+ .sendToThread(makeScope(), { threadId: foreignThreadId, message: "archived" })+ .pipe(Effect.flip);+ expect(archived.code).toBe("parent_not_active");++ parentShell = { ...parentShell, archivedAt: null, pendingBackgroundTasks: [] };+ const stopped = yield* service+ .sendToThread(makeScope(), { threadId: foreignThreadId, message: "after stop" })+ .pipe(Effect.flip);+ expect(stopped.code).toBe("parent_not_active");}).pipe(Effect.provide(layer), Effect.runPromise);});diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.tsindex 9378251eb9e..71ab210715a 100644--- a/apps/server/src/mcp/OrchestratorMcpService.ts+++ b/apps/server/src/mcp/OrchestratorMcpService.ts@@ -50,6 +50,7 @@ import {type OrchestratorMcpThreadWaitInput,type OrchestratorMcpThreadWaitResult,type ProviderInteractionMode,+ type ProviderInstanceId,type ProviderOptionDescriptor,type ProviderOptionSelection,type RuntimeMode,@@ -200,6 +201,29 @@ function failure(code: OrchestratorMcpFailure["code"], message: string): Orchestreturn new OrchestratorMcpFailure({ code, message });}+/**+ * A caller's thread is live while it is not archived, runs on the caller's+ * provider instance, and has an active run or a background subagent that+ * instance started. A background subagent outlives its run and calls tools+ * with its thread's credential, which is revoked when the provider process+ * goes away.+ */+export const isLiveCallerShell = (+ shell: Pick<+ OrchestrationV2ThreadShell,+ "archivedAt" | "activeRunId" | "providerInstanceId" | "pendingBackgroundTasks"+ > | null,+ providerInstanceId: ProviderInstanceId | undefined,+) =>+ shell !== null &&+ shell.archivedAt === null &&+ shell.providerInstanceId === providerInstanceId &&+ (shell.activeRunId !== null ||+ (shell.pendingBackgroundTasks?.some(+ (task) => task.kind === "subagent" && task.providerInstanceId === providerInstanceId,+ ) ??+ false));+function threadManagementFailure(error: unknown): OrchestratorMcpFailure {if (!isThreadManagementError(error)) return failure("orchestration_error", errorMessage(error));switch (error._tag) {@@ -1060,13 +1084,26 @@ const make = Effect.gen(function* () {scope: McpInvocationScope,parent: Pick<OrchestrationV2ThreadProjection, "thread" | "runs">,) => {+ const notActive = failure(+ "parent_not_active",+ "The calling provider no longer owns an active thread run.",+ );const activeRun = ThreadManagementService.latestActiveRun(parent);+ if (parent.thread.archivedAt === null && activeRun === undefined) {+ // Decide from this one fresh snapshot: a run may have started since `parent` was read.+ return threadManagement.getThreadShell(parent.thread.id).pipe(+ Effect.mapError(threadManagementFailure),+ Effect.flatMap((shell) =>+ isLiveCallerShell(shell, scope.thread?.providerInstanceId)+ ? Effect.void+ : Effect.fail(notActive),+ ),+ );+ }return parent.thread.archivedAt !== null ||activeRun === undefined ||activeRun.providerInstanceId !== scope.thread?.providerInstanceId- ? Effect.fail(- failure("parent_not_active", "The calling provider no longer owns an active thread run."),- )+ ? Effect.fail(notActive): Effect.void;};diff --git a/apps/server/src/mcp/threadAccess.ts b/apps/server/src/mcp/threadAccess.tsindex 5debcc331c5..be70ecf1807 100644--- a/apps/server/src/mcp/threadAccess.ts+++ b/apps/server/src/mcp/threadAccess.ts@@ -103,22 +103,21 @@ export const assertTargetWithinLimits = ();/**- * A thread caller acts only while it owns a live run of a thread that is not- * archived, so a provider token that outlived its session cannot act. An- * OAuth client has no run; its session and ceiling are its authority.+ * A thread caller acts only while it owns a live run, or a background+ * subagent that run started, of a thread that is not archived, so a provider+ * token that outlived its session cannot act. An OAuth client has no run; its+ * session and ceiling are its authority.*/export function assertLiveCaller({ caller, scope }: Caller) {if (caller === undefined) return Effect.void;- return caller.archivedAt !== null ||- caller.activeRunId === null ||- caller.providerInstanceId !== scope.thread?.providerInstanceId- ? Effect.fail(+ return OrchestrationMcp.isLiveCallerShell(caller, scope.thread?.providerInstanceId)+ ? Effect.void+ : Effect.fail(new OrchestratorMcpFailure({code: "parent_not_active",message: "The calling provider no longer owns an active thread run.",}),- )- : Effect.void;+ );}export const assertFullAccess = (context: Caller, message: string) =>diff --git a/apps/server/src/orchestration-v2/ProjectionStore.test.ts b/apps/server/src/orchestration-v2/ProjectionStore.test.tsindex 9a7d56511b6..3c23bf42316 100644--- a/apps/server/src/orchestration-v2/ProjectionStore.test.ts+++ b/apps/server/src/orchestration-v2/ProjectionStore.test.ts@@ -182,6 +182,191 @@ const addRolledBackRecoveryCandidate = Effect.fn("addRolledBackRecoveryCandidatereturn threadId;});+it.effect.each([+ ["memory", ProjectionStore.layerMemory],+ ["SQL", layerTest],+] as const)(+ "%s shells use the latest subagent owner for duplicate provider-thread ids",+ ([, layer]) =>+ Effect.gen(function* () {+ const store = yield* ProjectionStore.ProjectionStoreV2;+ const threadId = yield* addRolledBackRecoveryCandidate("duplicate-provider-thread-owner");+ const initial = yield* store.getThreadProjection(threadId);+ const at = initial.updatedAt;+ const otherThreadId = yield* addRolledBackRecoveryCandidate(+ "duplicate-provider-thread-owner:other",+ );+ const other = yield* store.getThreadProjection(otherThreadId);+ const otherRun = other.runs[0]!;+ const otherInstanceId = ProviderInstanceId.make("codex-other");+ yield* store.apply({+ id: EventId.make("event:duplicate-provider-thread-owner:other-completed"),+ type: "run.updated",+ threadId: otherThreadId,+ occurredAt: at,+ payload: { ...otherRun, status: "completed", completedAt: at },+ });+ yield* store.apply({+ id: EventId.make("event:duplicate-provider-thread-owner:other-switched"),+ type: "thread.provider-switched",+ threadId: otherThreadId,+ occurredAt: at,+ payload: {+ ...other.thread,+ providerInstanceId: otherInstanceId,+ modelSelection: { ...modelSelection, instanceId: otherInstanceId },+ },+ });+ const providerThreadId = ProviderThreadId.make("provider-thread:duplicate-owner");+ const nativeTaskId = "native-task:duplicate-provider-thread-owner";+ // The latest upsert moves the row off the later-created thread.+ for (const [appThreadId, owner] of [+ [otherThreadId, otherInstanceId],+ [threadId, providerInstanceId],+ ] as const) {+ yield* store.apply({+ id: EventId.make(`event:duplicate-provider-thread-owner:${owner}`),+ type: "provider-thread.updated",+ threadId: appThreadId,+ occurredAt: at,+ payload: {+ id: providerThreadId,+ driver,+ providerInstanceId: owner,+ providerSessionId: null,+ appThreadId,+ ownerNodeId: null,+ nativeThreadRef: null,+ nativeConversationHeadRef: null,+ status: "idle",+ firstRunOrdinal: 1,+ lastRunOrdinal: 1,+ handoffIds: [],+ forkedFrom: null,+ createdAt: at,+ updatedAt: at,+ pendingBackgroundTasks:+ owner === otherInstanceId+ ? [{ taskId: nativeTaskId, kind: "subagent", description: "Review" }]+ : [],+ },+ });+ }+ yield* store.apply({+ id: EventId.make("event:duplicate-provider-thread-owner:completed"),+ type: "run.updated",+ threadId,+ occurredAt: at,+ payload: { ...initial.runs[0]!, status: "completed", completedAt: at },+ });+ const item = {+ ...initial.turnItems[0]!,+ id: TurnItemId.make("item:duplicate-provider-thread-owner"),+ providerThreadId,+ nativeItemRef: { driver, nativeId: nativeTaskId, strength: "strong" as const },+ type: "subagent" as const,+ status: "running" as const,+ subagentId: NodeId.make("node:duplicate-provider-thread-owner"),+ origin: "provider_native" as const,+ driver,+ providerInstanceId,+ childThreadId: null,+ title: "Review",+ prompt: "Review",+ result: null,+ };+ yield* store.apply({+ id: EventId.make("event:duplicate-provider-thread-owner:item"),+ type: "turn-item.updated",+ threadId,+ occurredAt: at,+ payload: item,+ });+ yield* store.apply({+ id: EventId.make("event:duplicate-provider-thread-owner:other-item"),+ type: "turn-item.updated",+ threadId: otherThreadId,+ occurredAt: at,+ payload: {+ ...item,+ id: TurnItemId.make("item:duplicate-provider-thread-owner:other"),+ threadId: otherThreadId,+ runId: otherRun.id,+ nodeId: otherRun.rootNodeId,+ subagentId: NodeId.make("node:duplicate-provider-thread-owner:other"),+ },+ });+ yield* store.apply({+ id: EventId.make("event:duplicate-provider-thread-owner:switched"),+ type: "thread.provider-switched",+ threadId,+ occurredAt: at,+ payload: {+ ...initial.thread,+ providerInstanceId: otherInstanceId,+ modelSelection: { ...modelSelection, instanceId: otherInstanceId },+ },+ });+ // The other thread's item reads its owner from a provider thread stored on another thread.+ assert.deepEqual((yield* store.getThreadProjection(otherThreadId)).providerThreads, []);+ const assertOwners = Effect.fnUntraced(function* (+ targetThreadId: ThreadId,+ expected: ReadonlyArray<unknown>,+ ) {+ const listed = (yield* store.getShellSnapshot()).threads.find(+ (thread) => thread.id === targetThreadId,+ );+ for (const shell of [yield* store.getThreadShell(targetThreadId), listed]) {+ assert.equal(shell?.providerInstanceId, otherInstanceId);+ assert.equal(shell?.activeRunId, null);+ assert.deepEqual(+ shell?.pendingBackgroundTasks?.filter((task) => task.kind === "subagent"),+ expected,+ );+ }+ });+ const owned = [+ { taskId: nativeTaskId, description: item.title, kind: "subagent", providerInstanceId },+ ];+ yield* assertOwners(threadId, owned);+ yield* assertOwners(otherThreadId, owned);+ yield* store.apply({+ id: EventId.make("event:duplicate-provider-thread-owner:stopped"),+ type: "turn-item.updated",+ threadId,+ occurredAt: at,+ payload: { ...item, status: "cancelled", completedAt: at },+ });+ yield* assertOwners(threadId, []);+ const ownerSnapshot = (yield* store.getThreadProjection(threadId)).providerThreads[0]!;+ // Rollback writes its provider snapshot before the rolled-back run events.+ yield* store.apply({+ id: EventId.make("event:duplicate-provider-thread-owner:rollback-provider-thread"),+ type: "provider-thread.updated",+ threadId: otherThreadId,+ occurredAt: at,+ payload: ownerSnapshot,+ });+ yield* store.apply({+ id: EventId.make("event:duplicate-provider-thread-owner:other-rolled-back"),+ type: "run.updated",+ threadId: otherThreadId,+ occurredAt: at,+ payload: { ...otherRun, status: "rolled_back", completedAt: at },+ });+ const rolledBack = yield* store.getThreadProjection(otherThreadId);+ assert.deepEqual(rolledBack.providerThreads, []);+ assert.equal(+ (yield* store.getThreadProjection(threadId)).thread.activeProviderThreadId,+ providerThreadId,+ );+ assert.deepEqual(+ ProjectionStore.threadShellFromProjection(rolledBack).pendingBackgroundTasks,+ [],+ );+ }).pipe(Effect.provide(layer)),+);+const addOrphanedRecoveryCandidate = Effect.fn("addOrphanedRecoveryCandidate")(function* (suffix: string,) {diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.tsindex 1a1cdff54b2..61fb0dcc05b 100644--- a/apps/server/src/orchestration-v2/ProjectionStore.ts+++ b/apps/server/src/orchestration-v2/ProjectionStore.ts@@ -33,7 +33,6 @@ import type {OrchestrationV2ThreadProjection,OrchestrationV2TurnItem,ProjectId,- ProviderInstanceId,ProviderSessionId,ProviderThreadId,ProviderTurnId,@@ -64,6 +63,7 @@ import {ThreadId,TurnItemId,NodeId,+ ProviderInstanceId,} from "@t3tools/contracts";import {createOrchestrationV2TurnItemVisibility,@@ -890,17 +890,20 @@ export function applyToProjection(/*** Provider sessions are process-scoped: one session row can be bound to several app* threads. Updating that row changes what every bound thread reads, even though the- * application event itself belongs to one thread stream.+ * application event itself belongs to one thread stream. Provider thread owners are global+ * too: the latest event wins across app threads.*/export interface ProjectionReplayState {readonly projections: Map<ThreadId, OrchestrationV2ThreadProjection>;readonly providerSessionThreadIds: Map<ProviderSessionId, ReadonlySet<ThreadId>>;+ readonly providerThreadInstanceIds: Map<ProviderThreadId, ProviderInstanceId>;}function makeProjectionReplayState(): ProjectionReplayState {return {projections: new Map(),providerSessionThreadIds: new Map(),+ providerThreadInstanceIds: new Map(),};}@@ -928,6 +931,25 @@ function applyToProjectionReplayState(state.projections.set(event.threadId, next);switch (event.type) {+ case "provider-thread.updated": {+ state.providerThreadInstanceIds.set(event.payload.id, event.payload.providerInstanceId);+ // SQL's upsert moves the provider-thread row and its roster to appThreadId.+ for (const [threadId, projection] of state.projections) {+ if (threadId === event.payload.appThreadId) {+ if (threadId !== event.threadId) {+ state.projections.set(threadId, applyToProjection(projection, event));+ }+ continue;+ }+ const providerThreads = projection.providerThreads.filter(+ (thread) => thread.id !== event.payload.id,+ );+ if (providerThreads.length !== projection.providerThreads.length) {+ state.projections.set(threadId, { ...projection, providerThreads });+ }+ }+ break;+ }case "provider-session.attached": {const boundThreadIds = new Set(state.providerSessionThreadIds.get(event.payload.id) ?? []);boundThreadIds.add(event.threadId);@@ -977,6 +999,11 @@ type PayloadRow = {readonly payload_json: string;};+type ShellPendingTurnItemRow = PayloadRow & {+ readonly thread_id: string;+ readonly owning_provider_instance_id: string | null;+};+type ShellThreadRow = {readonly thread_id: string;readonly payload_json: string;@@ -5448,9 +5475,11 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =const selectShellPendingTurnItemRows = (threadIds?: ReadonlyArray<ThreadId>) =>threadIds === undefined- ? sql<PayloadRow & { readonly thread_id: string }>`- SELECT i.thread_id, i.payload_json+ ? sql<ShellPendingTurnItemRow>`+ SELECT i.thread_id, i.payload_json, p.provider_instance_id AS owning_provider_instance_idFROM orchestration_v2_projection_turn_items i+ LEFT JOIN orchestration_v2_projection_provider_threads p+ ON p.provider_thread_id = i.provider_thread_idLEFT JOIN orchestration_v2_projection_runs rON r.run_id = i.run_idWHERE i.type IN ('command_execution', 'dynamic_tool', 'subagent')@@ -5460,9 +5489,11 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =-- matching the item_count query's exclusion above.AND (i.run_id IS NULL OR r.status <> 'rolled_back')`- : sql<PayloadRow & { readonly thread_id: string }>`- SELECT i.thread_id, i.payload_json+ : sql<ShellPendingTurnItemRow>`+ SELECT i.thread_id, i.payload_json, p.provider_instance_id AS owning_provider_instance_idFROM orchestration_v2_projection_turn_items i+ LEFT JOIN orchestration_v2_projection_provider_threads p+ ON p.provider_thread_id = i.provider_thread_idLEFT JOIN orchestration_v2_projection_runs rON r.run_id = i.run_idWHERE i.type IN ('command_execution', 'dynamic_tool', 'subagent')@@ -5496,7 +5527,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =const pendingBackgroundDataByThreadId = (input: {readonly providerThreadRows: ReadonlyArray<PayloadRow & { readonly thread_id: string }>;- readonly pendingTurnItemRows: ReadonlyArray<PayloadRow & { readonly thread_id: string }>;+ readonly pendingTurnItemRows: ReadonlyArray<ShellPendingTurnItemRow>;}) =>Effect.gen(function* () {const providerThreadsByThreadId = new Map<@@ -5517,7 +5548,16 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =const pendingTurnItemsByThreadId = new Map<ThreadId, Array<OrchestrationV2TurnItem>>();for (const row of input.pendingTurnItemRows) {- const turnItem = yield* decodeTurnItemPayload(row.payload_json);+ const turnItem = {+ ...(yield* decodeTurnItemPayload(row.payload_json)),+ ...(row.owning_provider_instance_id === null+ ? {}+ : {+ owningProviderInstanceId: ProviderInstanceId.make(+ row.owning_provider_instance_id,+ ),+ }),+ };const threadId = ThreadId.make(row.thread_id);const existing = pendingTurnItemsByThreadId.get(threadId) ?? [];existing.push(turnItem);@@ -6064,6 +6104,7 @@ export const layerMemory: Layer.Layer<ProjectionStoreV2> = Layer.effect(const next: ProjectionReplayState = {projections: new Map(existing.projections),providerSessionThreadIds: new Map(existing.providerSessionThreadIds),+ providerThreadInstanceIds: new Map(existing.providerThreadInstanceIds),};if (!applyToProjectionReplayState(next, event)) {return [@@ -6567,7 +6608,7 @@ export const layerMemory: Layer.Layer<ProjectionStoreV2> = Layer.effect(}),getThreadProjection: (threadId) =>Effect.gen(function* () {- const existing = (yield* Ref.get(replayState)).projections;+ const { projections: existing, providerThreadInstanceIds } = yield* Ref.get(replayState);const readProjection = (targetThreadId: ThreadId,seenThreadIds: ReadonlySet<ThreadId>,@@ -6596,7 +6637,17 @@ export const layerMemory: Layer.Layer<ProjectionStoreV2> = Layer.effect(if (!projection) {return yield* new ProjectionStoreThreadNotFoundError({ threadId });}- return projection;+ // Match the SQL shell join, including provider threads stored on child app threads.+ return {+ ...projection,+ turnItems: projection.turnItems.map((item) => {+ const owner =+ item.type !== "subagent" || item.providerThreadId === null+ ? undefined+ : providerThreadInstanceIds.get(item.providerThreadId);+ return owner === undefined ? item : { ...item, owningProviderInstanceId: owner };+ }),+ };}),getTurnStartContext: (threadId, runId) =>service.getThreadProjection(threadId).pipe(diff --git a/packages/contracts/src/orchestrationV2.test.ts b/packages/contracts/src/orchestrationV2.test.tsindex 7f31463a111..3f4be6092a7 100644--- a/packages/contracts/src/orchestrationV2.test.ts+++ b/packages/contracts/src/orchestrationV2.test.ts@@ -1486,6 +1486,7 @@ describe("background work kinds from older or newer servers", () => {{ taskId: "bg-3", description: "Nightly", kind: "workflow", schedule: "0 3 * * *" },{ taskId: "bg-4", description: "npm test", kind: "command" },{ taskId: "bg-5", kind: "subagent", childThreadId: "thread-child" },+ { taskId: "bg-6", kind: "subagent", providerInstanceId: "claudeAgent" },],});expect(providerThread.pendingBackgroundTasks).toEqual([@@ -1494,6 +1495,7 @@ describe("background work kinds from older or newer servers", () => {{ taskId: "bg-3", description: "Nightly", kind: "background_task" },{ taskId: "bg-4", description: "npm test", kind: "command" },{ taskId: "bg-5", kind: "subagent", childThreadId: "thread-child" },+ { taskId: "bg-6", kind: "subagent", providerInstanceId: "claudeAgent" },]);const encoded = encodeOrchestrationV2ProviderThreadJson(providerThread).pendingBackgroundTasks;expect(encoded).toEqual(providerThread.pendingBackgroundTasks);@@ -1512,6 +1514,7 @@ describe("background work kinds from older or newer servers", () => {"bg-3","bg-4","bg-5",+ "bg-6",]);expect(() =>decodeOrchestrationV2ProviderThreadJson({diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.tsindex fa4b7738eaa..50a7a452cdf 100644--- a/packages/contracts/src/orchestrationV2.ts+++ b/packages/contracts/src/orchestrationV2.ts@@ -806,6 +806,8 @@ export const OrchestrationV2PendingBackgroundTask = kindUnionWithFallback(Schema.Struct({...PendingBackgroundTaskFields,kind: Schema.Literal("subagent"),+ /** The owning provider thread's instance, populated in derived pending work. */+ providerInstanceId: Schema.optional(ProviderInstanceId),childThreadId: Schema.optional(ThreadId),}),Schema.Struct({ ...PendingBackgroundTaskFields, kind: Schema.Literal("command") }),diff --git a/packages/shared/src/orchestrationV2PendingBackgroundWork.test.ts b/packages/shared/src/orchestrationV2PendingBackgroundWork.test.tsindex 1031eb0a4a5..db701d3f4da 100644--- a/packages/shared/src/orchestrationV2PendingBackgroundWork.test.ts+++ b/packages/shared/src/orchestrationV2PendingBackgroundWork.test.ts@@ -1,5 +1,9 @@import { describe, expect, it } from "vite-plus/test";-import type { OrchestrationV2PendingBackgroundTask } from "@t3tools/contracts";+import {+ type OrchestrationV2PendingBackgroundTask,+ ProviderInstanceId,+ ProviderThreadId,+} from "@t3tools/contracts";import {backgroundWorkHoldsCompletion,derivePendingBackgroundWork,@@ -40,6 +44,50 @@ describe("backgroundWorkHoldsCompletion", () => {});describe("derivePendingBackgroundWork", () => {+ it("takes each subagent item's instance from its joined owner", () => {+ const owner = ProviderInstanceId.make("claude-owner");+ const tasks = derivePendingBackgroundWork({+ latestRun: { id: "run-1" as never, ordinal: 1, status: "completed" },+ providerThreads: [],+ turnItems: [+ {+ id: "owned-item",+ owningProviderInstanceId: owner,+ type: "subagent",+ status: "running",+ title: null,+ },+ { id: "unknown-item", type: "subagent", status: "running", title: null },+ ],+ });+ expect(tasks).toEqual([+ { taskId: "owned-item", kind: "subagent", providerInstanceId: owner },+ { taskId: "unknown-item", kind: "subagent" },+ ]);+ });++ it("takes a roster subagent's instance from its owning provider thread", () => {+ const owner = ProviderInstanceId.make("claude-owner");+ const tasks = derivePendingBackgroundWork({+ latestRun: { id: "run-1" as never, ordinal: 1, status: "completed" },+ providerThreads: [+ {+ id: ProviderThreadId.make("pt-owner"),+ providerInstanceId: owner,+ pendingBackgroundTasks: [+ {+ taskId: "roster-item",+ kind: "subagent",+ providerInstanceId: ProviderInstanceId.make("other"),+ },+ ],+ },+ ],+ turnItems: [],+ });+ expect(tasks).toEqual([{ taskId: "roster-item", kind: "subagent", providerInstanceId: owner }]);+ });+it("returns empty while the latest run is not settled", () => {const tasks = derivePendingBackgroundWork({latestRun: { id: "run-1" as never, ordinal: 1, status: "running" },diff --git a/packages/shared/src/orchestrationV2PendingBackgroundWork.ts b/packages/shared/src/orchestrationV2PendingBackgroundWork.tsindex 95a5c18971b..15453ae0185 100644--- a/packages/shared/src/orchestrationV2PendingBackgroundWork.ts+++ b/packages/shared/src/orchestrationV2PendingBackgroundWork.ts@@ -75,13 +75,15 @@ type PendingBackgroundWorkPullRequest = Pick<type PendingBackgroundWorkProviderThread = Pick<OrchestrationV2ProviderThread,"id" | "pendingBackgroundTasks"->;+> & { readonly providerInstanceId?: OrchestrationV2ProviderThread["providerInstanceId"] };type PendingBackgroundWorkTurnItem = {readonly id: OrchestrationV2TurnItem["id"] | string;readonly type: OrchestrationV2TurnItem["type"];readonly status: OrchestrationV2TurnItem["status"];readonly title: string | null;+ /** Shell readers join the owner, even when its provider thread belongs to a child app thread. */+ readonly owningProviderInstanceId?: OrchestrationV2ProviderThread["providerInstanceId"];readonly runId?: OrchestrationV2Run["id"] | string | null;readonly nativeItemRef?: {readonly nativeId: string | null;@@ -139,6 +141,9 @@ function pendingTaskFromTurnItem(return {...named,kind: "subagent",+ ...(item.owningProviderInstanceId === undefined+ ? {}+ : { providerInstanceId: item.owningProviderInstanceId }),...(item.childThreadId == null ? {} : { childThreadId: item.childThreadId }),};case "command_execution":@@ -224,6 +229,9 @@ export function derivePendingBackgroundWork(input: {const description = rawDescription?.trim();byTaskId.set(task.taskId, {...named,+ ...(task.kind === "subagent"+ ? { providerInstanceId: providerThread.providerInstanceId }+ : {}),...(description === undefined || description.length === 0 ? {} : { description }),});}