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

CodexCollabRuntime.integration.test.ts

297 lines12.5 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 { ThreadId } from "@t3tools/contracts";
17import * as Effect from "effect/Effect";
18import * as Fiber from "effect/Fiber";
19import * as Stream from "effect/Stream";
20import { assert, describe } from "vite-plus/test";
21​
22import wireFixture from "../testFixtures/codexMultiAgentWire.json" with { type: "json" };
23import { makeCodexSessionRuntime } from "./CodexSessionRuntime.ts";
24​
25const ROOT = wireFixture.rootThreadId;
26const [CHILD_A, CHILD_B] = wireFixture.childThreadIds as [string, string];
27​
28/**
29 * The captured sequence, extended with the shapes the live capture didn't
30 * include: a collabAgentToolCall with receiverThreadIds (feeds the legacy
31 * receiver-turn map, so ordering vs. v2 interception is exercised), child
32 * terminal lifecycle, and a serverRequest/resolved addressed to a child
33 * (must pass through to the parent path, not vanish).
34 */
35function buildScript() {
36 const captured = wireFixture.notifications;
37 const extras = [
38 {
39 method: "item/completed",
40 params: {
41 threadId: ROOT,
42 item: {
43 type: "collabAgentToolCall",
44 id: "call_fixture_wait",
45 tool: "wait",
46 status: "completed",
47 senderThreadId: ROOT,
48 receiverThreadIds: [CHILD_A, CHILD_B],
49 },
50 },
51 },
52 // Child terminal lifecycle AFTER the receiver map knows the children —
53 // pre-fix, the legacy suppressor dropped these before interception saw
54 // them, so no synthetic agent events were emitted.
55 {
56 method: "turn/completed",
57 params: {
58 threadId: CHILD_A,
59 turn: { id: `${CHILD_A}-turn-1`, status: "completed", items: [] },
60 },
61 },
62 { method: "thread/closed", params: { threadId: CHILD_B } },
63 // Parent-owned traffic addressed to a child conversation: must reach the
64 // parent path (approval correlation cleanup), not be swallowed.
65 { method: "serverRequest/resolved", params: { threadId: CHILD_A, requestId: "req-1" } },
66 ];
67 return {
68 rootThreadId: ROOT,
69 notifications: [...captured.filter((entry) => entry.method !== "turn/completed"), ...extras],
70 };
72​
73const scriptPath = NodePath.join(import.meta.dirname, "../testFixtures/.collab-script.json");
74const peerPath = NodePath.join(import.meta.dirname, "../testFixtures/codexCollabMockPeer.sh");
75​
76describe("CodexSessionRuntime collab integration", () => {
77 it.effect("replays the captured fan-out into synthetic agent events without child leaks", () =>
78 Effect.gen(function* () {
79 // @effect-diagnostics-next-line preferSchemaOverJson:off
80 NodeFS.writeFileSync(scriptPath, JSON.stringify(buildScript()), "utf8");
81 yield* Effect.addFinalizer(() =>
82 Effect.sync(() => NodeFS.rmSync(scriptPath, { force: true })),
83 );
84​
85 const runtime = yield* makeCodexSessionRuntime({
86 threadId: ThreadId.make("thread-collab-integration"),
87 binaryPath: peerPath,
88 cwd: "/tmp",
89 runtimeMode: "full-access",
90 environment: { ...process.env, T3_CODEX_COLLAB_SCRIPT: scriptPath },
91 });
92​
93 const eventsFiber = yield* runtime.events.pipe(
94 Stream.takeUntil((event) => event.method === "turn/completed"),
95 Stream.runCollect,
96 Effect.forkScoped,
97 );
98​
99 yield* runtime.start();
100 yield* runtime.sendTurn({ input: "fan out" });
101​
102 const events = Array.from(yield* Fiber.join(eventsFiber));
103 const methods = events.map((event) => event.method);
104​
105 // Children registered from subAgentActivity become synthetic agent
106 // lifecycle — including terminal rows that arrive AFTER the receiver
107 // map knows them (the ordering this test exists to pin).
108 assert.include(methods, "collabAgent/activity");
109 assert.include(methods, "collabAgent/turnCompleted");
110 assert.include(methods, "collabAgent/closed");
111​
112 const childTurnCompleted = events.find(
113 (event) =>
114 event.method === "collabAgent/turnCompleted" &&
115 (event.payload as { agentThreadId?: string }).agentThreadId === CHILD_A,
116 );
117 assert.isDefined(childTurnCompleted, "child A's turn completion becomes an agent event");
118​
119 const childClosed = events.find(
120 (event) =>
121 event.method === "collabAgent/closed" &&
122 (event.payload as { agentThreadId?: string }).agentThreadId === CHILD_B,
123 );
124 assert.isDefined(childClosed, "child B's close becomes an agent event");
125​
126 // Parent-owned resolution passes through — not swallowed, not
127 // re-labelled as an agent event.
128 assert.include(methods, "serverRequest/resolved");
129​
130 // The root's own subAgentActivity about "/root" must NOT register the
131 // root as a child: the parent turn completion still flows.
132 assert.include(methods, "turn/completed");
133​
134 // No raw child conversation methods leak onto the parent stream.
135 const leaked = events.filter((event) => {
136 const payload = event.payload as { threadId?: string } | undefined;
137 const addressedToChild = payload?.threadId === CHILD_A || payload?.threadId === CHILD_B;
138 return addressedToChild && (event.method?.startsWith("thread/") ?? false);
139 });
140 assert.deepEqual(
141 leaked.map((event) => event.method),
142 [],
143 "child thread/* lifecycle must not appear as parent events",
144 );
145​
146 yield* runtime.close;
147 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
148 );
149​
150 // it.live: the runtime talks to a real child process; under it.effect's
151 // TestClock the internal timers freeze and the join never completes.
152 it.live("Stop interrupts every live child regardless of registration timing", () =>
153 Effect.gen(function* () {
154 // Ordering + liveness torture for stop-everything: child A's
155 // turn/started arrives BEFORE anything registers it (foreign
156 // suppression path must record the live turn); child B's arrives after
157 // registration; child A's interrupt HANGS (RPC never settles — worse
158 // than rejecting) and the bounded deadline must still deliver B's and
159 // the parent's interrupts. The turn stays open so children are live
160 // when Stop fires.
161 // Build from REAL captured rows (hand-written shapes fail notification
162 // schema validation and are silently dropped): reorder so child A's
163 // turn/started precedes its registration, and drop terminal rows so
164 // children stay live when Stop fires.
165 const byIndex = wireFixture.notifications;
166 const isTurnStarted = (entry: (typeof byIndex)[number], child: string) =>
167 entry.method === "turn/started" &&
168 (entry.params as { threadId?: string }).threadId === child;
169 const isRegistration = (entry: (typeof byIndex)[number], child: string) => {
170 const item = (entry.params as { item?: { type?: string; agentThreadId?: string } }).item;
171 return item?.type === "subAgentActivity" && item.agentThreadId === child;
172 };
173 const turnStartedA = byIndex.find((entry) => isTurnStarted(entry, CHILD_A));
174 const turnStartedB = byIndex.find((entry) => isTurnStarted(entry, CHILD_B));
175 const registrationA = byIndex.find((entry) => isRegistration(entry, CHILD_A));
176 const registrationB = byIndex.find((entry) => isRegistration(entry, CHILD_B));
177 assert.isDefined(turnStartedA);
178 assert.isDefined(turnStartedB);
179 assert.isDefined(registrationA);
180 assert.isDefined(registrationB);
181 const script = {
182 rootThreadId: ROOT,
183 holdTurnOpen: true,
184 hangInterruptFor: CHILD_A,
185 notifications: [turnStartedA, registrationA, registrationB, turnStartedB],
186 };
187 // @effect-diagnostics-next-line preferSchemaOverJson:off
188 NodeFS.writeFileSync(scriptPath, JSON.stringify(script), "utf8");
189 const interruptsPath = `${scriptPath}.interrupts`;
190 NodeFS.rmSync(interruptsPath, { force: true });
191 yield* Effect.addFinalizer(() =>
192 Effect.sync(() => {
193 NodeFS.rmSync(scriptPath, { force: true });
194 NodeFS.rmSync(interruptsPath, { force: true });
195 }),
196 );
197​
198 const runtime = yield* makeCodexSessionRuntime({
199 threadId: ThreadId.make("thread-collab-stop"),
200 binaryPath: peerPath,
201 cwd: "/tmp",
202 runtimeMode: "full-access",
203 environment: { ...process.env, T3_CODEX_COLLAB_SCRIPT: scriptPath },
204 });
205​
206 // Wait for both children's turnStarted signals to be processed before
207 // stopping (B via the registered-child path; A only produces live-turn
208 // bookkeeping, so key on B's synthetic event).
209 const childBStartedFiber = yield* runtime.events.pipe(
210 Stream.filter(
211 (event) =>
212 event.method === "collabAgent/turnStarted" &&
213 (event.payload as { agentThreadId?: string }).agentThreadId === CHILD_B,
214 ),
215 Stream.take(1),
216 Stream.runCollect,
217 Effect.forkScoped,
218 );
219​
220 yield* runtime.start();
221 yield* runtime.sendTurn({ input: "fan out and hang" });
222 const childBStarted = yield* Fiber.join(childBStartedFiber).pipe(
223 Effect.timeoutOption("15 seconds"),
224 );
225 assert.isTrue(childBStarted._tag === "Some", "child B turnStarted never arrived");
226​
227 // Stop everything. A's interrupt hangs forever — the bounded child
228 // deadline must expire and the parent interrupt must still be sent.
229 yield* runtime.interruptTurn();
230​
231 const parseInterruptLine = (line: string) => JSON.parse(line) as { threadId?: string };
232 const interrupted = NodeFS.readFileSync(interruptsPath, "utf8")
233 .trim()
234 .split("\n")
235 .filter((line) => line.length > 0)
236 .map(parseInterruptLine);
237 const interruptedThreads = new Set(interrupted.map((entry) => entry.threadId));
238 assert.isTrue(
239 interruptedThreads.has(CHILD_A),
240 "pre-registration child A must still receive the interrupt RPC",
241 );
242 assert.isTrue(interruptedThreads.has(CHILD_B), "registered child B must be interrupted");
243 assert.isTrue(interruptedThreads.has(ROOT), "parent turn must be interrupted last");
244​
245 yield* runtime.close;
246 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
247 );
248​
249 it.live("Stop targets the active turn when Codex has accepted a queued follow-up", () =>
250 Effect.gen(function* () {
251 const activeTurnId = "019fe3e8-f908-7f31-8d51-283f4a47897a";
252 const queuedTurnId = "019fe3eb-8faf-7de3-a85b-ac64c7f9c8c3";
253 const script = {
254 rootThreadId: ROOT,
255 holdTurnOpen: true,
256 onlyFirstTurnStarts: true,
257 turnIds: [activeTurnId, queuedTurnId],
258 expectedActiveTurnId: activeTurnId,
259 notifications: [],
260 };
261 // @effect-diagnostics-next-line preferSchemaOverJson:off
262 NodeFS.writeFileSync(scriptPath, JSON.stringify(script), "utf8");
263 const interruptsPath = `${scriptPath}.interrupts`;
264 NodeFS.rmSync(interruptsPath, { force: true });
265 yield* Effect.addFinalizer(() =>
266 Effect.sync(() => {
267 NodeFS.rmSync(scriptPath, { force: true });
268 NodeFS.rmSync(interruptsPath, { force: true });
269 }),
270 );
271​
272 const runtime = yield* makeCodexSessionRuntime({
273 threadId: ThreadId.make("thread-codex-queued-stop"),
274 binaryPath: peerPath,
275 cwd: "/tmp",
276 runtimeMode: "full-access",
277 environment: { ...process.env, T3_CODEX_COLLAB_SCRIPT: scriptPath },
278 });
279​
280 yield* runtime.start();
281 yield* runtime.sendTurn({ input: "keep working" });
282 yield* runtime.sendTurn({ input: "queued follow-up" });
283 yield* runtime.interruptTurn();
284​
285 const interrupts = NodeFS.readFileSync(interruptsPath, "utf8")
286 .trim()
287 .split("\n")
288 .map((line) => JSON.parse(line) as { threadId?: string; turnId?: string });
289 assert.deepEqual(interrupts.at(-1), {
290 threadId: ROOT,
291 turnId: activeTurnId,
292 });
293​
294 yield* runtime.close;
295 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
296 );
297});