@devries-cameron20 / t3code Mirror · read-only
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 21, 03:37 UTC

main
ts 815 lines 33.7 KB
Raw
1 import * as NodeURL from "node:url";
2 import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
3 import * as NodeServices from "@effect/platform-node/NodeServices";
4 import { describe, expect, it } from "@effect/vitest";
5 import {
6 CommandId,
7 EnvironmentId,
8 isProviderNativeSubagentThread,
9 MessageId,
10 type ModelSelection,
11 OrchestratorMcpDelegateTaskResult,
12 OrchestratorMcpThreadInterruptResult,
13 OrchestratorMcpThreadSendResult,
14 OrchestratorMcpThreadReadResult,
15 ProjectId,
16 ProviderDriverKind,
17 ProviderInstanceId,
18 type ProviderOptionDescriptor,
19 type ServerProvider,
20 ThreadId,
21 } from "@t3tools/contracts";
22 import * as Effect from "effect/Effect";
23 import * as FileSystem from "effect/FileSystem";
24 import * as Layer from "effect/Layer";
25 import * as Option from "effect/Option";
26 import * as Schema from "effect/Schema";
27 import * as Stream from "effect/Stream";
28 import * as Tracer from "effect/Tracer";
29 import { McpSchema, McpServer } from "effect/ai";
30
31 import { CodexOrchestratorReplayHarness } from "../orchestration-v2/Adapters/CodexAdapterV2.testkit.ts";
32 import * as CommandReceiptStore from "../orchestration-v2/CommandReceiptStore.ts";
33 import * as Orchestrator from "../orchestration-v2/Orchestrator.ts";
34 import * as ThreadLaunchService from "../orchestration-v2/ThreadLaunchService.ts";
35 import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
36 import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";
37 import * as ServerSettings from "../serverSettings.ts";
38 import * as SqlitePersistence from "../persistence/Sqlite.ts";
39 import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
40 import * as SecretResolver from "@t3tools/secret-provider-core/server/SecretResolver";
41 import { checkpointWorkspace } from "@t3tools/provider-testing/replayWorkspace";
42 import * as ProviderReplayHarness from "../orchestration-v2/testkit/ProviderReplayHarness.ts";
43 import {
44 decodeProviderReplayNdjson,
45 materializeReplayTranscriptWorkspace,
46 } from "@t3tools/provider-testing/replayTranscript";
47 import * as ProviderRegistryMock from "../provider/testUtils/providerRegistryMock.ts";
48 import * as ProjectService from "../project/ProjectService.ts";
49 import * as ScheduledTaskService from "../scheduledTasks/ScheduledTaskService.ts";
50 import * as SecretRequests from "../secrets/SecretRequests.ts";
51 import * as RemoteDelegation from "../peer/RemoteDelegation.ts";
52 import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
53 import * as McpHttpServer from "./McpHttpServer.ts";
54 import * as McpInvocationContext from "./McpInvocationContext.ts";
55 import * as PeerForwarding from "../peer/PeerForwarding.ts";
56 import * as PeerLinkRequests from "../peer/PeerLinkRequests.ts";
57 import * as PeerLinks from "../peer/PeerLinks.ts";
58
59 const layerOrchestratorToolkit = McpHttpServer.layerOrchestratorToolkit.pipe(
60 Layer.provide(Layer.mock(ThreadLaunchService.ThreadLaunchService)({})),
61 Layer.provide(Layer.mock(GitVcsDriver.GitVcsDriver)({})),
62 );
63
64 /** A task delegated here always has a local child thread. */
65 const localChild = (childThreadId: ThreadId | null): ThreadId => {
66 if (childThreadId === null) throw new Error("expected a local delegated child");
67 return childThreadId;
68 };
69
70 // Effect returns a declared tool failure as `isError` with its encoded payload
71 // as JSON text, never as `structuredContent`.
72
73 const parentThreadId = ThreadId.make("thread:mcp-orchestrator-parent");
74 const projectId = ProjectId.make("project:mcp-orchestrator");
75 const codexInstanceId = ProviderInstanceId.make("codex");
76 const codexModel = "gpt-5.4";
77 const parentPrompt = "Keep this parent turn active while orchestration tools are tested.";
78 const delegatedPrompt = "Inspect the delegated API boundary and return the result.";
79 const delegatedResult = "Delegated API boundary inspected.";
80 const cancellationPrompt = "Remain active until the parent cancels this delegated task.";
81 const queuedFollowupPrompt = "Complete the queued follow-up and return the final result.";
82 const queuedFollowupResult = "Queued delegated follow-up completed.";
83 const decodeThreadRead = Schema.decodeUnknownEffect(OrchestratorMcpThreadReadResult);
84 const longFollowupResult = "Long delegated follow-up line. ".repeat(1_500);
85
86 const decodeDelegateTaskResult = Schema.decodeUnknownEffect(OrchestratorMcpDelegateTaskResult);
87 const decodeThreadInterruptResult = Schema.decodeUnknownEffect(
88 OrchestratorMcpThreadInterruptResult,
89 );
90 const decodeThreadSendResult = Schema.decodeUnknownEffect(OrchestratorMcpThreadSendResult);
91
92 const codexSelection = {
93 instanceId: codexInstanceId,
94 model: codexModel,
95 } satisfies ModelSelection;
96
97 const delegatedTaskStatusTranscriptFile = new URL(
98 "../orchestration-v2/testkit/fixtures/delegated_task_status/codex_transcript.ndjson",
99 import.meta.url,
100 );
101
102 const readDelegatedTaskStatusTranscript = Effect.fn("readDelegatedTaskStatusTranscript")(
103 function* (followupResult: string) {
104 const fs = yield* FileSystem.FileSystem;
105 const text = yield* fs.readFileString(NodeURL.fileURLToPath(delegatedTaskStatusTranscriptFile));
106 // The recording names the parent, then the child, after the fixture's titles; this test's differ.
107 const threadNames = ["MCP replay parent", delegatedPrompt];
108 const transcript = yield* decodeProviderReplayNdjson(
109 text
110 .replaceAll(queuedFollowupResult, followupResult)
111 .replace(
112 /"name":"Replay fixture: delegated_task_status"/g,
113 () => `"name":${JSON.stringify(threadNames.shift())}`,
114 ),
115 );
116 // The recording ends when the recorder closes the app-server while the parent
117 // turn is still open. This test keeps acting as that parent afterwards, and
118 // replaying the exit would kill the shared process and fail the parent run.
119 return {
120 ...transcript,
121 entries: transcript.entries.filter((entry) => entry.type !== "runtime_exit"),
122 };
123 },
124 Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
125 );
126
127 function makeProviderSnapshot(input: {
128 readonly instanceId: ProviderInstanceId;
129 readonly driver: ProviderDriverKind;
130 readonly model: string;
131 readonly optionDescriptors?: ReadonlyArray<ProviderOptionDescriptor>;
132 }): ServerProvider {
133 return {
134 instanceId: input.instanceId,
135 driver: input.driver,
136 enabled: true,
137 installed: true,
138 version: "test",
139 status: "ready",
140 auth: { status: "authenticated" },
141 checkedAt: "2026-06-17T00:00:00.000Z",
142 models: [
143 {
144 slug: input.model,
145 name: input.model,
146 isCustom: false,
147 capabilities:
148 input.optionDescriptors === undefined
149 ? null
150 : { optionDescriptors: input.optionDescriptors },
151 },
152 ],
153 slashCommands: [],
154 skills: [],
155 };
156 }
157
158 const client = McpSchema.McpServerClient.of({
159 clientId: 1,
160 protocolVersion: "2025-06-18",
161 clientCapabilities: {},
162 clientInfo: { name: "orchestrator-mcp-test", version: "1.0.0" },
163 initializePayload: {
164 protocolVersion: "2025-06-18",
165 capabilities: {},
166 clientInfo: { name: "orchestrator-mcp-test", version: "1.0.0" },
167 },
168 getClient: Effect.die("unused"),
169 });
170
171 const layerMemorySecretStore = Layer.sync(ServerSecretStore.ServerSecretStore, () => {
172 const stored = new Map<string, Uint8Array>();
173 return ServerSecretStore.ServerSecretStore.of({
174 get: (name) => Effect.succeed(Option.fromNullishOr(stored.get(name))),
175 set: (name, value) => Effect.sync(() => void stored.set(name, value)),
176 create: (name, value) => Effect.sync(() => void stored.set(name, value)),
177 getOrCreateRandom: (name, bytes) =>
178 Effect.sync(() => {
179 const existing = stored.get(name);
180 if (existing) return existing;
181 const value = new Uint8Array(bytes).fill(7);
182 stored.set(name, value);
183 return value;
184 }),
185 remove: (name) => Effect.sync(() => void stored.delete(name)),
186 });
187 });
188
189 const layerUnusedScheduledTaskStub = Layer.succeed(
190 ScheduledTaskService.ScheduledTaskService,
191 ScheduledTaskService.ScheduledTaskService.of({
192 list: () => Effect.succeed({ tasks: [] }),
193 subscribeList: () => Stream.succeed({ tasks: [] }),
194 upsert: () => Effect.die("ScheduledTaskService.upsert is unused in this test"),
195 setEnabled: () => Effect.die("ScheduledTaskService.setEnabled is unused in this test"),
196 delete: () => Effect.die("ScheduledTaskService.delete is unused in this test"),
197 deleteForThread: () => Effect.die("unused in this test"),
198 moveThreadTasks: () => Effect.die("unused in this test"),
199 runNow: () => Effect.die("ScheduledTaskService.runNow is unused in this test"),
200 rotateWebhookToken: () => Effect.die("unused in this test"),
201 listWebhookDeliveries: () => Effect.die("unused in this test"),
202 getWebhookDelivery: () => Effect.die("unused in this test"),
203 triggerWebhook: () => Effect.die("unused in this test"),
204 }),
205 );
206
207 describe("orchestrator MCP toolkit", () => {
208 it.live.each([
209 { label: "distinct", result: queuedFollowupResult, latestSummary: queuedFollowupResult },
210 { label: "identical", result: delegatedResult, latestSummary: null },
211 { label: "emoji", result: "😀", latestSummary: "😀" },
212 { label: "long", result: longFollowupResult, latestSummary: longFollowupResult },
213 ])("reports $label child results", ({ result, latestSummary }) =>
214 Effect.gen(function* () {
215 const cwd = yield* checkpointWorkspace("delegated-task-status");
216 const rawTranscript = yield* readDelegatedTaskStatusTranscript(result);
217 const transcript = yield* CodexOrchestratorReplayHarness.decodeTranscript(
218 materializeReplayTranscriptWorkspace(rawTranscript, cwd),
219 );
220 const layerOrchestrator = ProviderReplayHarness.layerProviderReplay(
221 {
222 name: "delegated-task-status/codex",
223 transcript,
224 commands: [],
225 runtimePolicyOverride: { cwd },
226 },
227 CodexOrchestratorReplayHarness,
228 );
229 // SQL spans carry no bound parameters, so this records which thread each tool read.
230 const threadRecordReads: Array<{
231 readonly threadId: ThreadId;
232 readonly fields: ReadonlyArray<string>;
233 }> = [];
234 const layerOrchestration = Layer.merge(
235 layerOrchestrator,
236 Layer.effect(
237 ThreadManagementService.ThreadManagementService,
238 Effect.gen(function* () {
239 const service = yield* ThreadManagementService.ThreadManagementService;
240 return ThreadManagementService.ThreadManagementService.of({
241 ...service,
242 getThreadRecords: (threadId, fields, filter) =>
243 Effect.sync(() => threadRecordReads.push({ threadId, fields })).pipe(
244 Effect.andThen(service.getThreadRecords(threadId, fields, filter)),
245 ),
246 });
247 }),
248 ).pipe(
249 Layer.provide(
250 ThreadManagementService.layer.pipe(
251 Layer.provide(layerOrchestrator),
252 Layer.provide(ServerSettings.layerTest()),
253 Layer.provide(
254 CommandReceiptStore.layer.pipe(Layer.provide(SqlitePersistence.layerMemory)),
255 ),
256 ),
257 ),
258 ),
259 );
260 const layerProviderRegistry = ProviderRegistryMock.layer([
261 makeProviderSnapshot({
262 instanceId: codexInstanceId,
263 driver: ProviderDriverKind.make("codex"),
264 model: codexModel,
265 }),
266 ]);
267 const layerTest = layerOrchestratorToolkit.pipe(
268 Layer.provideMerge(McpHttpServer.layerInProcessMcpServer),
269 Layer.provideMerge(layerOrchestration),
270 Layer.provide(
271 CodexOrchestratorReplayHarness.makeProviderAdapterRegistryLayer(transcript).pipe(
272 Layer.provide(McpProviderSessions.layer),
273 ),
274 ),
275 Layer.provide(layerProviderRegistry),
276 Layer.provide(ServerSettings.layerTest()),
277 Layer.provide(layerUnusedScheduledTaskStub),
278 Layer.provide(Layer.mock(PeerForwarding.PeerForwarding)({})),
279 Layer.provide(Layer.mock(PeerLinkRequests.PeerLinkRequests)({})),
280 Layer.provide(Layer.mock(PeerLinks.PeerLinks)({})),
281 Layer.provide(
282 Layer.mock(ProjectService.ProjectService)({ workspaceScanDirectory: Effect.succeed }),
283 ),
284 Layer.provideMerge(
285 SecretRequests.layer.pipe(
286 Layer.provide(layerMemorySecretStore),
287 Layer.provide(Layer.mock(SecretResolver.SecretResolver)({})),
288 Layer.provide(layerOrchestration),
289 ),
290 ),
291 Layer.provide(Layer.mock(RemoteDelegation.RemoteDelegation)({})),
292 Layer.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
293 );
294
295 yield* Effect.gen(function* () {
296 const orchestrator = yield* Orchestrator.OrchestratorV2;
297 const server = yield* McpServer.McpServer;
298 const parentCreate = yield* orchestrator.dispatch({
299 type: "thread.create",
300 createdBy: "user",
301 creationSource: "web",
302 commandId: CommandId.make("command:mcp-replay-parent:create"),
303 threadId: parentThreadId,
304 projectId,
305 title: "MCP replay parent",
306 modelSelection: codexSelection,
307 runtimeMode: "full-access",
308 interactionMode: "default",
309 branch: null,
310 worktreePath: cwd,
311 });
312 yield* orchestrator.dispatch({
313 type: "message.dispatch",
314 createdBy: "user",
315 creationSource: "web",
316 commandId: CommandId.make("command:mcp-replay-parent:start"),
317 threadId: parentThreadId,
318 messageId: MessageId.make("message:mcp-replay-parent:start"),
319 text: parentPrompt,
320 attachments: [],
321 modelSelection: codexSelection,
322 dispatchMode: { type: "start_immediately" },
323 });
324 yield* orchestrator
325 .streamStoredEventsFrom({
326 threadId: parentThreadId,
327 afterSequence: parentCreate.sequence,
328 })
329 .pipe(
330 Stream.filter(
331 (stored) =>
332 stored.event.type === "provider-turn.updated" &&
333 stored.event.payload.status === "running",
334 ),
335 Stream.runHead,
336 Effect.flatMap(
337 Option.match({
338 onNone: () => Effect.die("Parent provider turn did not start."),
339 onSome: () => Effect.void,
340 }),
341 ),
342 );
343
344 const invocation: McpInvocationContext.McpInvocationScope = {
345 environmentId: EnvironmentId.make("environment:mcp-replay"),
346 requestNamespace: "mcp-provider-session-replay-parent",
347 thread: {
348 threadId: parentThreadId,
349 providerSessionId: "mcp-provider-session-replay-parent",
350 providerInstanceId: codexInstanceId,
351 },
352 client: undefined,
353 capabilities: new Set(["orchestration"]),
354 issuedAt: 1,
355 };
356 const invoke = (name: string, args: Record<string, unknown>, scope = invocation) =>
357 server
358 .callTool({ name, arguments: args })
359 .pipe(
360 Effect.provideService(McpInvocationContext.McpInvocationContext, scope),
361 Effect.provideService(McpSchema.McpServerClient, client),
362 );
363
364 const delegationStartSequence = yield* orchestrator.getThreadEventSequence(parentThreadId);
365 const delegatedCall = yield* invoke("delegate_task", {
366 task: delegatedPrompt,
367 target: {
368 providerInstanceId: codexInstanceId,
369 model: codexModel,
370 },
371 mode: "async",
372 clientRequestId: "delegate-codex-replay-1",
373 });
374 const delegatedStart = yield* decodeDelegateTaskResult(
375 delegatedCall.structuredContent,
376 ).pipe(Effect.orDie);
377 expect(delegatedStart.childRunId).not.toBeNull();
378 yield* orchestrator
379 .streamStoredEventsFrom({
380 threadId: parentThreadId,
381 afterSequence: delegationStartSequence,
382 })
383 .pipe(
384 Stream.filter(
385 (stored) =>
386 stored.event.type === "context-transfer.created" &&
387 stored.event.payload.type === "subagent_result" &&
388 stored.event.payload.sourceThreadId === delegatedStart.childThreadId &&
389 stored.event.payload.sourcePoint.runId === delegatedStart.childRunId,
390 ),
391 Stream.runHead,
392 Effect.flatMap(
393 Option.match({
394 onNone: () => Effect.die("Delegated result transfer was not created."),
395 onSome: () => Effect.void,
396 }),
397 ),
398 );
399 const delegatedStatusCall = yield* invoke("task_status", {
400 taskId: delegatedStart.taskId,
401 });
402 const delegated = yield* decodeDelegateTaskResult(
403 delegatedStatusCall.structuredContent,
404 ).pipe(Effect.orDie);
405 expect(delegated).toMatchObject({
406 status: "completed",
407 summary: delegatedResult,
408 providerInstanceId: codexInstanceId,
409 hasPendingChildRuns: false,
410 latestTerminalRunId: delegated.childRunId,
411 latestTerminalStatus: "completed",
412 latestTerminalSummary: null,
413 latestTerminalResultContextTransferId: null,
414 });
415 expect(delegated.resultContextTransferId).not.toBeNull();
416
417 const delegatedChild = yield* orchestrator.getThreadProjection(
418 localChild(delegated.childThreadId),
419 );
420 expect(delegatedChild.thread.lineage.relationshipToParent).toBe("subagent");
421 expect(isProviderNativeSubagentThread(delegatedChild.thread)).toBe(false);
422 const followupStartSequence = yield* orchestrator.getThreadEventSequence(
423 localChild(delegated.childThreadId),
424 );
425 const runningFollowupCall = yield* invoke("t3_thread_send", {
426 threadId: localChild(delegated.childThreadId),
427 message: cancellationPrompt,
428 clientRequestId: "delegated-child-replay-running-1",
429 });
430 const runningFollowup = yield* decodeThreadSendResult(
431 runningFollowupCall.structuredContent,
432 ).pipe(Effect.orDie);
433 yield* orchestrator
434 .streamStoredEventsFrom({
435 threadId: localChild(delegated.childThreadId),
436 afterSequence: followupStartSequence,
437 })
438 .pipe(
439 Stream.filter(
440 (stored) =>
441 stored.event.type === "provider-turn.updated" &&
442 stored.event.payload.status === "running",
443 ),
444 Stream.runHead,
445 Effect.flatMap(
446 Option.match({
447 onNone: () => Effect.die("Follow-up provider turn did not start."),
448 onSome: () => Effect.void,
449 }),
450 ),
451 );
452
453 const queuedFollowupCall = yield* invoke("t3_thread_send", {
454 threadId: localChild(delegated.childThreadId),
455 message: queuedFollowupPrompt,
456 mode: "queue",
457 clientRequestId: "delegated-child-replay-queued-1",
458 });
459 const queuedFollowup = yield* decodeThreadSendResult(
460 queuedFollowupCall.structuredContent,
461 ).pipe(Effect.orDie);
462 expect(queuedFollowup).toMatchObject({
463 status: "queued",
464 delivery: "queued",
465 });
466
467 const pendingProjection = yield* orchestrator.getThreadProjection(
468 localChild(delegated.childThreadId),
469 );
470 const followupTasks = (yield* orchestrator.getThreadProjection(
471 parentThreadId,
472 )).subagents.filter(
473 (task) => task.childThreadId === delegated.childThreadId && task.id !== delegated.taskId,
474 );
475 expect(followupTasks).toHaveLength(2);
476 expect(followupTasks.every((task) => task.result === null)).toBe(true);
477 expect(followupTasks.map((task) => task.id)).toEqual([
478 runningFollowup.taskId,
479 queuedFollowup.taskId,
480 ]);
481 expect(pendingProjection.runs.find((run) => run.id === delegated.childRunId)?.status).toBe(
482 "completed",
483 );
484 expect(pendingProjection.runs.find((run) => run.id === runningFollowup.runId)?.status).toBe(
485 "running",
486 );
487 expect(pendingProjection.runs.find((run) => run.id === queuedFollowup.runId)?.status).toBe(
488 "queued",
489 );
490 expect(
491 (yield* orchestrator.getThreadProjection(parentThreadId)).runs.some(
492 (run) => run.status === "running",
493 ),
494 ).toBe(true);
495
496 const pendingStatusCall = yield* invoke("task_status", {
497 taskId: delegated.taskId,
498 });
499 const pendingStatus = yield* decodeDelegateTaskResult(
500 pendingStatusCall.structuredContent,
501 ).pipe(Effect.orDie);
502 expect(pendingStatus).toMatchObject({
503 childRunId: delegated.childRunId,
504 status: "completed",
505 summary: delegatedResult,
506 resultContextTransferId: delegated.resultContextTransferId,
507 hasPendingChildRuns: true,
508 latestTerminalRunId: delegated.childRunId,
509 latestTerminalStatus: "completed",
510 latestTerminalSummary: null,
511 latestTerminalResultContextTransferId: null,
512 });
513
514 const finalSequence = yield* orchestrator.getThreadEventSequence(
515 localChild(delegated.childThreadId),
516 );
517 const interruptCall = yield* invoke("t3_thread_interrupt", {
518 threadId: localChild(delegated.childThreadId),
519 runId: runningFollowup.runId,
520 reason: "Allow the queued replay follow-up to run.",
521 clientRequestId: "interrupt-delegated-child-replay-1",
522 });
523 const interrupt = yield* decodeThreadInterruptResult(interruptCall.structuredContent).pipe(
524 Effect.orDie,
525 );
526 expect(interrupt).toMatchObject({
527 runId: runningFollowup.runId,
528 status: "interrupt_requested",
529 });
530 yield* orchestrator
531 .streamStoredEventsFrom({
532 threadId: localChild(delegated.childThreadId),
533 afterSequence: finalSequence,
534 })
535 .pipe(
536 Stream.filter(
537 (stored) =>
538 stored.event.type === "run.updated" &&
539 stored.event.payload.id === queuedFollowup.runId &&
540 stored.event.payload.status === "completed",
541 ),
542 Stream.runHead,
543 Effect.flatMap(
544 Option.match({
545 onNone: () => Effect.die("Queued follow-up did not complete."),
546 onSome: () => Effect.void,
547 }),
548 ),
549 );
550
551 const finalProjection = yield* orchestrator.getThreadProjection(
552 localChild(delegated.childThreadId),
553 );
554 expect(finalProjection.runs.find((run) => run.id === runningFollowup.runId)?.status).toBe(
555 "interrupted",
556 );
557 expect(finalProjection.runs.find((run) => run.id === queuedFollowup.runId)?.status).toBe(
558 "completed",
559 );
560 expect(
561 finalProjection.turnItems.find(
562 (item) => item.runId === runningFollowup.runId && item.type === "run_interrupt_result",
563 ),
564 ).toMatchObject({
565 message: "Stopped by an agent: Allow the queued replay follow-up to run.",
566 });
567 yield* orchestrator
568 .streamStoredEventsFrom({
569 threadId: parentThreadId,
570 afterSequence: finalSequence,
571 })
572 .pipe(
573 Stream.filter(
574 (stored) =>
575 stored.event.type === "subagent.updated" &&
576 stored.event.payload.id === followupTasks[1]!.id &&
577 stored.event.payload.status === "completed",
578 ),
579 Stream.runHead,
580 Effect.flatMap(
581 Option.match({
582 onNone: () => Effect.die("Follow-up task did not settle."),
583 onSome: () => Effect.void,
584 }),
585 ),
586 );
587 const finishedParent = yield* orchestrator.getThreadProjection(parentThreadId);
588 expect(
589 finishedParent.subagents.find((task) => task.id === followupTasks[0]!.id)?.status,
590 ).toBe("interrupted");
591 expect(
592 finishedParent.subagents.find((task) => task.id === followupTasks[1]!.id),
593 ).toMatchObject({
594 status: "completed",
595 result,
596 });
597 expect(
598 finishedParent.contextTransfers.filter(
599 (transfer) =>
600 transfer.type === "subagent_result" &&
601 transfer.sourceThreadId === delegated.childThreadId,
602 ),
603 ).toHaveLength(3);
604 expect(
605 finishedParent.subagents.find((task) => task.id === followupTasks[1]!.id)
606 ?.completionDelivery?.state,
607 ).toBe("claimed");
608 const finalStatusCall = yield* invoke("task_status", {
609 taskId: delegated.taskId,
610 });
611 const finalStatus = yield* decodeDelegateTaskResult(finalStatusCall.structuredContent).pipe(
612 Effect.orDie,
613 );
614 expect(finalStatus).toMatchObject({
615 childRunId: delegated.childRunId,
616 status: "completed",
617 summary: delegatedResult,
618 resultContextTransferId: delegated.resultContextTransferId,
619 hasPendingChildRuns: false,
620 latestTerminalRunId: queuedFollowup.runId,
621 latestTerminalStatus: "completed",
622 latestTerminalSummary: latestSummary,
623 });
624 const followupTransfer = finishedParent.contextTransfers.find(
625 (transfer) =>
626 transfer.type === "subagent_result" &&
627 transfer.sourcePoint.runId === queuedFollowup.runId,
628 );
629 expect(followupTransfer).toBeDefined();
630 expect(finalStatus.latestTerminalResultContextTransferId).toBe(followupTransfer?.id);
631 expect(finalStatus.latestTerminalResultContextTransferId).not.toBe(
632 delegated.resultContextTransferId,
633 );
634 const transferReads: Array<string> = [];
635 const messageReads: Array<string> = [];
636 const runReads: Array<string> = [];
637 const projectionTableReads: Array<string> = [];
638 const acknowledgementReads: Array<string> = [];
639 const tracer = Tracer.make({
640 span(options) {
641 const span = new Tracer.NativeSpan(options);
642 const end = span.end.bind(span);
643 span.end = (endTime, exit) => {
644 end(endTime, exit);
645 const query = span.attributes.get("db.query.text");
646 if (typeof query !== "string") return;
647 let parent = Option.getOrUndefined(span.parent);
648 while (parent?._tag === "Span") {
649 if (
650 parent.name === "Orchestrator.dispatchDelegatedTaskCompletionDeliveryResolution"
651 ) {
652 acknowledgementReads.push(query);
653 break;
654 }
655 parent = Option.getOrUndefined(parent.parent);
656 }
657 for (const [, table] of query.matchAll(/FROM orchestration_v2_projection_(\w+)/gi)) {
658 projectionTableReads.push(table!);
659 }
660 if (/SELECT[\s\S]*FROM orchestration_v2_projection_context_transfers/i.test(query)) {
661 transferReads.push(query);
662 }
663 if (/SELECT\s+payload_json\s+FROM orchestration_v2_projection_runs/i.test(query)) {
664 runReads.push(query);
665 }
666 if (
667 /SELECT\s+payload_json\s+FROM orchestration_v2_projection_messages/i.test(query)
668 ) {
669 messageReads.push(query);
670 }
671 };
672 return span;
673 },
674 });
675 const wait = yield* invoke(
676 "t3_thread_wait",
677 { threadId: delegated.childThreadId, runId: queuedFollowup.runId },
678 { ...invocation, thread: undefined },
679 ).pipe(Effect.withTracer(tracer));
680 expect(wait.isError).not.toBe(true);
681 const expectedWait = {
682 threadId: delegated.childThreadId,
683 runId: queuedFollowup.runId,
684 status: "completed",
685 timedOut: false,
686 };
687 expect(wait.structuredContent).toEqual(expectedWait);
688 expect(messageReads).toEqual([]);
689 expect(transferReads).toHaveLength(0);
690 const settledWait = yield* invoke(
691 "t3_thread_wait",
692 {
693 threadId: delegated.childThreadId,
694 runId: queuedFollowup.runId,
695 untilDelegatedWorkSettled: true,
696 },
697 { ...invocation, thread: undefined },
698 ).pipe(Effect.withTracer(tracer));
699 expect(settledWait.isError).not.toBe(true);
700 expect(settledWait.structuredContent).toMatchObject({
701 ...expectedWait,
702 resultRun: { runId: queuedFollowup.runId, status: "completed" },
703 });
704 expect(messageReads.length).toBeGreaterThan(0);
705 expect(
706 messageReads.filter((query) => query.includes("$.notification.source.kind")),
707 ).toHaveLength(1);
708 // The orchestrator's restart-continuation guard still reads its own records.
709 expect(
710 messageReads.filter((query) => !query.includes("$.notification.source.kind")),
711 ).toHaveLength(1);
712 const parentlessRead = yield* invoke(
713 "t3_thread_read",
714 {
715 threadId: delegated.childThreadId,
716 limit: 100,
717 maxCharsPerItem: result === "😀" ? 1 : 50_000,
718 },
719 { ...invocation, thread: undefined },
720 ).pipe(Effect.withTracer(tracer));
721 expect(parentlessRead.isError).not.toBe(true);
722 expect(transferReads).toHaveLength(0);
723 const afterParentlessRead = yield* orchestrator.getThreadProjection(parentThreadId);
724 expect(
725 afterParentlessRead.subagents.find((task) => task.id === queuedFollowup.taskId)
726 ?.completionDelivery?.state,
727 ).toBe("claimed");
728
729 const read = yield* invoke("t3_thread_read", {
730 threadId: delegated.childThreadId,
731 limit: 100,
732 ...(result === "😀" ? { maxCharsPerItem: 1 } : {}),
733 }).pipe(Effect.withTracer(tracer));
734 expect(read.isError).not.toBe(true);
735 expect(transferReads.length).toBeGreaterThan(0);
736 const firstPage = yield* decodeThreadRead(read.structuredContent);
737 const finalItem = firstPage.items.find((item) => item.text === result.slice(0, 500));
738 expect(finalItem).toBeDefined();
739 if (result.length > 500) {
740 yield* invoke("t3_thread_read", {
741 threadId: delegated.childThreadId,
742 itemId: finalItem!.itemId,
743 textOffset: result.length,
744 });
745 } else {
746 expect(read.structuredContent).toEqual(parentlessRead.structuredContent);
747 }
748 let text = finalItem!.text ?? "";
749 let nextTextOffset = finalItem?.nextTextOffset ?? null;
750 while (nextTextOffset !== null) {
751 const beforeContinuation = yield* orchestrator.getThreadProjection(parentThreadId);
752 expect(
753 beforeContinuation.subagents.find((task) => task.id === queuedFollowup.taskId)
754 ?.completionDelivery?.state,
755 ).toBe("claimed");
756 const continuation = yield* invoke("t3_thread_read", {
757 threadId: delegated.childThreadId,
758 itemId: finalItem!.itemId,
759 textOffset: nextTextOffset,
760 maxCharsPerItem: 50_000,
761 }).pipe(Effect.withTracer(tracer));
762 const nextPage = yield* decodeThreadRead(continuation.structuredContent);
763 text += nextPage.items[0]?.text ?? "";
764 nextTextOffset = nextPage.items[0]?.nextTextOffset ?? null;
765 }
766 expect(text).toBe(result);
767 // The acknowledgement reads the task and its spawning run by id, not the parent's history.
768 expect(acknowledgementReads.length).toBeGreaterThan(0);
769 expect(
770 acknowledgementReads.filter(
771 (query) =>
772 /FROM orchestration_v2_projection_(nodes|run_attempts)\b/.test(query) ||
773 (/FROM orchestration_v2_projection_runs\b/.test(query) &&
774 !query.includes("AND run_id IN")) ||
775 (/FROM orchestration_v2_projection_subagents\b/.test(query) &&
776 !query.includes("AND subagent_id IN")),
777 ),
778 ).toEqual([]);
779 const afterRead = yield* orchestrator.getThreadProjection(parentThreadId);
780 expect(
781 afterRead.subagents.find((task) => task.id === queuedFollowup.taskId)?.completionDelivery
782 ?.state,
783 ).toBe("acknowledged");
784
785 const messageReadsBeforeCapabilities = messageReads.length;
786 const tableReadsBeforeCapabilities = projectionTableReads.length;
787 const capabilities = yield* invoke("orchestrator_capabilities", {}).pipe(
788 Effect.withTracer(tracer),
789 );
790 expect(capabilities.isError).not.toBe(true);
791 expect(messageReads).toHaveLength(messageReadsBeforeCapabilities);
792 // The caller check reads only the thread row, never its history.
793 expect(new Set(projectionTableReads.slice(tableReadsBeforeCapabilities))).toEqual(
794 new Set(["threads"]),
795 );
796 const runReadsBeforeStatus = runReads.length;
797 const transferReadsBeforeStatus = transferReads.length;
798 const threadRecordReadsBeforeStatus = threadRecordReads.length;
799 const statusAgain = yield* invoke("task_status", { taskId: delegated.taskId }).pipe(
800 Effect.withTracer(tracer),
801 );
802 expect(statusAgain.isError).not.toBe(true);
803 // A task wait reads result transfers and runs from the child; the parent's stay unread.
804 expect(runReads).toHaveLength(runReadsBeforeStatus + 1);
805 expect(transferReads).toHaveLength(transferReadsBeforeStatus + 1);
806 expect(
807 threadRecordReads
808 .slice(threadRecordReadsBeforeStatus)
809 .filter(({ fields }) => fields.includes("runs") || fields.includes("contextTransfers"))
810 .map(({ threadId }) => threadId),
811 ).toEqual([delegated.childThreadId]);
812 }).pipe(Effect.provide(layerTest));
813 }),
814 );
815 });