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

CodexCollabRuntime.integration.test.ts

453 lines17.7 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 NodePath from "node:path";
13​
14import * as NodeServices from "@effect/platform-node/NodeServices";
15import { it } from "@effect/vitest";
16import { type ProviderApprovalDecision, type ProviderEvent, ThreadId } from "@t3tools/contracts";
17import * as Deferred from "effect/Deferred";
18import * as Effect from "effect/Effect";
19import * as Fiber from "effect/Fiber";
20import * as Schema from "effect/Schema";
21import * as Stream from "effect/Stream";
22import { assert, describe } from "vite-plus/test";
23​
24import wireFixture from "../testFixtures/codexMultiAgentWire.json" with { type: "json" };
25import { makeCodexSessionRuntime } from "./CodexSessionRuntime.ts";
26​
27const ROOT = wireFixture.rootThreadId;
28const [CHILD_A, CHILD_B] = wireFixture.childThreadIds as [string, string];
29const MEMORY = "memory-consolidation-thread";
30const decodeMcpElicitationResponse = Schema.decodeUnknownEffect(
31 Schema.fromJsonString(
32 Schema.Struct({
33 id: Schema.Number,
34 result: Schema.Unknown,
35 }),
36 ),
37);
38​
39/**
40 * The captured sequence, extended with the shapes the live capture didn't
41 * include: a collabAgentToolCall with receiverThreadIds (feeds the legacy
42 * receiver-turn map, so ordering vs. v2 interception is exercised), child
43 * terminal lifecycle, and a serverRequest/resolved addressed to a child
44 * (must pass through to the parent path, not vanish).
45 */
46function buildScript() {
47 const captured = wireFixture.notifications;
48 const extras = [
49 {
50 method: "item/completed",
51 params: {
52 threadId: ROOT,
53 item: {
54 type: "collabAgentToolCall",
55 id: "call_fixture_wait",
56 tool: "wait",
57 status: "completed",
58 senderThreadId: ROOT,
59 receiverThreadIds: [CHILD_A, CHILD_B],
60 },
61 },
62 },
63 // Child terminal lifecycle AFTER the receiver map knows the children —
64 // pre-fix, the legacy suppressor dropped these before interception saw
65 // them, so no synthetic agent events were emitted.
66 {
67 method: "turn/completed",
68 params: {
69 threadId: CHILD_A,
70 turn: { id: `${CHILD_A}-turn-1`, status: "completed", items: [] },
71 },
72 },
73 { method: "thread/closed", params: { threadId: CHILD_B } },
74 // Parent-owned traffic addressed to a child conversation: must reach the
75 // parent path (approval correlation cleanup), not be swallowed.
76 { method: "serverRequest/resolved", params: { threadId: CHILD_A, requestId: "req-1" } },
77 ];
78 return {
79 rootThreadId: ROOT,
80 notifications: [...captured.filter((entry) => entry.method !== "turn/completed"), ...extras],
81 };
83​
84const scriptPath = NodePath.join(import.meta.dirname, "../testFixtures/.collab-script.json");
85const peerPath = NodePath.join(import.meta.dirname, "../testFixtures/codexCollabMockPeer.sh");
86​
87describe("CodexSessionRuntime collab integration", () => {
88 it.effect("replays the captured fan-out into synthetic agent events without child leaks", () =>
89 Effect.gen(function* () {
90 // @effect-diagnostics-next-line preferSchemaOverJson:off
91 NodeFS.writeFileSync(scriptPath, JSON.stringify(buildScript()), "utf8");
92 yield* Effect.addFinalizer(() =>
93 Effect.sync(() => NodeFS.rmSync(scriptPath, { force: true })),
94 );
95​
96 const runtime = yield* makeCodexSessionRuntime({
97 threadId: ThreadId.make("thread-collab-integration"),
98 binaryPath: peerPath,
99 cwd: "/tmp",
100 runtimeMode: "full-access",
101 environment: { ...process.env, T3_CODEX_COLLAB_SCRIPT: scriptPath },
102 });
103​
104 const eventsFiber = yield* runtime.events.pipe(
105 Stream.takeUntil((event) => event.method === "turn/completed"),
106 Stream.runCollect,
107 Effect.forkScoped,
108 );
109​
110 yield* runtime.start();
111 yield* runtime.sendTurn({ input: "fan out" });
112​
113 const events = Array.from(yield* Fiber.join(eventsFiber));
114 const methods = events.map((event) => event.method);
115​
116 // Children registered from subAgentActivity become synthetic agent
117 // lifecycle — including terminal rows that arrive AFTER the receiver
118 // map knows them (the ordering this test exists to pin).
119 assert.include(methods, "collabAgent/activity");
120 assert.include(methods, "collabAgent/turnCompleted");
121 assert.include(methods, "collabAgent/closed");
122​
123 const childTurnCompleted = events.find(
124 (event) =>
125 event.method === "collabAgent/turnCompleted" &&
126 (event.payload as { agentThreadId?: string }).agentThreadId === CHILD_A,
127 );
128 assert.isDefined(childTurnCompleted, "child A's turn completion becomes an agent event");
129​
130 const childClosed = events.find(
131 (event) =>
132 event.method === "collabAgent/closed" &&
133 (event.payload as { agentThreadId?: string }).agentThreadId === CHILD_B,
134 );
135 assert.isDefined(childClosed, "child B's close becomes an agent event");
136​
137 // Parent-owned resolution passes through — not swallowed, not
138 // re-labelled as an agent event.
139 assert.include(methods, "serverRequest/resolved");
140​
141 // The root's own subAgentActivity about "/root" must NOT register the
142 // root as a child: the parent turn completion still flows.
143 assert.include(methods, "turn/completed");
144​
145 // No raw child conversation methods leak onto the parent stream.
146 const leaked = events.filter((event) => {
147 const payload = event.payload as { threadId?: string } | undefined;
148 const addressedToChild = payload?.threadId === CHILD_A || payload?.threadId === CHILD_B;
149 return addressedToChild && (event.method?.startsWith("thread/") ?? false);
150 });
151 assert.deepEqual(
152 leaked.map((event) => event.method),
153 [],
154 "child thread/* lifecycle must not appear as parent events",
155 );
156​
157 yield* runtime.close;
158 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
159 );
160​
161 // it.live: the runtime talks to a real child process; under it.effect's
162 // TestClock the internal timers freeze and the join never completes.
163 it.live("Stop interrupts every live child regardless of registration timing", () =>
164 Effect.gen(function* () {
165 // Ordering + liveness torture for stop-everything: child A's
166 // turn/started arrives BEFORE anything registers it (foreign
167 // suppression path must record the live turn); child B's arrives after
168 // registration; child A's interrupt HANGS (RPC never settles — worse
169 // than rejecting) and the bounded deadline must still deliver B's and
170 // the parent's interrupts. The turn stays open so children are live
171 // when Stop fires.
172 // Build from REAL captured rows (hand-written shapes fail notification
173 // schema validation and are silently dropped): reorder so child A's
174 // turn/started precedes its registration, and drop terminal rows so
175 // children stay live when Stop fires.
176 const byIndex = wireFixture.notifications;
177 const isTurnStarted = (entry: (typeof byIndex)[number], child: string) =>
178 entry.method === "turn/started" &&
179 (entry.params as { threadId?: string }).threadId === child;
180 const isRegistration = (entry: (typeof byIndex)[number], child: string) => {
181 const item = (entry.params as { item?: { type?: string; agentThreadId?: string } }).item;
182 return item?.type === "subAgentActivity" && item.agentThreadId === child;
183 };
184 const turnStartedA = byIndex.find((entry) => isTurnStarted(entry, CHILD_A));
185 const turnStartedB = byIndex.find((entry) => isTurnStarted(entry, CHILD_B));
186 const registrationA = byIndex.find((entry) => isRegistration(entry, CHILD_A));
187 const registrationB = byIndex.find((entry) => isRegistration(entry, CHILD_B));
188 const rootThreadStarted = byIndex.find((entry) => entry.method === "thread/started");
189 assert.isDefined(turnStartedA);
190 assert.isDefined(turnStartedB);
191 assert.isDefined(registrationA);
192 assert.isDefined(registrationB);
193 assert.isDefined(rootThreadStarted);
194 const memoryThreadStarted = {
195 ...rootThreadStarted,
196 params: {
197 thread: {
198 ...rootThreadStarted.params.thread,
199 id: MEMORY,
200 sessionId: MEMORY,
201 source: "unknown",
202 threadSource: "memory_consolidation",
203 },
204 },
205 };
206 const memoryTurnStarted = {
207 ...turnStartedA,
208 params: {
209 ...turnStartedA.params,
210 threadId: MEMORY,
211 turn: { ...turnStartedA.params.turn, id: "memory-consolidation-turn" },
212 },
213 };
214 const script = {
215 rootThreadId: ROOT,
216 holdTurnOpen: true,
217 hangInterruptFor: CHILD_A,
218 notifications: [
219 turnStartedA,
220 registrationA,
221 memoryThreadStarted,
222 memoryTurnStarted,
223 registrationB,
224 turnStartedB,
225 ],
226 };
227 // @effect-diagnostics-next-line preferSchemaOverJson:off
228 NodeFS.writeFileSync(scriptPath, JSON.stringify(script), "utf8");
229 const interruptsPath = `${scriptPath}.interrupts`;
230 NodeFS.rmSync(interruptsPath, { force: true });
231 yield* Effect.addFinalizer(() =>
232 Effect.sync(() => {
233 NodeFS.rmSync(scriptPath, { force: true });
234 NodeFS.rmSync(interruptsPath, { force: true });
235 }),
236 );
237​
238 const runtime = yield* makeCodexSessionRuntime({
239 threadId: ThreadId.make("thread-collab-stop"),
240 binaryPath: peerPath,
241 cwd: "/tmp",
242 runtimeMode: "full-access",
243 environment: { ...process.env, T3_CODEX_COLLAB_SCRIPT: scriptPath },
244 });
245​
246 // Wait for both children's turnStarted signals to be processed before
247 // stopping (B via the registered-child path; A only produces live-turn
248 // bookkeeping, so key on B's synthetic event).
249 const childBStartedFiber = yield* runtime.events.pipe(
250 Stream.filter(
251 (event) =>
252 event.method === "collabAgent/turnStarted" &&
253 (event.payload as { agentThreadId?: string }).agentThreadId === CHILD_B,
254 ),
255 Stream.take(1),
256 Stream.runCollect,
257 Effect.forkScoped,
258 );
259​
260 yield* runtime.start();
261 yield* runtime.sendTurn({ input: "fan out and hang" });
262 const childBStarted = yield* Fiber.join(childBStartedFiber).pipe(
263 Effect.timeoutOption("15 seconds"),
264 );
265 assert.isTrue(childBStarted._tag === "Some", "child B turnStarted never arrived");
266​
267 // Stop everything. A's interrupt hangs forever — the bounded child
268 // deadline must expire and the parent interrupt must still be sent.
269 yield* runtime.interruptTurn();
270​
271 const parseInterruptLine = (line: string) => JSON.parse(line) as { threadId?: string };
272 const interrupted = NodeFS.readFileSync(interruptsPath, "utf8")
273 .trim()
274 .split("\n")
275 .filter((line) => line.length > 0)
276 .map(parseInterruptLine);
277 const interruptedThreads = new Set(interrupted.map((entry) => entry.threadId));
278 assert.isTrue(
279 interruptedThreads.has(CHILD_A),
280 "pre-registration child A must still receive the interrupt RPC",
281 );
282 assert.isTrue(interruptedThreads.has(CHILD_B), "registered child B must be interrupted");
283 assert.isTrue(
284 interruptedThreads.has(MEMORY),
285 "memory consolidation must be interrupted without appearing in chat",
286 );
287 assert.isTrue(interruptedThreads.has(ROOT), "parent turn must be interrupted last");
288​
289 yield* runtime.close;
290 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
291 );
292​
293 it.live("Stop targets the active turn when Codex has accepted a queued follow-up", () =>
294 Effect.gen(function* () {
295 const activeTurnId = "019fe3e8-f908-7f31-8d51-283f4a47897a";
296 const queuedTurnId = "019fe3eb-8faf-7de3-a85b-ac64c7f9c8c3";
297 const script = {
298 rootThreadId: ROOT,
299 holdTurnOpen: true,
300 onlyFirstTurnStarts: true,
301 turnIds: [activeTurnId, queuedTurnId],
302 expectedActiveTurnId: activeTurnId,
303 notifications: [],
304 };
305 // @effect-diagnostics-next-line preferSchemaOverJson:off
306 NodeFS.writeFileSync(scriptPath, JSON.stringify(script), "utf8");
307 const interruptsPath = `${scriptPath}.interrupts`;
308 NodeFS.rmSync(interruptsPath, { force: true });
309 yield* Effect.addFinalizer(() =>
310 Effect.sync(() => {
311 NodeFS.rmSync(scriptPath, { force: true });
312 NodeFS.rmSync(interruptsPath, { force: true });
313 }),
314 );
315​
316 const runtime = yield* makeCodexSessionRuntime({
317 threadId: ThreadId.make("thread-codex-queued-stop"),
318 binaryPath: peerPath,
319 cwd: "/tmp",
320 runtimeMode: "full-access",
321 environment: { ...process.env, T3_CODEX_COLLAB_SCRIPT: scriptPath },
322 });
323​
324 yield* runtime.start();
325 yield* runtime.sendTurn({ input: "keep working" });
326 yield* runtime.sendTurn({ input: "queued follow-up" });
327 yield* runtime.interruptTurn();
328​
329 const interrupts = NodeFS.readFileSync(interruptsPath, "utf8")
330 .trim()
331 .split("\n")
332 .map((line) => JSON.parse(line) as { threadId?: string; turnId?: string });
333 assert.deepEqual(interrupts.at(-1), {
334 threadId: ROOT,
335 turnId: activeTurnId,
336 });
337​
338 yield* runtime.close;
339 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
340 );
341​
342 const elicitationCases = [
343 {
344 decision: "accept",
345 response: { action: "accept", content: { approval: "once" } },
346 },
347 {
348 decision: "acceptForSession",
349 response: {
350 action: "accept",
351 _meta: { persist: "session" },
352 content: { approval: "session" },
353 },
354 },
355 {
356 decision: "acceptAlways",
357 response: {
358 action: "accept",
359 _meta: { persist: "always" },
360 content: { approval: "always" },
361 },
362 },
363 { decision: "decline", response: { action: "decline" } },
364 { decision: "cancel", response: { action: "cancel" } },
365 ] satisfies ReadonlyArray<{
366 readonly decision: ProviderApprovalDecision;
367 readonly response: Record<string, unknown>;
368 }>;
369​
370 for (const { decision, response } of elicitationCases) {
371 it.live(`returns the MCP elicitation ${decision} response to Codex`, () =>
372 Effect.gen(function* () {
373 const scriptedRequest = {
374 id: 7001,
375 method: "mcpServer/elicitation/request",
376 params: {
377 mode: "form",
378 message: "Allow ChatGPT to use Safari?",
379 serverName: "computer-use",
380 threadId: ROOT,
381 turnId: wireFixture.responses.turnStart.turn.id,
382 _meta: { app_name: "Safari", persist: ["session", "always"] },
383 requestedSchema: {
384 type: "object",
385 properties: {
386 approval: {
387 type: "string",
388 enum: ["once", "session", "always"],
389 },
390 },
391 required: ["approval"],
392 },
393 },
394 };
395 const script = {
396 rootThreadId: ROOT,
397 holdTurnOpen: true,
398 completeTurnOnServerResponse: true,
399 notifications: [],
400 serverRequests: [scriptedRequest],
401 };
402 const responsesPath = `${scriptPath}.responses`;
403 // @effect-diagnostics-next-line preferSchemaOverJson:off
404 NodeFS.writeFileSync(scriptPath, JSON.stringify(script), "utf8");
405 NodeFS.rmSync(responsesPath, { force: true });
406 yield* Effect.addFinalizer(() =>
407 Effect.sync(() => {
408 NodeFS.rmSync(scriptPath, { force: true });
409 NodeFS.rmSync(responsesPath, { force: true });
410 }),
411 );
412​
413 const runtime = yield* makeCodexSessionRuntime({
414 threadId: ThreadId.make("thread-codex-mcp-elicitation"),
415 binaryPath: peerPath,
416 cwd: "/tmp",
417 runtimeMode: "auto",
418 environment: { ...process.env, T3_CODEX_COLLAB_SCRIPT: scriptPath },
419 });
420 const approvalRequested = yield* Deferred.make<ProviderEvent>();
421 const turnCompleted = yield* Deferred.make<void>();
422 yield* runtime.events.pipe(
423 Stream.runForEach((event) =>
424 event.method === "mcpServer/elicitation/request"
425 ? Deferred.succeed(approvalRequested, event).pipe(Effect.asVoid)
426 : event.method === "turn/completed"
427 ? Deferred.succeed(turnCompleted, undefined).pipe(Effect.asVoid)
428 : Effect.void,
429 ),
430 Effect.forkScoped,
431 );
432​
433 yield* runtime.start();
434 yield* runtime.sendTurn({ input: "Open Safari" });
435 const approval = yield* Deferred.await(approvalRequested);
436 assert.equal(approval.requestKind, "mcp-elicitation");
437 assert.isDefined(approval.requestId);
438 if (approval.requestId === undefined) return;
439​
440 yield* runtime.respondToRequest(approval.requestId, decision);
441 yield* Deferred.await(turnCompleted);
442​
443 const recordedResponse = yield* decodeMcpElicitationResponse(
444 NodeFS.readFileSync(responsesPath, "utf8"),
445 );
446 assert.equal(recordedResponse.id, scriptedRequest.id);
447 assert.deepEqual(recordedResponse.result, response);
448​
449 yield* runtime.close;
450 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
451 );
452 }
453});