Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

CodexCollabRuntime.integration.test.ts

768 lines28.4 KB

1/**
2 * Runtime-level collab regression: boots the REAL CodexSessionRuntime against
3 * a scripted mock app-server peer that replays the captured multi-agent wire
4 * sequence (codexMultiAgentWire.json) plus the shapes the capture alone can't
5 * script (receiver-turn bookkeeping via collabAgentToolCall, child terminal
6 * lifecycle, approval pass-through). This is the layer the pure routing-table
7 * test can't reach: ordering between the legacy receiver-turn suppressor and
8 * v2 interception, registration state, and synthetic event emission.
9 */
10// @effect-diagnostics nodeBuiltinImport:off
11import * as NodeFS from "node:fs";
12import * as NodeOS from "node:os";
13import * as NodePath from "node:path";
14​
15import * as NodeServices from "@effect/platform-node/NodeServices";
16import { it } from "@effect/vitest";
17import { type ProviderApprovalDecision, type ProviderEvent, ThreadId } from "@t3tools/contracts";
18import * as Deferred from "effect/Deferred";
19import * as Effect from "effect/Effect";
20import * as Fiber from "effect/Fiber";
21import * as Schema from "effect/Schema";
22import * as Stream from "effect/Stream";
23import { assert, describe } from "vite-plus/test";
24​
25import wireFixture from "../testFixtures/codexMultiAgentWire.json" with { type: "json" };
26import { makeCodexSessionRuntime } from "./CodexSessionRuntime.ts";
27import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
28​
29const ROOT = wireFixture.rootThreadId;
30const [CHILD_A, CHILD_B] = wireFixture.childThreadIds as [string, string];
31const MEMORY = "memory-consolidation-thread";
32const decodeMcpElicitationResponse = Schema.decodeUnknownEffect(
33 Schema.fromJsonString(
34 Schema.Struct({
35 id: Schema.Number,
36 result: Schema.Unknown,
37 }),
38 ),
39);
40​
41/**
42 * The captured sequence, extended with the shapes the live capture didn't
43 * include: a collabAgentToolCall with receiverThreadIds (feeds the legacy
44 * receiver-turn map, so ordering vs. v2 interception is exercised), child
45 * terminal lifecycle, and a serverRequest/resolved addressed to a child
46 * (must pass through to the parent path, not vanish).
47 */
48function buildScript() {
49 const captured = wireFixture.notifications;
50 const extras = [
51 {
52 method: "item/completed",
53 params: {
54 threadId: ROOT,
55 item: {
56 type: "collabAgentToolCall",
57 id: "call_fixture_wait",
58 tool: "wait",
59 status: "completed",
60 senderThreadId: ROOT,
61 receiverThreadIds: [CHILD_A, CHILD_B],
62 },
63 },
64 },
65 // Child terminal lifecycle AFTER the receiver map knows the children —
66 // pre-fix, the legacy suppressor dropped these before interception saw
67 // them, so no synthetic agent events were emitted.
68 {
69 method: "turn/completed",
70 params: {
71 threadId: CHILD_A,
72 turn: { id: `${CHILD_A}-turn-1`, status: "completed", items: [] },
73 },
74 },
75 { method: "thread/closed", params: { threadId: CHILD_B } },
76 // Parent-owned traffic addressed to a child conversation: must reach the
77 // parent path (approval correlation cleanup), not be swallowed.
78 { method: "serverRequest/resolved", params: { threadId: CHILD_A, requestId: "req-1" } },
79 ];
80 return {
81 rootThreadId: ROOT,
82 notifications: [...captured.filter((entry) => entry.method !== "turn/completed"), ...extras],
83 };
85​
86function capturedStartedActivity(childId = CHILD_A) {
87 const captured = wireFixture.notifications.find((entry) => {
88 const item = (entry.params as { item?: { type?: string; kind?: string } }).item;
89 return item?.type === "subAgentActivity" && item.kind === "started";
90 });
91 assert.isDefined(captured);
92 return {
93 ...captured,
94 params: {
95 ...captured.params,
96 item: {
97 ...captured.params.item,
98 agentThreadId: childId,
99 agentPath: "/root/model-check",
100 },
101 },
102 };
104​
105function capturedSpawnedThread(childId = CHILD_A) {
106 const captured = wireFixture.notifications.find((entry) => entry.method === "thread/started");
107 assert.isDefined(captured);
108 return {
109 ...captured,
110 params: {
111 thread: {
112 ...captured.params.thread,
113 id: childId,
114 sessionId: childId,
115 parentThreadId: ROOT,
116 agentNickname: "model-check",
117 agentRole: "verifier",
118 source: {
119 subAgent: {
120 thread_spawn: {
121 agent_nickname: "model-check",
122 agent_path: "/root/model-check",
123 agent_role: "verifier",
124 depth: 1,
125 parent_thread_id: ROOT,
126 },
127 },
128 },
129 },
130 },
131 };
133​
134function childSettings(threadId: string, model: string, effort: string) {
135 return {
136 method: "thread/settings/updated",
137 params: {
138 threadId,
139 threadSettings: {
140 approvalPolicy: "on-request",
141 approvalsReviewer: "auto_review",
142 collaborationMode: { mode: "default", settings: { model } },
143 cwd: "/workspace/repo",
144 effort,
145 model,
146 modelProvider: "openai",
147 sandboxPolicy: { type: "dangerFullAccess" },
148 },
149 },
150 };
152​
153function readRecordedRequests() {
154 return NodeFS.readFileSync(`${scriptPath}.requests`, "utf8")
155 .trim()
156 .split("\n")
157 .filter((line) => line.length > 0)
158 .map((line) => JSON.parse(line) as { method: string; params: Record<string, unknown> });
160​
161const scriptPath = NodePath.join(import.meta.dirname, "../testFixtures/.collab-script.json");
162// Windows cannot run the shebang wrapper; the .cmd sibling does the same job.
163const peerPath = NodePath.join(
164 import.meta.dirname,
165 `../testFixtures/codexCollabMockPeer.${HostProcessPlatform.defaultValue() === "win32" ? "cmd" : "sh"}`,
166);
167​
168describe("CodexSessionRuntime collab integration", () => {
169 it.effect("looks up child model metadata once after activity registration", () =>
170 Effect.gen(function* () {
171 const script = {
172 rootThreadId: ROOT,
173 recordRequests: true,
174 notifications: [
175 capturedStartedActivity(),
176 capturedStartedActivity(),
177 {
178 ...capturedStartedActivity(CHILD_B),
179 params: {
180 ...capturedStartedActivity(CHILD_B).params,
181 item: { ...capturedStartedActivity(CHILD_B).params.item, kind: "interacted" },
182 },
183 },
184 { method: "thread/closed", params: { threadId: CHILD_B } },
185 capturedSpawnedThread(ROOT),
186 ],
187 childResumeSnapshots: {
188 [CHILD_A]: { model: "gpt-5.6-luna", reasoningEffort: "low" },
189 },
190 };
191 // @effect-diagnostics-next-line preferSchemaOverJson:off
192 NodeFS.writeFileSync(scriptPath, JSON.stringify(script), "utf8");
193 NodeFS.rmSync(`${scriptPath}.requests`, { force: true });
194 yield* Effect.addFinalizer(() =>
195 Effect.sync(() => {
196 NodeFS.rmSync(scriptPath, { force: true });
197 NodeFS.rmSync(`${scriptPath}.requests`, { force: true });
198 }),
199 );
200​
201 const runtime = yield* makeCodexSessionRuntime({
202 threadId: ThreadId.make("thread-collab-model-activity"),
203 binaryPath: peerPath,
204 cwd: NodeOS.tmpdir(),
205 runtimeMode: "full-access",
206 environment: { ...process.env, T3_CODEX_COLLAB_SCRIPT: scriptPath },
207 });
208 const metadataFiber = yield* runtime.events.pipe(
209 Stream.filter(
210 (event) =>
211 event.method === "collabAgent/metadataUpdated" &&
212 (event.payload as { agentThreadId?: string }).agentThreadId === CHILD_A,
213 ),
214 Stream.take(1),
215 Stream.runCollect,
216 Effect.forkScoped,
217 );
218​
219 const session = yield* runtime.start();
220 assert.equal(session.model, "gpt-5.6-sol");
221 yield* runtime.sendTurn({ input: "start one child" });
222 const metadataEvents = Array.from(yield* Fiber.join(metadataFiber));
223 assert.deepInclude(metadataEvents[0]?.payload, {
224 agentThreadId: CHILD_A,
225 model: "gpt-5.6-luna",
226 effort: "low",
227 });
228 assert.deepEqual(readRecordedRequests(), [
229 {
230 method: "thread/resume",
231 params: { threadId: CHILD_A, excludeTurns: true },
232 },
233 ]);
234​
235 yield* runtime.close;
236 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
237 );
238​
239 it.effect("keeps child settings and reroutes newer than the resume snapshot", () =>
240 Effect.gen(function* () {
241 const statusChanged = wireFixture.notifications.find(
242 (entry) =>
243 entry.method === "thread/status/changed" &&
244 (entry.params as { threadId?: string }).threadId === CHILD_A,
245 );
246 assert.isDefined(statusChanged);
247 const script = {
248 rootThreadId: ROOT,
249 recordRequests: true,
250 notifications: [
251 childSettings(CHILD_A, "child-before", "medium"),
252 capturedSpawnedThread(),
253 childSettings(CHILD_A, "child-after", "high"),
254 {
255 method: "model/rerouted",
256 params: {
257 threadId: CHILD_A,
258 turnId: `${CHILD_A}-turn`,
259 fromModel: "child-after",
260 toModel: "child-rerouted",
261 reason: "highRiskCyberActivity",
262 },
263 },
264 {
265 method: "model/rerouted",
266 params: {
267 threadId: ROOT,
268 turnId: `${ROOT}-turn`,
269 fromModel: "gpt-5.6-sol",
270 toModel: "root-rerouted",
271 reason: "highRiskCyberActivity",
272 },
273 },
274 ],
275 childResumeSnapshots: {
276 [CHILD_A]: {
277 model: "stale-snapshot",
278 reasoningEffort: "low",
279 notifications: [statusChanged],
280 },
281 },
282 };
283 // @effect-diagnostics-next-line preferSchemaOverJson:off
284 NodeFS.writeFileSync(scriptPath, JSON.stringify(script), "utf8");
285 NodeFS.rmSync(`${scriptPath}.requests`, { force: true });
286 yield* Effect.addFinalizer(() =>
287 Effect.sync(() => {
288 NodeFS.rmSync(scriptPath, { force: true });
289 NodeFS.rmSync(`${scriptPath}.requests`, { force: true });
290 }),
291 );
292​
293 const runtime = yield* makeCodexSessionRuntime({
294 threadId: ThreadId.make("thread-collab-model-spawn"),
295 binaryPath: peerPath,
296 cwd: NodeOS.tmpdir(),
297 runtimeMode: "full-access",
298 environment: { ...process.env, T3_CODEX_COLLAB_SCRIPT: scriptPath },
299 });
300 const eventsFiber = yield* runtime.events.pipe(
301 Stream.takeUntil(
302 (event) =>
303 event.method === "collabAgent/statusChanged" &&
304 (event.payload as { agentThreadId?: string }).agentThreadId === CHILD_A,
305 ),
306 Stream.runCollect,
307 Effect.forkScoped,
308 );
309​
310 yield* runtime.start();
311 yield* runtime.sendTurn({ input: "start one spawned child" });
312 const events = Array.from(yield* Fiber.join(eventsFiber));
313 const started = events.find((event) => event.method === "collabAgent/started");
314 assert.deepInclude(started?.payload, {
315 agentThreadId: CHILD_A,
316 model: "child-before",
317 effort: "medium",
318 });
319 const childStatus = events.find((event) => event.method === "collabAgent/statusChanged");
320 assert.deepInclude(childStatus?.payload, {
321 agentThreadId: CHILD_A,
322 model: "child-rerouted",
323 effort: "high",
324 });
325 assert.isTrue(
326 events.some(
327 (event) =>
328 event.method === "model/rerouted" &&
329 (event.payload as { threadId?: string }).threadId === ROOT,
330 ),
331 "the root reroute must stay on the parent path",
332 );
333 assert.isFalse(
334 events.some(
335 (event) =>
336 (event.method === "thread/settings/updated" || event.method === "model/rerouted") &&
337 (event.payload as { threadId?: string }).threadId === CHILD_A,
338 ),
339 "child metadata notifications must not leak to the parent path",
340 );
341 assert.equal(readRecordedRequests().length, 1);
342​
343 yield* runtime.close;
344 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
345 );
346​
347 it.effect("does not delay the parent turn when the child lookup fails", () =>
348 Effect.gen(function* () {
349 yield* Effect.addFinalizer(() =>
350 Effect.sync(() => {
351 NodeFS.rmSync(scriptPath, { force: true });
352 NodeFS.rmSync(`${scriptPath}.requests`, { force: true });
353 }),
354 );
355 for (const [name, childSnapshot] of [
356 ["hang", { hang: true }],
357 ["error", { error: "child unavailable" }],
358 ] as const) {
359 yield* Effect.gen(function* () {
360 const marker = `lookup-${name}`;
361 const script = {
362 rootThreadId: ROOT,
363 recordRequests: true,
364 resumeRequestMarker: marker,
365 notifications: [capturedStartedActivity()],
366 childResumeSnapshots: { [CHILD_A]: childSnapshot },
367 };
368 // @effect-diagnostics-next-line preferSchemaOverJson:off
369 NodeFS.writeFileSync(scriptPath, JSON.stringify(script), "utf8");
370 NodeFS.rmSync(`${scriptPath}.requests`, { force: true });
371​
372 const runtime = yield* makeCodexSessionRuntime({
373 threadId: ThreadId.make(`thread-collab-model-${name}`),
374 binaryPath: peerPath,
375 cwd: NodeOS.tmpdir(),
376 runtimeMode: "full-access",
377 environment: { ...process.env, T3_CODEX_COLLAB_SCRIPT: scriptPath },
378 });
379 const eventsFiber = yield* runtime.events.pipe(
380 Stream.takeUntil(
381 (event) =>
382 event.method === "serverRequest/resolved" &&
383 (event.payload as { requestId?: string }).requestId === marker,
384 ),
385 Stream.runCollect,
386 Effect.forkScoped,
387 );
388​
389 yield* runtime.start();
390 yield* runtime.sendTurn({ input: "finish without child metadata" });
391 const events = Array.from(yield* Fiber.join(eventsFiber));
392 assert.isTrue(events.some((event) => event.method === "turn/completed"));
393 assert.equal(readRecordedRequests().length, 1);
394​
395 yield* runtime.close;
396 NodeFS.rmSync(scriptPath, { force: true });
397 NodeFS.rmSync(`${scriptPath}.requests`, { force: true });
398 }).pipe(Effect.scoped);
399 }
400 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
401 );
402​
403 it.effect("replays the captured fan-out into synthetic agent events without child leaks", () =>
404 Effect.gen(function* () {
405 // @effect-diagnostics-next-line preferSchemaOverJson:off
406 NodeFS.writeFileSync(scriptPath, JSON.stringify(buildScript()), "utf8");
407 yield* Effect.addFinalizer(() =>
408 Effect.sync(() => NodeFS.rmSync(scriptPath, { force: true })),
409 );
410​
411 const runtime = yield* makeCodexSessionRuntime({
412 threadId: ThreadId.make("thread-collab-integration"),
413 binaryPath: peerPath,
414 cwd: NodeOS.tmpdir(),
415 runtimeMode: "full-access",
416 environment: { ...process.env, T3_CODEX_COLLAB_SCRIPT: scriptPath },
417 });
418​
419 const eventsFiber = yield* runtime.events.pipe(
420 Stream.takeUntil((event) => event.method === "turn/completed"),
421 Stream.runCollect,
422 Effect.forkScoped,
423 );
424​
425 yield* runtime.start();
426 yield* runtime.sendTurn({ input: "fan out" });
427​
428 const events = Array.from(yield* Fiber.join(eventsFiber));
429 const methods = events.map((event) => event.method);
430​
431 // Children registered from subAgentActivity become synthetic agent
432 // lifecycle — including terminal rows that arrive AFTER the receiver
433 // map knows them (the ordering this test exists to pin).
434 assert.include(methods, "collabAgent/activity");
435 assert.include(methods, "collabAgent/turnCompleted");
436 assert.include(methods, "collabAgent/closed");
437​
438 const childTurnCompleted = events.find(
439 (event) =>
440 event.method === "collabAgent/turnCompleted" &&
441 (event.payload as { agentThreadId?: string }).agentThreadId === CHILD_A,
442 );
443 assert.isDefined(childTurnCompleted, "child A's turn completion becomes an agent event");
444​
445 const childClosed = events.find(
446 (event) =>
447 event.method === "collabAgent/closed" &&
448 (event.payload as { agentThreadId?: string }).agentThreadId === CHILD_B,
449 );
450 assert.isDefined(childClosed, "child B's close becomes an agent event");
451​
452 // Parent-owned resolution passes through — not swallowed, not
453 // re-labelled as an agent event.
454 assert.include(methods, "serverRequest/resolved");
455​
456 // The root's own subAgentActivity about "/root" must NOT register the
457 // root as a child: the parent turn completion still flows.
458 assert.include(methods, "turn/completed");
459​
460 // No raw child conversation methods leak onto the parent stream.
461 const leaked = events.filter((event) => {
462 const payload = event.payload as { threadId?: string } | undefined;
463 const addressedToChild = payload?.threadId === CHILD_A || payload?.threadId === CHILD_B;
464 return addressedToChild && (event.method?.startsWith("thread/") ?? false);
465 });
466 assert.deepEqual(
467 leaked.map((event) => event.method),
468 [],
469 "child thread/* lifecycle must not appear as parent events",
470 );
471​
472 yield* runtime.close;
473 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
474 );
475​
476 // it.live: the runtime talks to a real child process; under it.effect's
477 // TestClock the internal timers freeze and the join never completes.
478 it.live("Stop interrupts every live child regardless of registration timing", () =>
479 Effect.gen(function* () {
480 // Ordering + liveness torture for stop-everything: child A's
481 // turn/started arrives BEFORE anything registers it (foreign
482 // suppression path must record the live turn); child B's arrives after
483 // registration; child A's interrupt HANGS (RPC never settles — worse
484 // than rejecting) and the bounded deadline must still deliver B's and
485 // the parent's interrupts. The turn stays open so children are live
486 // when Stop fires.
487 // Build from REAL captured rows (hand-written shapes fail notification
488 // schema validation and are silently dropped): reorder so child A's
489 // turn/started precedes its registration, and drop terminal rows so
490 // children stay live when Stop fires.
491 const byIndex = wireFixture.notifications;
492 const isTurnStarted = (entry: (typeof byIndex)[number], child: string) =>
493 entry.method === "turn/started" &&
494 (entry.params as { threadId?: string }).threadId === child;
495 const isRegistration = (entry: (typeof byIndex)[number], child: string) => {
496 const item = (entry.params as { item?: { type?: string; agentThreadId?: string } }).item;
497 return item?.type === "subAgentActivity" && item.agentThreadId === child;
498 };
499 const turnStartedA = byIndex.find((entry) => isTurnStarted(entry, CHILD_A));
500 const turnStartedB = byIndex.find((entry) => isTurnStarted(entry, CHILD_B));
501 const registrationA = byIndex.find((entry) => isRegistration(entry, CHILD_A));
502 const registrationB = byIndex.find((entry) => isRegistration(entry, CHILD_B));
503 const rootThreadStarted = byIndex.find((entry) => entry.method === "thread/started");
504 assert.isDefined(turnStartedA);
505 assert.isDefined(turnStartedB);
506 assert.isDefined(registrationA);
507 assert.isDefined(registrationB);
508 assert.isDefined(rootThreadStarted);
509 const memoryThreadStarted = {
510 ...rootThreadStarted,
511 params: {
512 thread: {
513 ...rootThreadStarted.params.thread,
514 id: MEMORY,
515 sessionId: MEMORY,
516 source: "unknown",
517 threadSource: "memory_consolidation",
518 },
519 },
520 };
521 const memoryTurnStarted = {
522 ...turnStartedA,
523 params: {
524 ...turnStartedA.params,
525 threadId: MEMORY,
526 turn: { ...turnStartedA.params.turn, id: "memory-consolidation-turn" },
527 },
528 };
529 const script = {
530 rootThreadId: ROOT,
531 holdTurnOpen: true,
532 hangInterruptFor: CHILD_A,
533 notifications: [
534 turnStartedA,
535 registrationA,
536 memoryThreadStarted,
537 memoryTurnStarted,
538 registrationB,
539 turnStartedB,
540 ],
541 };
542 // @effect-diagnostics-next-line preferSchemaOverJson:off
543 NodeFS.writeFileSync(scriptPath, JSON.stringify(script), "utf8");
544 const interruptsPath = `${scriptPath}.interrupts`;
545 NodeFS.rmSync(interruptsPath, { force: true });
546 yield* Effect.addFinalizer(() =>
547 Effect.sync(() => {
548 NodeFS.rmSync(scriptPath, { force: true });
549 NodeFS.rmSync(interruptsPath, { force: true });
550 }),
551 );
552​
553 const runtime = yield* makeCodexSessionRuntime({
554 threadId: ThreadId.make("thread-collab-stop"),
555 binaryPath: peerPath,
556 cwd: NodeOS.tmpdir(),
557 runtimeMode: "full-access",
558 environment: { ...process.env, T3_CODEX_COLLAB_SCRIPT: scriptPath },
559 });
560​
561 // Wait for both children's turnStarted signals to be processed before
562 // stopping (B via the registered-child path; A only produces live-turn
563 // bookkeeping, so key on B's synthetic event).
564 const childBStartedFiber = yield* runtime.events.pipe(
565 Stream.filter(
566 (event) =>
567 event.method === "collabAgent/turnStarted" &&
568 (event.payload as { agentThreadId?: string }).agentThreadId === CHILD_B,
569 ),
570 Stream.take(1),
571 Stream.runCollect,
572 Effect.forkScoped,
573 );
574​
575 yield* runtime.start();
576 yield* runtime.sendTurn({ input: "fan out and hang" });
577 const childBStarted = yield* Fiber.join(childBStartedFiber).pipe(
578 Effect.timeoutOption("15 seconds"),
579 );
580 assert.isTrue(childBStarted._tag === "Some", "child B turnStarted never arrived");
581​
582 // Stop everything. A's interrupt hangs forever — the bounded child
583 // deadline must expire and the parent interrupt must still be sent.
584 yield* runtime.interruptTurn();
585​
586 const parseInterruptLine = (line: string) => JSON.parse(line) as { threadId?: string };
587 const interrupted = NodeFS.readFileSync(interruptsPath, "utf8")
588 .trim()
589 .split("\n")
590 .filter((line) => line.length > 0)
591 .map(parseInterruptLine);
592 const interruptedThreads = new Set(interrupted.map((entry) => entry.threadId));
593 assert.isTrue(
594 interruptedThreads.has(CHILD_A),
595 "pre-registration child A must still receive the interrupt RPC",
596 );
597 assert.isTrue(interruptedThreads.has(CHILD_B), "registered child B must be interrupted");
598 assert.isTrue(
599 interruptedThreads.has(MEMORY),
600 "memory consolidation must be interrupted without appearing in chat",
601 );
602 assert.isTrue(interruptedThreads.has(ROOT), "parent turn must be interrupted last");
603​
604 yield* runtime.close;
605 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
606 );
607​
608 it.live("Stop targets the active turn when Codex has accepted a queued follow-up", () =>
609 Effect.gen(function* () {
610 const activeTurnId = "019fe3e8-f908-7f31-8d51-283f4a47897a";
611 const queuedTurnId = "019fe3eb-8faf-7de3-a85b-ac64c7f9c8c3";
612 const script = {
613 rootThreadId: ROOT,
614 holdTurnOpen: true,
615 onlyFirstTurnStarts: true,
616 turnIds: [activeTurnId, queuedTurnId],
617 expectedActiveTurnId: activeTurnId,
618 notifications: [],
619 };
620 // @effect-diagnostics-next-line preferSchemaOverJson:off
621 NodeFS.writeFileSync(scriptPath, JSON.stringify(script), "utf8");
622 const interruptsPath = `${scriptPath}.interrupts`;
623 NodeFS.rmSync(interruptsPath, { force: true });
624 yield* Effect.addFinalizer(() =>
625 Effect.sync(() => {
626 NodeFS.rmSync(scriptPath, { force: true });
627 NodeFS.rmSync(interruptsPath, { force: true });
628 }),
629 );
630​
631 const runtime = yield* makeCodexSessionRuntime({
632 threadId: ThreadId.make("thread-codex-queued-stop"),
633 binaryPath: peerPath,
634 cwd: NodeOS.tmpdir(),
635 runtimeMode: "full-access",
636 environment: { ...process.env, T3_CODEX_COLLAB_SCRIPT: scriptPath },
637 });
638​
639 yield* runtime.start();
640 yield* runtime.sendTurn({ input: "keep working" });
641 yield* runtime.sendTurn({ input: "queued follow-up" });
642 yield* runtime.interruptTurn();
643​
644 const interrupts = NodeFS.readFileSync(interruptsPath, "utf8")
645 .trim()
646 .split("\n")
647 .map((line) => JSON.parse(line) as { threadId?: string; turnId?: string });
648 assert.deepEqual(interrupts.at(-1), {
649 threadId: ROOT,
650 turnId: activeTurnId,
651 });
652​
653 yield* runtime.close;
654 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
655 );
656​
657 const elicitationCases = [
658 {
659 decision: "accept",
660 response: { action: "accept", content: { approval: "once" } },
661 },
662 {
663 decision: "acceptForSession",
664 response: {
665 action: "accept",
666 _meta: { persist: "session" },
667 content: { approval: "session" },
668 },
669 },
670 {
671 decision: "acceptAlways",
672 response: {
673 action: "accept",
674 _meta: { persist: "always" },
675 content: { approval: "always" },
676 },
677 },
678 { decision: "decline", response: { action: "decline" } },
679 { decision: "cancel", response: { action: "cancel" } },
680 ] satisfies ReadonlyArray<{
681 readonly decision: ProviderApprovalDecision;
682 readonly response: Record<string, unknown>;
683 }>;
684​
685 for (const { decision, response } of elicitationCases) {
686 it.live(`returns the MCP elicitation ${decision} response to Codex`, () =>
687 Effect.gen(function* () {
688 const scriptedRequest = {
689 id: 7001,
690 method: "mcpServer/elicitation/request",
691 params: {
692 mode: "form",
693 message: "Allow ChatGPT to use Safari?",
694 serverName: "computer-use",
695 threadId: ROOT,
696 turnId: wireFixture.responses.turnStart.turn.id,
697 _meta: { app_name: "Safari", persist: ["session", "always"] },
698 requestedSchema: {
699 type: "object",
700 properties: {
701 approval: {
702 type: "string",
703 enum: ["once", "session", "always"],
704 },
705 },
706 required: ["approval"],
707 },
708 },
709 };
710 const script = {
711 rootThreadId: ROOT,
712 holdTurnOpen: true,
713 completeTurnOnServerResponse: true,
714 notifications: [],
715 serverRequests: [scriptedRequest],
716 };
717 const responsesPath = `${scriptPath}.responses`;
718 // @effect-diagnostics-next-line preferSchemaOverJson:off
719 NodeFS.writeFileSync(scriptPath, JSON.stringify(script), "utf8");
720 NodeFS.rmSync(responsesPath, { force: true });
721 yield* Effect.addFinalizer(() =>
722 Effect.sync(() => {
723 NodeFS.rmSync(scriptPath, { force: true });
724 NodeFS.rmSync(responsesPath, { force: true });
725 }),
726 );
727​
728 const runtime = yield* makeCodexSessionRuntime({
729 threadId: ThreadId.make("thread-codex-mcp-elicitation"),
730 binaryPath: peerPath,
731 cwd: NodeOS.tmpdir(),
732 runtimeMode: "auto",
733 environment: { ...process.env, T3_CODEX_COLLAB_SCRIPT: scriptPath },
734 });
735 const approvalRequested = yield* Deferred.make<ProviderEvent>();
736 const turnCompleted = yield* Deferred.make<void>();
737 yield* runtime.events.pipe(
738 Stream.runForEach((event) =>
739 event.method === "mcpServer/elicitation/request"
740 ? Deferred.succeed(approvalRequested, event).pipe(Effect.asVoid)
741 : event.method === "turn/completed"
742 ? Deferred.succeed(turnCompleted, undefined).pipe(Effect.asVoid)
743 : Effect.void,
744 ),
745 Effect.forkScoped,
746 );
747​
748 yield* runtime.start();
749 yield* runtime.sendTurn({ input: "Open Safari" });
750 const approval = yield* Deferred.await(approvalRequested);
751 assert.equal(approval.requestKind, "mcp-elicitation");
752 assert.isDefined(approval.requestId);
753 if (approval.requestId === undefined) return;
754​
755 yield* runtime.respondToRequest(approval.requestId, decision);
756 yield* Deferred.await(turnCompleted);
757​
758 const recordedResponse = yield* decodeMcpElicitationResponse(
759 NodeFS.readFileSync(responsesPath, "utf8"),
760 );
761 assert.equal(recordedResponse.id, scriptedRequest.id);
762 assert.deepEqual(recordedResponse.result, response);
763​
764 yield* runtime.close;
765 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
766 );
767 }
768});