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

CodexCollabRuntime.integration.test.ts

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