@devries-cameron20 / t3code Mirror · read-only / commits / 11ce406d2c
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 23, 08:00 UTC

fix(server): background subagents keep T3 tools after the parent turn ends (#19751)

maria committed Oct 17, 2026 at 02:11 UTC 11ce406d2cf1581748a3eb150716071f6674ec8e
10 files changed +474 -25
apps/server/src/mcp/McpToolAccess.test.ts
+43
@@ -23,6 +23,17 @@ const supervisedThreadId = ThreadId.make("thread:supervised");
23 const planThreadId = ThreadId.make("thread:plan");
24 const fullAccessThreadId = ThreadId.make("thread:full-access");
25 const endedThreadId = ThreadId.make("thread:ended");
26 +const backgroundThreadId = ThreadId.make("thread:background");
27 +const oldProviderThreadId = ThreadId.make("thread:old-provider-background");
28 +const archivedThreadId = ThreadId.make("thread:archived-background");
29 +const unknownOwnerThreadId = ThreadId.make("thread:unknown-background-owner");
30 +
31 +const backgroundShell = (threadId: ThreadId, providerInstanceId: ProviderInstanceId) => ({
32 + ...liveThreadShell(threadId, { activeRunId: null }),
33 + pendingBackgroundTasks: [
34 + { taskId: "task:background", kind: "subagent" as const, providerInstanceId },
35 + ],
36 +});
37
38 const shells = new Map([
39 [supervisedThreadId, liveThreadShell(supervisedThreadId, { runtimeMode: "approval-required" })],
@@ -32,6 +43,22 @@ const shells = new Map([
43 ],
44 [fullAccessThreadId, liveThreadShell(fullAccessThreadId)],
45 [endedThreadId, liveThreadShell(endedThreadId, { activeRunId: null })],
46 + [backgroundThreadId, backgroundShell(backgroundThreadId, ProviderInstanceId.make("codex"))],
47 + [oldProviderThreadId, backgroundShell(oldProviderThreadId, ProviderInstanceId.make("claude"))],
48 + [
49 + archivedThreadId,
50 + {
51 + ...backgroundShell(archivedThreadId, ProviderInstanceId.make("codex")),
52 + archivedAt: liveThreadShell(archivedThreadId).updatedAt,
53 + },
54 + ],
55 + [
56 + unknownOwnerThreadId,
57 + {
58 + ...liveThreadShell(unknownOwnerThreadId, { activeRunId: null }),
59 + pendingBackgroundTasks: [{ taskId: "task:unknown", kind: "subagent" as const }],
60 + },
61 + ],
62 ]);
63
64 const threadCaller = (threadId: ThreadId): McpInvocationContext.McpInvocationScope => ({
@@ -189,6 +216,15 @@ const supervised = threadCaller(supervisedThreadId);
216 const plan = threadCaller(planThreadId);
217 const fullAccess = threadCaller(fullAccessThreadId);
218 const ended = threadCaller(endedThreadId);
219 +// Its turn ended, but a background subagent it started still runs.
220 +const background = threadCaller(backgroundThreadId);
221 +const oldProviderBackground = threadCaller(oldProviderThreadId);
222 +const archivedBackground = threadCaller(archivedThreadId);
223 +const unknownOwnerBackground = threadCaller(unknownOwnerThreadId);
224 +const mismatchedProvider = {
225 + ...background,
226 + thread: { ...background.thread!, providerInstanceId: ProviderInstanceId.make("claude") },
227 +};
228 const supervisedClient = clientCaller("approval-required");
229 const fullAccessClient = clientCaller("full-access");
230 const readOnlyClient = clientCaller("read-only");
@@ -208,10 +244,17 @@ it.effect.each([
244 ["reads_as_caller", fullAccessClient, {}, "thread_credential_required"],
245 ["acts_as_caller", supervised, {}, "ran"],
246 ["acts_as_caller", ended, {}, "parent_not_active"],
247 + ["acts_as_caller", background, {}, "ran"],
248 + ["acts_as_caller", oldProviderBackground, {}, "parent_not_active"],
249 + ["acts_as_caller", mismatchedProvider, {}, "parent_not_active"],
250 + ["acts_as_caller", archivedBackground, {}, "parent_not_active"],
251 + ["acts_as_caller", unknownOwnerBackground, {}, "parent_not_active"],
252 ["acts_as_caller", fullAccessClient, {}, "thread_credential_required"],
253
254 ["writes", supervised, {}, "ran"],
255 ["writes", ended, {}, "parent_not_active"],
256 + ["writes", background, {}, "ran"],
257 + ["writes", oldProviderBackground, {}, "parent_not_active"],
258 ["writes", supervisedClient, {}, "ran"],
259 ["writes", previewOnly, {}, "capability_denied"],
260 ["writes_environment", previewOnly, {}, "capability_denied"],
apps/server/src/mcp/OrchestratorMcpService.activity.test.ts
+74 -1
@@ -27,6 +27,7 @@ import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
27 import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";
28 import type * as McpInvocationContext from "./McpInvocationContext.ts";
29 import * as OrchestratorMcpService from "./OrchestratorMcpService.ts";
30 +import { liveThreadShell } from "./McpToolAccess.testkit.ts";
31
32 const layerOrchestratorService = OrchestratorMcpService.layer.pipe(
33 Layer.provide(Layer.mock(ThreadLaunchService.ThreadLaunchService)({})),
@@ -363,6 +364,7 @@ it("taskStatus returns task.providerInstanceId rather than the driver kind", asy
364 });
365
366 it("readThread and sendToThread reach threads in other projects", async () => {
367 + let parentShell: OrchestrationV2ThreadShell | null = null;
368 let parentRuns: ReadonlyArray<unknown> = [
369 makeRun({ id: RunId.make("run-parent-live"), ordinal: 1, status: "running" }),
370 ];
@@ -435,7 +437,9 @@ it("readThread and sendToThread reach threads in other projects", async () => {
437 Effect.succeed(
438 threadId === foreignThreadId
439 ? (foreignProjection(threadId).thread as unknown as OrchestrationV2ThreadShell)
438 - : null,
440 + : threadId === parentThreadId
441 + ? parentShell
442 + : null,
443 ),
444 getTimelinePage: (threadId) =>
445 Effect.succeed({
@@ -528,5 +532,74 @@ it("readThread and sendToThread reach threads in other projects", async () => {
532 .deleteScheduledTask(makeScope(), { scheduledTaskId: ScheduledTaskId.make("task-foreign") })
533 .pipe(Effect.flip);
534 expect(staleDelete.code).toBe("parent_not_active");
535 +
536 + // A background item keeps only its owning instance live, even after a switch.
537 + const backgroundTasks = [
538 + {
539 + taskId: "background-subagent",
540 + kind: "subagent" as const,
541 + providerInstanceId: parentInstanceId,
542 + },
543 + ];
544 + parentShell = {
545 + ...liveThreadShell(parentThreadId, { activeRunId: null }),
546 + pendingBackgroundTasks: backgroundTasks,
547 + };
548 + const backgroundSent = yield* service.sendToThread(makeScope(), {
549 + threadId: foreignThreadId,
550 + message: "background",
551 + });
552 + expect(backgroundSent.threadId).toBe(foreignThreadId);
553 + const delegate = yield* service
554 + .delegateTask(makeScope(), { task: "requires a run" })
555 + .pipe(Effect.flip);
556 + expect(delegate.code).toBe("parent_not_active");
557 + const create = yield* service
558 + .createThreads(makeScope(), { threads: [{ prompt: "requires a run" }] })
559 + .pipe(Effect.flip);
560 + expect(create.code).toBe("parent_not_active");
561 + const secret = yield* service
562 + .requestSecret(makeScope(), { label: "Secret", reason: "requires a run" })
563 + .pipe(Effect.flip);
564 + expect(secret.code).toBe("parent_not_active");
565 +
566 + parentShell = { ...parentShell, providerInstanceId: customCodexInstanceId };
567 + const switchedScope = {
568 + ...makeScope(),
569 + thread: { ...makeScope().thread!, providerInstanceId: customCodexInstanceId },
570 + };
571 + const switched = yield* service
572 + .sendToThread(switchedScope, { threadId: foreignThreadId, message: "wrong owner" })
573 + .pipe(Effect.flip);
574 + expect(switched.code).toBe("parent_not_active");
575 + const mismatched = yield* service
576 + .sendToThread(makeScope(), { threadId: foreignThreadId, message: "stale provider" })
577 + .pipe(Effect.flip);
578 + expect(mismatched.code).toBe("parent_not_active");
579 +
580 + // A fresh active run wins over the earlier inactive projection and empty roster.
581 + parentShell = liveThreadShell(parentThreadId);
582 + const restarted = yield* service.sendToThread(makeScope(), {
583 + threadId: foreignThreadId,
584 + message: "new run",
585 + });
586 + expect(restarted.threadId).toBe(foreignThreadId);
587 +
588 + parentShell = {
589 + ...parentShell,
590 + activeRunId: null,
591 + pendingBackgroundTasks: backgroundTasks,
592 + archivedAt: now,
593 + };
594 + const archived = yield* service
595 + .sendToThread(makeScope(), { threadId: foreignThreadId, message: "archived" })
596 + .pipe(Effect.flip);
597 + expect(archived.code).toBe("parent_not_active");
598 +
599 + parentShell = { ...parentShell, archivedAt: null, pendingBackgroundTasks: [] };
600 + const stopped = yield* service
601 + .sendToThread(makeScope(), { threadId: foreignThreadId, message: "after stop" })
602 + .pipe(Effect.flip);
603 + expect(stopped.code).toBe("parent_not_active");
604 }).pipe(Effect.provide(layer), Effect.runPromise);
605 });
apps/server/src/mcp/OrchestratorMcpService.ts
+40 -3
@@ -50,6 +50,7 @@ import {
50 type OrchestratorMcpThreadWaitInput,
51 type OrchestratorMcpThreadWaitResult,
52 type ProviderInteractionMode,
53 + type ProviderInstanceId,
54 type ProviderOptionDescriptor,
55 type ProviderOptionSelection,
56 type RuntimeMode,
@@ -200,6 +201,29 @@ function failure(code: OrchestratorMcpFailure["code"], message: string): Orchest
201 return new OrchestratorMcpFailure({ code, message });
202 }
203
204 +/**
205 + * A caller's thread is live while it is not archived, runs on the caller's
206 + * provider instance, and has an active run or a background subagent that
207 + * instance started. A background subagent outlives its run and calls tools
208 + * with its thread's credential, which is revoked when the provider process
209 + * goes away.
210 + */
211 +export const isLiveCallerShell = (
212 + shell: Pick<
213 + OrchestrationV2ThreadShell,
214 + "archivedAt" | "activeRunId" | "providerInstanceId" | "pendingBackgroundTasks"
215 + > | null,
216 + providerInstanceId: ProviderInstanceId | undefined,
217 +) =>
218 + shell !== null &&
219 + shell.archivedAt === null &&
220 + shell.providerInstanceId === providerInstanceId &&
221 + (shell.activeRunId !== null ||
222 + (shell.pendingBackgroundTasks?.some(
223 + (task) => task.kind === "subagent" && task.providerInstanceId === providerInstanceId,
224 + ) ??
225 + false));
226 +
227 function threadManagementFailure(error: unknown): OrchestratorMcpFailure {
228 if (!isThreadManagementError(error)) return failure("orchestration_error", errorMessage(error));
229 switch (error._tag) {
@@ -1060,13 +1084,26 @@ const make = Effect.gen(function* () {
1084 scope: McpInvocationScope,
1085 parent: Pick<OrchestrationV2ThreadProjection, "thread" | "runs">,
1086 ) => {
1087 + const notActive = failure(
1088 + "parent_not_active",
1089 + "The calling provider no longer owns an active thread run.",
1090 + );
1091 const activeRun = ThreadManagementService.latestActiveRun(parent);
1092 + if (parent.thread.archivedAt === null && activeRun === undefined) {
1093 + // Decide from this one fresh snapshot: a run may have started since `parent` was read.
1094 + return threadManagement.getThreadShell(parent.thread.id).pipe(
1095 + Effect.mapError(threadManagementFailure),
1096 + Effect.flatMap((shell) =>
1097 + isLiveCallerShell(shell, scope.thread?.providerInstanceId)
1098 + ? Effect.void
1099 + : Effect.fail(notActive),
1100 + ),
1101 + );
1102 + }
1103 return parent.thread.archivedAt !== null ||
1104 activeRun === undefined ||
1105 activeRun.providerInstanceId !== scope.thread?.providerInstanceId
1067 - ? Effect.fail(
1068 - failure("parent_not_active", "The calling provider no longer owns an active thread run."),
1069 - )
1106 + ? Effect.fail(notActive)
1107 : Effect.void;
1108 };
1109
apps/server/src/mcp/threadAccess.ts
+8 -9
@@ -103,22 +103,21 @@ export const assertTargetWithinLimits = (
103 );
104
105 /**
106 - * A thread caller acts only while it owns a live run of a thread that is not
107 - * archived, so a provider token that outlived its session cannot act. An
108 - * OAuth client has no run; its session and ceiling are its authority.
106 + * A thread caller acts only while it owns a live run, or a background
107 + * subagent that run started, of a thread that is not archived, so a provider
108 + * token that outlived its session cannot act. An OAuth client has no run; its
109 + * session and ceiling are its authority.
110 */
111 export function assertLiveCaller({ caller, scope }: Caller) {
112 if (caller === undefined) return Effect.void;
112 - return caller.archivedAt !== null ||
113 - caller.activeRunId === null ||
114 - caller.providerInstanceId !== scope.thread?.providerInstanceId
115 - ? Effect.fail(
113 + return OrchestrationMcp.isLiveCallerShell(caller, scope.thread?.providerInstanceId)
114 + ? Effect.void
115 + : Effect.fail(
116 new OrchestratorMcpFailure({
117 code: "parent_not_active",
118 message: "The calling provider no longer owns an active thread run.",
119 }),
120 - )
121 - : Effect.void;
120 + );
121 }
122
123 export const assertFullAccess = (context: Caller, message: string) =>
apps/server/src/orchestration-v2/ProjectionStore.test.ts
+185
@@ -182,6 +182,191 @@ const addRolledBackRecoveryCandidate = Effect.fn("addRolledBackRecoveryCandidate
182 return threadId;
183 });
184
185 +it.effect.each([
186 + ["memory", ProjectionStore.layerMemory],
187 + ["SQL", layerTest],
188 +] as const)(
189 + "%s shells use the latest subagent owner for duplicate provider-thread ids",
190 + ([, layer]) =>
191 + Effect.gen(function* () {
192 + const store = yield* ProjectionStore.ProjectionStoreV2;
193 + const threadId = yield* addRolledBackRecoveryCandidate("duplicate-provider-thread-owner");
194 + const initial = yield* store.getThreadProjection(threadId);
195 + const at = initial.updatedAt;
196 + const otherThreadId = yield* addRolledBackRecoveryCandidate(
197 + "duplicate-provider-thread-owner:other",
198 + );
199 + const other = yield* store.getThreadProjection(otherThreadId);
200 + const otherRun = other.runs[0]!;
201 + const otherInstanceId = ProviderInstanceId.make("codex-other");
202 + yield* store.apply({
203 + id: EventId.make("event:duplicate-provider-thread-owner:other-completed"),
204 + type: "run.updated",
205 + threadId: otherThreadId,
206 + occurredAt: at,
207 + payload: { ...otherRun, status: "completed", completedAt: at },
208 + });
209 + yield* store.apply({
210 + id: EventId.make("event:duplicate-provider-thread-owner:other-switched"),
211 + type: "thread.provider-switched",
212 + threadId: otherThreadId,
213 + occurredAt: at,
214 + payload: {
215 + ...other.thread,
216 + providerInstanceId: otherInstanceId,
217 + modelSelection: { ...modelSelection, instanceId: otherInstanceId },
218 + },
219 + });
220 + const providerThreadId = ProviderThreadId.make("provider-thread:duplicate-owner");
221 + const nativeTaskId = "native-task:duplicate-provider-thread-owner";
222 + // The latest upsert moves the row off the later-created thread.
223 + for (const [appThreadId, owner] of [
224 + [otherThreadId, otherInstanceId],
225 + [threadId, providerInstanceId],
226 + ] as const) {
227 + yield* store.apply({
228 + id: EventId.make(`event:duplicate-provider-thread-owner:${owner}`),
229 + type: "provider-thread.updated",
230 + threadId: appThreadId,
231 + occurredAt: at,
232 + payload: {
233 + id: providerThreadId,
234 + driver,
235 + providerInstanceId: owner,
236 + providerSessionId: null,
237 + appThreadId,
238 + ownerNodeId: null,
239 + nativeThreadRef: null,
240 + nativeConversationHeadRef: null,
241 + status: "idle",
242 + firstRunOrdinal: 1,
243 + lastRunOrdinal: 1,
244 + handoffIds: [],
245 + forkedFrom: null,
246 + createdAt: at,
247 + updatedAt: at,
248 + pendingBackgroundTasks:
249 + owner === otherInstanceId
250 + ? [{ taskId: nativeTaskId, kind: "subagent", description: "Review" }]
251 + : [],
252 + },
253 + });
254 + }
255 + yield* store.apply({
256 + id: EventId.make("event:duplicate-provider-thread-owner:completed"),
257 + type: "run.updated",
258 + threadId,
259 + occurredAt: at,
260 + payload: { ...initial.runs[0]!, status: "completed", completedAt: at },
261 + });
262 + const item = {
263 + ...initial.turnItems[0]!,
264 + id: TurnItemId.make("item:duplicate-provider-thread-owner"),
265 + providerThreadId,
266 + nativeItemRef: { driver, nativeId: nativeTaskId, strength: "strong" as const },
267 + type: "subagent" as const,
268 + status: "running" as const,
269 + subagentId: NodeId.make("node:duplicate-provider-thread-owner"),
270 + origin: "provider_native" as const,
271 + driver,
272 + providerInstanceId,
273 + childThreadId: null,
274 + title: "Review",
275 + prompt: "Review",
276 + result: null,
277 + };
278 + yield* store.apply({
279 + id: EventId.make("event:duplicate-provider-thread-owner:item"),
280 + type: "turn-item.updated",
281 + threadId,
282 + occurredAt: at,
283 + payload: item,
284 + });
285 + yield* store.apply({
286 + id: EventId.make("event:duplicate-provider-thread-owner:other-item"),
287 + type: "turn-item.updated",
288 + threadId: otherThreadId,
289 + occurredAt: at,
290 + payload: {
291 + ...item,
292 + id: TurnItemId.make("item:duplicate-provider-thread-owner:other"),
293 + threadId: otherThreadId,
294 + runId: otherRun.id,
295 + nodeId: otherRun.rootNodeId,
296 + subagentId: NodeId.make("node:duplicate-provider-thread-owner:other"),
297 + },
298 + });
299 + yield* store.apply({
300 + id: EventId.make("event:duplicate-provider-thread-owner:switched"),
301 + type: "thread.provider-switched",
302 + threadId,
303 + occurredAt: at,
304 + payload: {
305 + ...initial.thread,
306 + providerInstanceId: otherInstanceId,
307 + modelSelection: { ...modelSelection, instanceId: otherInstanceId },
308 + },
309 + });
310 + // The other thread's item reads its owner from a provider thread stored on another thread.
311 + assert.deepEqual((yield* store.getThreadProjection(otherThreadId)).providerThreads, []);
312 + const assertOwners = Effect.fnUntraced(function* (
313 + targetThreadId: ThreadId,
314 + expected: ReadonlyArray<unknown>,
315 + ) {
316 + const listed = (yield* store.getShellSnapshot()).threads.find(
317 + (thread) => thread.id === targetThreadId,
318 + );
319 + for (const shell of [yield* store.getThreadShell(targetThreadId), listed]) {
320 + assert.equal(shell?.providerInstanceId, otherInstanceId);
321 + assert.equal(shell?.activeRunId, null);
322 + assert.deepEqual(
323 + shell?.pendingBackgroundTasks?.filter((task) => task.kind === "subagent"),
324 + expected,
325 + );
326 + }
327 + });
328 + const owned = [
329 + { taskId: nativeTaskId, description: item.title, kind: "subagent", providerInstanceId },
330 + ];
331 + yield* assertOwners(threadId, owned);
332 + yield* assertOwners(otherThreadId, owned);
333 + yield* store.apply({
334 + id: EventId.make("event:duplicate-provider-thread-owner:stopped"),
335 + type: "turn-item.updated",
336 + threadId,
337 + occurredAt: at,
338 + payload: { ...item, status: "cancelled", completedAt: at },
339 + });
340 + yield* assertOwners(threadId, []);
341 + const ownerSnapshot = (yield* store.getThreadProjection(threadId)).providerThreads[0]!;
342 + // Rollback writes its provider snapshot before the rolled-back run events.
343 + yield* store.apply({
344 + id: EventId.make("event:duplicate-provider-thread-owner:rollback-provider-thread"),
345 + type: "provider-thread.updated",
346 + threadId: otherThreadId,
347 + occurredAt: at,
348 + payload: ownerSnapshot,
349 + });
350 + yield* store.apply({
351 + id: EventId.make("event:duplicate-provider-thread-owner:other-rolled-back"),
352 + type: "run.updated",
353 + threadId: otherThreadId,
354 + occurredAt: at,
355 + payload: { ...otherRun, status: "rolled_back", completedAt: at },
356 + });
357 + const rolledBack = yield* store.getThreadProjection(otherThreadId);
358 + assert.deepEqual(rolledBack.providerThreads, []);
359 + assert.equal(
360 + (yield* store.getThreadProjection(threadId)).thread.activeProviderThreadId,
361 + providerThreadId,
362 + );
363 + assert.deepEqual(
364 + ProjectionStore.threadShellFromProjection(rolledBack).pendingBackgroundTasks,
365 + [],
366 + );
367 + }).pipe(Effect.provide(layer)),
368 +);
369 +
370 const addOrphanedRecoveryCandidate = Effect.fn("addOrphanedRecoveryCandidate")(function* (
371 suffix: string,
372 ) {
apps/server/src/orchestration-v2/ProjectionStore.ts
+61 -10
@@ -33,7 +33,6 @@ import type {
33 OrchestrationV2ThreadProjection,
34 OrchestrationV2TurnItem,
35 ProjectId,
36 - ProviderInstanceId,
36 ProviderSessionId,
37 ProviderThreadId,
38 ProviderTurnId,
@@ -64,6 +63,7 @@ import {
63 ThreadId,
64 TurnItemId,
65 NodeId,
66 + ProviderInstanceId,
67 } from "@t3tools/contracts";
68 import {
69 createOrchestrationV2TurnItemVisibility,
@@ -890,17 +890,20 @@ export function applyToProjection(
890 /**
891 * Provider sessions are process-scoped: one session row can be bound to several app
892 * threads. Updating that row changes what every bound thread reads, even though the
893 - * application event itself belongs to one thread stream.
893 + * application event itself belongs to one thread stream. Provider thread owners are global
894 + * too: the latest event wins across app threads.
895 */
896 export interface ProjectionReplayState {
897 readonly projections: Map<ThreadId, OrchestrationV2ThreadProjection>;
898 readonly providerSessionThreadIds: Map<ProviderSessionId, ReadonlySet<ThreadId>>;
899 + readonly providerThreadInstanceIds: Map<ProviderThreadId, ProviderInstanceId>;
900 }
901
902 function makeProjectionReplayState(): ProjectionReplayState {
903 return {
904 projections: new Map(),
905 providerSessionThreadIds: new Map(),
906 + providerThreadInstanceIds: new Map(),
907 };
908 }
909
@@ -928,6 +931,25 @@ function applyToProjectionReplayState(
931 state.projections.set(event.threadId, next);
932
933 switch (event.type) {
934 + case "provider-thread.updated": {
935 + state.providerThreadInstanceIds.set(event.payload.id, event.payload.providerInstanceId);
936 + // SQL's upsert moves the provider-thread row and its roster to appThreadId.
937 + for (const [threadId, projection] of state.projections) {
938 + if (threadId === event.payload.appThreadId) {
939 + if (threadId !== event.threadId) {
940 + state.projections.set(threadId, applyToProjection(projection, event));
941 + }
942 + continue;
943 + }
944 + const providerThreads = projection.providerThreads.filter(
945 + (thread) => thread.id !== event.payload.id,
946 + );
947 + if (providerThreads.length !== projection.providerThreads.length) {
948 + state.projections.set(threadId, { ...projection, providerThreads });
949 + }
950 + }
951 + break;
952 + }
953 case "provider-session.attached": {
954 const boundThreadIds = new Set(state.providerSessionThreadIds.get(event.payload.id) ?? []);
955 boundThreadIds.add(event.threadId);
@@ -977,6 +999,11 @@ type PayloadRow = {
999 readonly payload_json: string;
1000 };
1001
1002 +type ShellPendingTurnItemRow = PayloadRow & {
1003 + readonly thread_id: string;
1004 + readonly owning_provider_instance_id: string | null;
1005 +};
1006 +
1007 type ShellThreadRow = {
1008 readonly thread_id: string;
1009 readonly payload_json: string;
@@ -5448,9 +5475,11 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
5475
5476 const selectShellPendingTurnItemRows = (threadIds?: ReadonlyArray<ThreadId>) =>
5477 threadIds === undefined
5451 - ? sql<PayloadRow & { readonly thread_id: string }>`
5452 - SELECT i.thread_id, i.payload_json
5478 + ? sql<ShellPendingTurnItemRow>`
5479 + SELECT i.thread_id, i.payload_json, p.provider_instance_id AS owning_provider_instance_id
5480 FROM orchestration_v2_projection_turn_items i
5481 + LEFT JOIN orchestration_v2_projection_provider_threads p
5482 + ON p.provider_thread_id = i.provider_thread_id
5483 LEFT JOIN orchestration_v2_projection_runs r
5484 ON r.run_id = i.run_id
5485 WHERE i.type IN ('command_execution', 'dynamic_tool', 'subagent')
@@ -5460,9 +5489,11 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
5489 -- matching the item_count query's exclusion above.
5490 AND (i.run_id IS NULL OR r.status <> 'rolled_back')
5491 `
5463 - : sql<PayloadRow & { readonly thread_id: string }>`
5464 - SELECT i.thread_id, i.payload_json
5492 + : sql<ShellPendingTurnItemRow>`
5493 + SELECT i.thread_id, i.payload_json, p.provider_instance_id AS owning_provider_instance_id
5494 FROM orchestration_v2_projection_turn_items i
5495 + LEFT JOIN orchestration_v2_projection_provider_threads p
5496 + ON p.provider_thread_id = i.provider_thread_id
5497 LEFT JOIN orchestration_v2_projection_runs r
5498 ON r.run_id = i.run_id
5499 WHERE i.type IN ('command_execution', 'dynamic_tool', 'subagent')
@@ -5496,7 +5527,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
5527
5528 const pendingBackgroundDataByThreadId = (input: {
5529 readonly providerThreadRows: ReadonlyArray<PayloadRow & { readonly thread_id: string }>;
5499 - readonly pendingTurnItemRows: ReadonlyArray<PayloadRow & { readonly thread_id: string }>;
5530 + readonly pendingTurnItemRows: ReadonlyArray<ShellPendingTurnItemRow>;
5531 }) =>
5532 Effect.gen(function* () {
5533 const providerThreadsByThreadId = new Map<
@@ -5517,7 +5548,16 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
5548
5549 const pendingTurnItemsByThreadId = new Map<ThreadId, Array<OrchestrationV2TurnItem>>();
5550 for (const row of input.pendingTurnItemRows) {
5520 - const turnItem = yield* decodeTurnItemPayload(row.payload_json);
5551 + const turnItem = {
5552 + ...(yield* decodeTurnItemPayload(row.payload_json)),
5553 + ...(row.owning_provider_instance_id === null
5554 + ? {}
5555 + : {
5556 + owningProviderInstanceId: ProviderInstanceId.make(
5557 + row.owning_provider_instance_id,
5558 + ),
5559 + }),
5560 + };
5561 const threadId = ThreadId.make(row.thread_id);
5562 const existing = pendingTurnItemsByThreadId.get(threadId) ?? [];
5563 existing.push(turnItem);
@@ -6064,6 +6104,7 @@ export const layerMemory: Layer.Layer<ProjectionStoreV2> = Layer.effect(
6104 const next: ProjectionReplayState = {
6105 projections: new Map(existing.projections),
6106 providerSessionThreadIds: new Map(existing.providerSessionThreadIds),
6107 + providerThreadInstanceIds: new Map(existing.providerThreadInstanceIds),
6108 };
6109 if (!applyToProjectionReplayState(next, event)) {
6110 return [
@@ -6567,7 +6608,7 @@ export const layerMemory: Layer.Layer<ProjectionStoreV2> = Layer.effect(
6608 }),
6609 getThreadProjection: (threadId) =>
6610 Effect.gen(function* () {
6570 - const existing = (yield* Ref.get(replayState)).projections;
6611 + const { projections: existing, providerThreadInstanceIds } = yield* Ref.get(replayState);
6612 const readProjection = (
6613 targetThreadId: ThreadId,
6614 seenThreadIds: ReadonlySet<ThreadId>,
@@ -6596,7 +6637,17 @@ export const layerMemory: Layer.Layer<ProjectionStoreV2> = Layer.effect(
6637 if (!projection) {
6638 return yield* new ProjectionStoreThreadNotFoundError({ threadId });
6639 }
6599 - return projection;
6640 + // Match the SQL shell join, including provider threads stored on child app threads.
6641 + return {
6642 + ...projection,
6643 + turnItems: projection.turnItems.map((item) => {
6644 + const owner =
6645 + item.type !== "subagent" || item.providerThreadId === null
6646 + ? undefined
6647 + : providerThreadInstanceIds.get(item.providerThreadId);
6648 + return owner === undefined ? item : { ...item, owningProviderInstanceId: owner };
6649 + }),
6650 + };
6651 }),
6652 getTurnStartContext: (threadId, runId) =>
6653 service.getThreadProjection(threadId).pipe(
packages/contracts/src/orchestrationV2.test.ts
+3
@@ -1486,6 +1486,7 @@ describe("background work kinds from older or newer servers", () => {
1486 { taskId: "bg-3", description: "Nightly", kind: "workflow", schedule: "0 3 * * *" },
1487 { taskId: "bg-4", description: "npm test", kind: "command" },
1488 { taskId: "bg-5", kind: "subagent", childThreadId: "thread-child" },
1489 + { taskId: "bg-6", kind: "subagent", providerInstanceId: "claudeAgent" },
1490 ],
1491 });
1492 expect(providerThread.pendingBackgroundTasks).toEqual([
@@ -1494,6 +1495,7 @@ describe("background work kinds from older or newer servers", () => {
1495 { taskId: "bg-3", description: "Nightly", kind: "background_task" },
1496 { taskId: "bg-4", description: "npm test", kind: "command" },
1497 { taskId: "bg-5", kind: "subagent", childThreadId: "thread-child" },
1498 + { taskId: "bg-6", kind: "subagent", providerInstanceId: "claudeAgent" },
1499 ]);
1500 const encoded = encodeOrchestrationV2ProviderThreadJson(providerThread).pendingBackgroundTasks;
1501 expect(encoded).toEqual(providerThread.pendingBackgroundTasks);
@@ -1512,6 +1514,7 @@ describe("background work kinds from older or newer servers", () => {
1514 "bg-3",
1515 "bg-4",
1516 "bg-5",
1517 + "bg-6",
1518 ]);
1519 expect(() =>
1520 decodeOrchestrationV2ProviderThreadJson({
packages/contracts/src/orchestrationV2.ts
+2
@@ -806,6 +806,8 @@ export const OrchestrationV2PendingBackgroundTask = kindUnionWithFallback(
806 Schema.Struct({
807 ...PendingBackgroundTaskFields,
808 kind: Schema.Literal("subagent"),
809 + /** The owning provider thread's instance, populated in derived pending work. */
810 + providerInstanceId: Schema.optional(ProviderInstanceId),
811 childThreadId: Schema.optional(ThreadId),
812 }),
813 Schema.Struct({ ...PendingBackgroundTaskFields, kind: Schema.Literal("command") }),
packages/shared/src/orchestrationV2PendingBackgroundWork.test.ts
+49 -1
@@ -1,5 +1,9 @@
1 import { describe, expect, it } from "vite-plus/test";
2 -import type { OrchestrationV2PendingBackgroundTask } from "@t3tools/contracts";
2 +import {
3 + type OrchestrationV2PendingBackgroundTask,
4 + ProviderInstanceId,
5 + ProviderThreadId,
6 +} from "@t3tools/contracts";
7 import {
8 backgroundWorkHoldsCompletion,
9 derivePendingBackgroundWork,
@@ -40,6 +44,50 @@ describe("backgroundWorkHoldsCompletion", () => {
44 });
45
46 describe("derivePendingBackgroundWork", () => {
47 + it("takes each subagent item's instance from its joined owner", () => {
48 + const owner = ProviderInstanceId.make("claude-owner");
49 + const tasks = derivePendingBackgroundWork({
50 + latestRun: { id: "run-1" as never, ordinal: 1, status: "completed" },
51 + providerThreads: [],
52 + turnItems: [
53 + {
54 + id: "owned-item",
55 + owningProviderInstanceId: owner,
56 + type: "subagent",
57 + status: "running",
58 + title: null,
59 + },
60 + { id: "unknown-item", type: "subagent", status: "running", title: null },
61 + ],
62 + });
63 + expect(tasks).toEqual([
64 + { taskId: "owned-item", kind: "subagent", providerInstanceId: owner },
65 + { taskId: "unknown-item", kind: "subagent" },
66 + ]);
67 + });
68 +
69 + it("takes a roster subagent's instance from its owning provider thread", () => {
70 + const owner = ProviderInstanceId.make("claude-owner");
71 + const tasks = derivePendingBackgroundWork({
72 + latestRun: { id: "run-1" as never, ordinal: 1, status: "completed" },
73 + providerThreads: [
74 + {
75 + id: ProviderThreadId.make("pt-owner"),
76 + providerInstanceId: owner,
77 + pendingBackgroundTasks: [
78 + {
79 + taskId: "roster-item",
80 + kind: "subagent",
81 + providerInstanceId: ProviderInstanceId.make("other"),
82 + },
83 + ],
84 + },
85 + ],
86 + turnItems: [],
87 + });
88 + expect(tasks).toEqual([{ taskId: "roster-item", kind: "subagent", providerInstanceId: owner }]);
89 + });
90 +
91 it("returns empty while the latest run is not settled", () => {
92 const tasks = derivePendingBackgroundWork({
93 latestRun: { id: "run-1" as never, ordinal: 1, status: "running" },
packages/shared/src/orchestrationV2PendingBackgroundWork.ts
+9 -1
@@ -75,13 +75,15 @@ type PendingBackgroundWorkPullRequest = Pick<
75 type PendingBackgroundWorkProviderThread = Pick<
76 OrchestrationV2ProviderThread,
77 "id" | "pendingBackgroundTasks"
78 ->;
78 +> & { readonly providerInstanceId?: OrchestrationV2ProviderThread["providerInstanceId"] };
79
80 type PendingBackgroundWorkTurnItem = {
81 readonly id: OrchestrationV2TurnItem["id"] | string;
82 readonly type: OrchestrationV2TurnItem["type"];
83 readonly status: OrchestrationV2TurnItem["status"];
84 readonly title: string | null;
85 + /** Shell readers join the owner, even when its provider thread belongs to a child app thread. */
86 + readonly owningProviderInstanceId?: OrchestrationV2ProviderThread["providerInstanceId"];
87 readonly runId?: OrchestrationV2Run["id"] | string | null;
88 readonly nativeItemRef?: {
89 readonly nativeId: string | null;
@@ -139,6 +141,9 @@ function pendingTaskFromTurnItem(
141 return {
142 ...named,
143 kind: "subagent",
144 + ...(item.owningProviderInstanceId === undefined
145 + ? {}
146 + : { providerInstanceId: item.owningProviderInstanceId }),
147 ...(item.childThreadId == null ? {} : { childThreadId: item.childThreadId }),
148 };
149 case "command_execution":
@@ -224,6 +229,9 @@ export function derivePendingBackgroundWork(input: {
229 const description = rawDescription?.trim();
230 byTaskId.set(task.taskId, {
231 ...named,
232 + ...(task.kind === "subagent"
233 + ? { providerInstanceId: providerThread.providerInstanceId }
234 + : {}),
235 ...(description === undefined || description.length === 0 ? {} : { description }),
236 });
237 }