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

codexAppServerManager.test.ts

1,017 lines29.2 KB

1import { describe, expect, it, vi } from "vitest";
2import { randomUUID } from "node:crypto";
3import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
4import os from "node:os";
5import path from "node:path";
6import { ApprovalRequestId, ThreadId } from "@t3tools/contracts";
7​
8import {
9 buildCodexInitializeParams,
10 CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS,
11 CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS,
12 CodexAppServerManager,
13 classifyCodexStderrLine,
14 isRecoverableThreadResumeError,
15 normalizeCodexModelSlug,
16 readCodexAccountSnapshot,
17 resolveCodexModelForAccount,
18} from "./codexAppServerManager";
19​
20const asThreadId = (value: string): ThreadId => ThreadId.makeUnsafe(value);
21​
22function createSendTurnHarness() {
23 const manager = new CodexAppServerManager();
24 const context = {
25 session: {
26 provider: "codex",
27 status: "ready",
28 threadId: "thread_1",
29 runtimeMode: "full-access",
30 model: "gpt-5.3-codex",
31 resumeCursor: { threadId: "thread_1" },
32 createdAt: "2026-02-10T00:00:00.000Z",
33 updatedAt: "2026-02-10T00:00:00.000Z",
34 },
35 account: {
36 type: "unknown",
37 planType: null,
38 sparkEnabled: true,
39 },
40 collabReceiverTurns: new Map(),
41 };
42​
43 const requireSession = vi
44 .spyOn(
45 manager as unknown as { requireSession: (sessionId: string) => unknown },
46 "requireSession",
47 )
48 .mockReturnValue(context);
49 const sendRequest = vi
50 .spyOn(
51 manager as unknown as { sendRequest: (...args: unknown[]) => Promise<unknown> },
52 "sendRequest",
53 )
54 .mockResolvedValue({
55 turn: {
56 id: "turn_1",
57 },
58 });
59 const updateSession = vi
60 .spyOn(manager as unknown as { updateSession: (...args: unknown[]) => void }, "updateSession")
61 .mockImplementation(() => {});
62​
63 return { manager, context, requireSession, sendRequest, updateSession };
65​
66function createThreadControlHarness() {
67 const manager = new CodexAppServerManager();
68 const context = {
69 session: {
70 provider: "codex",
71 status: "ready",
72 threadId: "thread_1",
73 runtimeMode: "full-access",
74 model: "gpt-5.3-codex",
75 resumeCursor: { threadId: "thread_1" },
76 createdAt: "2026-02-10T00:00:00.000Z",
77 updatedAt: "2026-02-10T00:00:00.000Z",
78 },
79 collabReceiverTurns: new Map(),
80 };
81​
82 const requireSession = vi
83 .spyOn(
84 manager as unknown as { requireSession: (sessionId: string) => unknown },
85 "requireSession",
86 )
87 .mockReturnValue(context);
88 const sendRequest = vi.spyOn(
89 manager as unknown as { sendRequest: (...args: unknown[]) => Promise<unknown> },
90 "sendRequest",
91 );
92 const updateSession = vi
93 .spyOn(manager as unknown as { updateSession: (...args: unknown[]) => void }, "updateSession")
94 .mockImplementation(() => {});
95​
96 return { manager, context, requireSession, sendRequest, updateSession };
98​
99function createPendingUserInputHarness() {
100 const manager = new CodexAppServerManager();
101 const context = {
102 session: {
103 provider: "codex",
104 status: "ready",
105 threadId: "thread_1",
106 runtimeMode: "full-access",
107 model: "gpt-5.3-codex",
108 resumeCursor: { threadId: "thread_1" },
109 createdAt: "2026-02-10T00:00:00.000Z",
110 updatedAt: "2026-02-10T00:00:00.000Z",
111 },
112 pendingUserInputs: new Map([
113 [
114 ApprovalRequestId.makeUnsafe("req-user-input-1"),
115 {
116 requestId: ApprovalRequestId.makeUnsafe("req-user-input-1"),
117 jsonRpcId: 42,
118 threadId: asThreadId("thread_1"),
119 },
120 ],
121 ]),
122 collabReceiverTurns: new Map(),
123 };
124​
125 const requireSession = vi
126 .spyOn(
127 manager as unknown as { requireSession: (sessionId: string) => unknown },
128 "requireSession",
129 )
130 .mockReturnValue(context);
131 const writeMessage = vi
132 .spyOn(manager as unknown as { writeMessage: (...args: unknown[]) => void }, "writeMessage")
133 .mockImplementation(() => {});
134 const emitEvent = vi
135 .spyOn(manager as unknown as { emitEvent: (...args: unknown[]) => void }, "emitEvent")
136 .mockImplementation(() => {});
137​
138 return { manager, context, requireSession, writeMessage, emitEvent };
140​
141function createCollabNotificationHarness() {
142 const manager = new CodexAppServerManager();
143 const context = {
144 session: {
145 provider: "codex",
146 status: "running",
147 threadId: asThreadId("thread_1"),
148 runtimeMode: "full-access",
149 model: "gpt-5.3-codex",
150 activeTurnId: "turn_parent",
151 resumeCursor: { threadId: "provider_parent" },
152 createdAt: "2026-02-10T00:00:00.000Z",
153 updatedAt: "2026-02-10T00:00:00.000Z",
154 },
155 account: {
156 type: "unknown",
157 planType: null,
158 sparkEnabled: true,
159 },
160 pending: new Map(),
161 pendingApprovals: new Map(),
162 pendingUserInputs: new Map(),
163 collabReceiverTurns: new Map<string, string>(),
164 nextRequestId: 1,
165 stopping: false,
166 };
167​
168 const emitEvent = vi
169 .spyOn(manager as unknown as { emitEvent: (...args: unknown[]) => void }, "emitEvent")
170 .mockImplementation(() => {});
171 const updateSession = vi
172 .spyOn(manager as unknown as { updateSession: (...args: unknown[]) => void }, "updateSession")
173 .mockImplementation(() => {});
174​
175 return { manager, context, emitEvent, updateSession };
177​
178describe("classifyCodexStderrLine", () => {
179 it("ignores empty lines", () => {
180 expect(classifyCodexStderrLine(" ")).toBeNull();
181 });
182​
183 it("ignores non-error structured codex logs", () => {
184 const line =
185 "2026-02-08T04:24:19.241256Z WARN codex_core::features: unknown feature key in config: skills";
186 expect(classifyCodexStderrLine(line)).toBeNull();
187 });
188​
189 it("ignores known benign rollout path errors", () => {
190 const line =
191 "\u001b[2m2026-02-08T04:24:20.085687Z\u001b[0m \u001b[31mERROR\u001b[0m \u001b[2mcodex_core::rollout::list\u001b[0m: state db missing rollout path for thread 019c3b6c-46b8-7b70-ad23-82f824d161fb";
192 expect(classifyCodexStderrLine(line)).toBeNull();
193 });
194​
195 it("keeps unknown structured errors", () => {
196 const line = "2026-02-08T04:24:20.085687Z ERROR codex_core::runtime: unrecoverable failure";
197 expect(classifyCodexStderrLine(line)).toEqual({
198 message: line,
199 });
200 });
201​
202 it("keeps plain stderr messages", () => {
203 const line = "fatal: permission denied";
204 expect(classifyCodexStderrLine(line)).toEqual({
205 message: line,
206 });
207 });
208});
209​
210describe("normalizeCodexModelSlug", () => {
211 it("maps 5.3 aliases to gpt-5.3-codex", () => {
212 expect(normalizeCodexModelSlug("5.3")).toBe("gpt-5.3-codex");
213 expect(normalizeCodexModelSlug("gpt-5.3")).toBe("gpt-5.3-codex");
214 });
215​
216 it("prefers codex id when model differs", () => {
217 expect(normalizeCodexModelSlug("gpt-5.3", "gpt-5.3-codex")).toBe("gpt-5.3-codex");
218 });
219​
220 it("keeps non-aliased models as-is", () => {
221 expect(normalizeCodexModelSlug("gpt-5.2-codex")).toBe("gpt-5.2-codex");
222 expect(normalizeCodexModelSlug("gpt-5.2")).toBe("gpt-5.2");
223 });
224});
225​
226describe("isRecoverableThreadResumeError", () => {
227 it("matches not-found resume errors", () => {
228 expect(
229 isRecoverableThreadResumeError(new Error("thread/resume failed: thread not found")),
230 ).toBe(true);
231 });
232​
233 it("ignores non-resume errors", () => {
234 expect(
235 isRecoverableThreadResumeError(new Error("thread/start failed: permission denied")),
236 ).toBe(false);
237 });
238​
239 it("ignores non-recoverable resume errors", () => {
240 expect(
241 isRecoverableThreadResumeError(
242 new Error("thread/resume failed: timed out waiting for server"),
243 ),
244 ).toBe(false);
245 });
246});
247​
248describe("readCodexAccountSnapshot", () => {
249 it("disables spark for chatgpt plus accounts", () => {
250 expect(
251 readCodexAccountSnapshot({
252 type: "chatgpt",
253 email: "plus@example.com",
254 planType: "plus",
255 }),
256 ).toEqual({
257 type: "chatgpt",
258 planType: "plus",
259 sparkEnabled: false,
260 });
261 });
262​
263 it("keeps spark enabled for chatgpt pro accounts", () => {
264 expect(
265 readCodexAccountSnapshot({
266 type: "chatgpt",
267 email: "pro@example.com",
268 planType: "pro",
269 }),
270 ).toEqual({
271 type: "chatgpt",
272 planType: "pro",
273 sparkEnabled: true,
274 });
275 });
276​
277 it("keeps spark enabled for api key accounts", () => {
278 expect(
279 readCodexAccountSnapshot({
280 type: "apiKey",
281 }),
282 ).toEqual({
283 type: "apiKey",
284 planType: null,
285 sparkEnabled: true,
286 });
287 });
288});
289​
290describe("resolveCodexModelForAccount", () => {
291 it("falls back from spark to default for unsupported chatgpt plans", () => {
292 expect(
293 resolveCodexModelForAccount("gpt-5.3-codex-spark", {
294 type: "chatgpt",
295 planType: "plus",
296 sparkEnabled: false,
297 }),
298 ).toBe("gpt-5.3-codex");
299 });
300​
301 it("keeps spark for supported plans", () => {
302 expect(
303 resolveCodexModelForAccount("gpt-5.3-codex-spark", {
304 type: "chatgpt",
305 planType: "pro",
306 sparkEnabled: true,
307 }),
308 ).toBe("gpt-5.3-codex-spark");
309 });
310});
311​
312describe("startSession", () => {
313 it("enables Codex experimental api capabilities during initialize", () => {
314 expect(buildCodexInitializeParams()).toEqual({
315 clientInfo: {
316 name: "t3code_desktop",
317 title: "T3 Code Desktop",
318 version: "0.1.0",
319 },
320 capabilities: {
321 experimentalApi: true,
322 },
323 });
324 });
325​
326 it("emits session/startFailed when resolving cwd throws before process launch", async () => {
327 const manager = new CodexAppServerManager();
328 const events: Array<{ method: string; kind: string; message?: string }> = [];
329 manager.on("event", (event) => {
330 events.push({
331 method: event.method,
332 kind: event.kind,
333 ...(event.message ? { message: event.message } : {}),
334 });
335 });
336​
337 const processCwd = vi.spyOn(process, "cwd").mockImplementation(() => {
338 throw new Error("cwd missing");
339 });
340 try {
341 await expect(
342 manager.startSession({
343 threadId: asThreadId("thread-1"),
344 provider: "codex",
345 runtimeMode: "full-access",
346 }),
347 ).rejects.toThrow("cwd missing");
348 expect(events).toHaveLength(1);
349 expect(events[0]).toEqual({
350 method: "session/startFailed",
351 kind: "error",
352 message: "cwd missing",
353 });
354 } finally {
355 processCwd.mockRestore();
356 manager.stopAll();
357 }
358 });
359​
360 it("fails fast with an upgrade message when codex is below the minimum supported version", async () => {
361 const manager = new CodexAppServerManager();
362 const events: Array<{ method: string; kind: string; message?: string }> = [];
363 manager.on("event", (event) => {
364 events.push({
365 method: event.method,
366 kind: event.kind,
367 ...(event.message ? { message: event.message } : {}),
368 });
369 });
370​
371 const versionCheck = vi
372 .spyOn(
373 manager as unknown as {
374 assertSupportedCodexCliVersion: (input: {
375 binaryPath: string;
376 cwd: string;
377 homePath?: string;
378 }) => void;
379 },
380 "assertSupportedCodexCliVersion",
381 )
382 .mockImplementation(() => {
383 throw new Error(
384 "Codex CLI v0.36.0 is too old for T3 Code. Upgrade to v0.37.0 or newer and restart T3 Code.",
385 );
386 });
387​
388 try {
389 await expect(
390 manager.startSession({
391 threadId: asThreadId("thread-1"),
392 provider: "codex",
393 runtimeMode: "full-access",
394 }),
395 ).rejects.toThrow(
396 "Codex CLI v0.36.0 is too old for T3 Code. Upgrade to v0.37.0 or newer and restart T3 Code.",
397 );
398 expect(versionCheck).toHaveBeenCalledTimes(1);
399 expect(events).toEqual([
400 {
401 method: "session/startFailed",
402 kind: "error",
403 message:
404 "Codex CLI v0.36.0 is too old for T3 Code. Upgrade to v0.37.0 or newer and restart T3 Code.",
405 },
406 ]);
407 } finally {
408 versionCheck.mockRestore();
409 manager.stopAll();
410 }
411 });
412});
413​
414describe("sendTurn", () => {
415 it("sends text and image user input items to turn/start", async () => {
416 const { manager, context, requireSession, sendRequest, updateSession } =
417 createSendTurnHarness();
418​
419 const result = await manager.sendTurn({
420 threadId: asThreadId("thread_1"),
421 input: "Inspect this image",
422 attachments: [
423 {
424 type: "image",
425 url: "data:image/png;base64,AAAA",
426 },
427 ],
428 model: "gpt-5.3",
429 serviceTier: "fast",
430 effort: "high",
431 });
432​
433 expect(result).toEqual({
434 threadId: "thread_1",
435 turnId: "turn_1",
436 resumeCursor: { threadId: "thread_1" },
437 });
438 expect(requireSession).toHaveBeenCalledWith("thread_1");
439 expect(sendRequest).toHaveBeenCalledWith(context, "turn/start", {
440 threadId: "thread_1",
441 input: [
442 {
443 type: "text",
444 text: "Inspect this image",
445 text_elements: [],
446 },
447 {
448 type: "image",
449 url: "data:image/png;base64,AAAA",
450 },
451 ],
452 model: "gpt-5.3-codex",
453 serviceTier: "fast",
454 effort: "high",
455 });
456 expect(updateSession).toHaveBeenCalledWith(context, {
457 status: "running",
458 activeTurnId: "turn_1",
459 resumeCursor: { threadId: "thread_1" },
460 });
461 });
462​
463 it("supports image-only turns", async () => {
464 const { manager, context, sendRequest } = createSendTurnHarness();
465​
466 await manager.sendTurn({
467 threadId: asThreadId("thread_1"),
468 attachments: [
469 {
470 type: "image",
471 url: "data:image/png;base64,BBBB",
472 },
473 ],
474 });
475​
476 expect(sendRequest).toHaveBeenCalledWith(context, "turn/start", {
477 threadId: "thread_1",
478 input: [
479 {
480 type: "image",
481 url: "data:image/png;base64,BBBB",
482 },
483 ],
484 model: "gpt-5.3-codex",
485 });
486 });
487​
488 it("passes Codex plan mode as a collaboration preset on turn/start", async () => {
489 const { manager, context, sendRequest } = createSendTurnHarness();
490​
491 await manager.sendTurn({
492 threadId: asThreadId("thread_1"),
493 input: "Plan the work",
494 interactionMode: "plan",
495 });
496​
497 expect(sendRequest).toHaveBeenCalledWith(context, "turn/start", {
498 threadId: "thread_1",
499 input: [
500 {
501 type: "text",
502 text: "Plan the work",
503 text_elements: [],
504 },
505 ],
506 model: "gpt-5.3-codex",
507 collaborationMode: {
508 mode: "plan",
509 settings: {
510 model: "gpt-5.3-codex",
511 reasoning_effort: "medium",
512 developer_instructions: CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS,
513 },
514 },
515 });
516 });
517​
518 it("passes Codex default mode as a collaboration preset on turn/start", async () => {
519 const { manager, context, sendRequest } = createSendTurnHarness();
520​
521 await manager.sendTurn({
522 threadId: asThreadId("thread_1"),
523 input: "PLEASE IMPLEMENT THIS PLAN:\n- step 1",
524 interactionMode: "default",
525 });
526​
527 expect(sendRequest).toHaveBeenCalledWith(context, "turn/start", {
528 threadId: "thread_1",
529 input: [
530 {
531 type: "text",
532 text: "PLEASE IMPLEMENT THIS PLAN:\n- step 1",
533 text_elements: [],
534 },
535 ],
536 model: "gpt-5.3-codex",
537 collaborationMode: {
538 mode: "default",
539 settings: {
540 model: "gpt-5.3-codex",
541 reasoning_effort: "medium",
542 developer_instructions: CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS,
543 },
544 },
545 });
546 });
547​
548 it("keeps the session model when interaction mode is set without an explicit model", async () => {
549 const { manager, context, sendRequest } = createSendTurnHarness();
550 context.session.model = "gpt-5.2-codex";
551​
552 await manager.sendTurn({
553 threadId: asThreadId("thread_1"),
554 input: "Plan this with my current session model",
555 interactionMode: "plan",
556 });
557​
558 expect(sendRequest).toHaveBeenCalledWith(context, "turn/start", {
559 threadId: "thread_1",
560 input: [
561 {
562 type: "text",
563 text: "Plan this with my current session model",
564 text_elements: [],
565 },
566 ],
567 model: "gpt-5.2-codex",
568 collaborationMode: {
569 mode: "plan",
570 settings: {
571 model: "gpt-5.2-codex",
572 reasoning_effort: "medium",
573 developer_instructions: CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS,
574 },
575 },
576 });
577 });
578​
579 it("rejects empty turn input", async () => {
580 const { manager } = createSendTurnHarness();
581​
582 await expect(
583 manager.sendTurn({
584 threadId: asThreadId("thread_1"),
585 }),
586 ).rejects.toThrow("Turn input must include text or attachments.");
587 });
588});
589​
590describe("thread checkpoint control", () => {
591 it("reads thread turns from thread/read", async () => {
592 const { manager, context, requireSession, sendRequest } = createThreadControlHarness();
593 sendRequest.mockResolvedValue({
594 thread: {
595 id: "thread_1",
596 turns: [
597 {
598 id: "turn_1",
599 items: [{ type: "userMessage", content: [{ type: "text", text: "hello" }] }],
600 },
601 ],
602 },
603 });
604​
605 const result = await manager.readThread(asThreadId("thread_1"));
606​
607 expect(requireSession).toHaveBeenCalledWith("thread_1");
608 expect(sendRequest).toHaveBeenCalledWith(context, "thread/read", {
609 threadId: "thread_1",
610 includeTurns: true,
611 });
612 expect(result).toEqual({
613 threadId: "thread_1",
614 turns: [
615 {
616 id: "turn_1",
617 items: [{ type: "userMessage", content: [{ type: "text", text: "hello" }] }],
618 },
619 ],
620 });
621 });
622​
623 it("reads thread turns from flat thread/read responses", async () => {
624 const { manager, context, sendRequest } = createThreadControlHarness();
625 sendRequest.mockResolvedValue({
626 threadId: "thread_1",
627 turns: [
628 {
629 id: "turn_1",
630 items: [{ type: "userMessage", content: [{ type: "text", text: "hello" }] }],
631 },
632 ],
633 });
634​
635 const result = await manager.readThread(asThreadId("thread_1"));
636​
637 expect(sendRequest).toHaveBeenCalledWith(context, "thread/read", {
638 threadId: "thread_1",
639 includeTurns: true,
640 });
641 expect(result).toEqual({
642 threadId: "thread_1",
643 turns: [
644 {
645 id: "turn_1",
646 items: [{ type: "userMessage", content: [{ type: "text", text: "hello" }] }],
647 },
648 ],
649 });
650 });
651​
652 it("rolls back turns via thread/rollback and resets session running state", async () => {
653 const { manager, context, sendRequest, updateSession } = createThreadControlHarness();
654 sendRequest.mockResolvedValue({
655 thread: {
656 id: "thread_1",
657 turns: [],
658 },
659 });
660​
661 const result = await manager.rollbackThread(asThreadId("thread_1"), 2);
662​
663 expect(sendRequest).toHaveBeenCalledWith(context, "thread/rollback", {
664 threadId: "thread_1",
665 numTurns: 2,
666 });
667 expect(updateSession).toHaveBeenCalledWith(context, {
668 status: "ready",
669 activeTurnId: undefined,
670 });
671 expect(result).toEqual({
672 threadId: "thread_1",
673 turns: [],
674 });
675 });
676});
677​
678describe("respondToUserInput", () => {
679 it("serializes canonical answers to Codex native answer objects", async () => {
680 const { manager, context, requireSession, writeMessage, emitEvent } =
681 createPendingUserInputHarness();
682​
683 await manager.respondToUserInput(
684 asThreadId("thread_1"),
685 ApprovalRequestId.makeUnsafe("req-user-input-1"),
686 {
687 scope: "All request methods",
688 compat: "Keep current envelope",
689 },
690 );
691​
692 expect(requireSession).toHaveBeenCalledWith("thread_1");
693 expect(writeMessage).toHaveBeenCalledWith(context, {
694 id: 42,
695 result: {
696 answers: {
697 scope: { answers: ["All request methods"] },
698 compat: { answers: ["Keep current envelope"] },
699 },
700 },
701 });
702 expect(emitEvent).toHaveBeenCalledWith(
703 expect.objectContaining({
704 method: "item/tool/requestUserInput/answered",
705 payload: {
706 requestId: "req-user-input-1",
707 answers: {
708 scope: { answers: ["All request methods"] },
709 compat: { answers: ["Keep current envelope"] },
710 },
711 },
712 }),
713 );
714 });
715​
716 it("preserves explicit empty multi-select answers", async () => {
717 const { manager, context, requireSession, writeMessage, emitEvent } =
718 createPendingUserInputHarness();
719​
720 await manager.respondToUserInput(
721 asThreadId("thread_1"),
722 ApprovalRequestId.makeUnsafe("req-user-input-1"),
723 {
724 scope: [],
725 },
726 );
727​
728 expect(requireSession).toHaveBeenCalledWith("thread_1");
729 expect(writeMessage).toHaveBeenCalledWith(context, {
730 id: 42,
731 result: {
732 answers: {
733 scope: { answers: [] },
734 },
735 },
736 });
737 expect(emitEvent).toHaveBeenCalledWith(
738 expect.objectContaining({
739 method: "item/tool/requestUserInput/answered",
740 payload: {
741 requestId: "req-user-input-1",
742 answers: {
743 scope: { answers: [] },
744 },
745 },
746 }),
747 );
748 });
749​
750 it("tracks file-read approval requests with the correct method", () => {
751 const manager = new CodexAppServerManager();
752 const context = {
753 session: {
754 sessionId: "sess_1",
755 provider: "codex",
756 status: "ready",
757 threadId: asThreadId("thread_1"),
758 resumeCursor: { threadId: "thread_1" },
759 createdAt: "2026-02-10T00:00:00.000Z",
760 updatedAt: "2026-02-10T00:00:00.000Z",
761 },
762 pendingApprovals: new Map(),
763 pendingUserInputs: new Map(),
764 collabReceiverTurns: new Map(),
765 };
766 type ApprovalRequestContext = {
767 session: typeof context.session;
768 pendingApprovals: typeof context.pendingApprovals;
769 pendingUserInputs: typeof context.pendingUserInputs;
770 };
771​
772 (
773 manager as unknown as {
774 handleServerRequest: (
775 context: ApprovalRequestContext,
776 request: Record<string, unknown>,
777 ) => void;
778 }
779 ).handleServerRequest(context, {
780 jsonrpc: "2.0",
781 id: 42,
782 method: "item/fileRead/requestApproval",
783 params: {},
784 });
785​
786 const request = Array.from(context.pendingApprovals.values())[0];
787 expect(request?.requestKind).toBe("file-read");
788 expect(request?.method).toBe("item/fileRead/requestApproval");
789 });
790});
791​
792describe("collab child conversation routing", () => {
793 it("rewrites child notification turn ids onto the parent turn", () => {
794 const { manager, context, emitEvent } = createCollabNotificationHarness();
795​
796 (
797 manager as unknown as {
798 handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
799 }
800 ).handleServerNotification(context, {
801 method: "item/completed",
802 params: {
803 item: {
804 type: "collabAgentToolCall",
805 id: "call_collab_1",
806 receiverThreadIds: ["child_provider_1"],
807 },
808 threadId: "provider_parent",
809 turnId: "turn_parent",
810 },
811 });
812​
813 (
814 manager as unknown as {
815 handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
816 }
817 ).handleServerNotification(context, {
818 method: "item/agentMessage/delta",
819 params: {
820 threadId: "child_provider_1",
821 turnId: "turn_child_1",
822 itemId: "msg_child_1",
823 delta: "working",
824 },
825 });
826​
827 expect(emitEvent).toHaveBeenLastCalledWith(
828 expect.objectContaining({
829 method: "item/agentMessage/delta",
830 turnId: "turn_parent",
831 itemId: "msg_child_1",
832 }),
833 );
834 });
835​
836 it("suppresses child lifecycle notifications so they cannot replace the parent turn", () => {
837 const { manager, context, emitEvent, updateSession } = createCollabNotificationHarness();
838​
839 (
840 manager as unknown as {
841 handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
842 }
843 ).handleServerNotification(context, {
844 method: "item/completed",
845 params: {
846 item: {
847 type: "collabAgentToolCall",
848 id: "call_collab_1",
849 receiverThreadIds: ["child_provider_1"],
850 },
851 threadId: "provider_parent",
852 turnId: "turn_parent",
853 },
854 });
855 emitEvent.mockClear();
856 updateSession.mockClear();
857​
858 (
859 manager as unknown as {
860 handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
861 }
862 ).handleServerNotification(context, {
863 method: "turn/started",
864 params: {
865 threadId: "child_provider_1",
866 turn: { id: "turn_child_1" },
867 },
868 });
869​
870 (
871 manager as unknown as {
872 handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
873 }
874 ).handleServerNotification(context, {
875 method: "turn/completed",
876 params: {
877 threadId: "child_provider_1",
878 turn: { id: "turn_child_1", status: "completed" },
879 },
880 });
881​
882 expect(emitEvent).not.toHaveBeenCalled();
883 expect(updateSession).not.toHaveBeenCalled();
884 });
885​
886 it("rewrites child approval requests onto the parent turn", () => {
887 const { manager, context, emitEvent } = createCollabNotificationHarness();
888​
889 (
890 manager as unknown as {
891 handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
892 }
893 ).handleServerNotification(context, {
894 method: "item/completed",
895 params: {
896 item: {
897 type: "collabAgentToolCall",
898 id: "call_collab_1",
899 receiverThreadIds: ["child_provider_1"],
900 },
901 threadId: "provider_parent",
902 turnId: "turn_parent",
903 },
904 });
905 emitEvent.mockClear();
906​
907 (
908 manager as unknown as {
909 handleServerRequest: (context: unknown, request: Record<string, unknown>) => void;
910 }
911 ).handleServerRequest(context, {
912 id: 42,
913 method: "item/commandExecution/requestApproval",
914 params: {
915 threadId: "child_provider_1",
916 turnId: "turn_child_1",
917 itemId: "call_child_1",
918 command: "bun install",
919 },
920 });
921​
922 expect(Array.from(context.pendingApprovals.values())[0]).toEqual(
923 expect.objectContaining({
924 turnId: "turn_parent",
925 itemId: "call_child_1",
926 }),
927 );
928 expect(emitEvent).toHaveBeenCalledWith(
929 expect.objectContaining({
930 method: "item/commandExecution/requestApproval",
931 turnId: "turn_parent",
932 itemId: "call_child_1",
933 }),
934 );
935 });
936});
937​
938describe.skipIf(!process.env.CODEX_BINARY_PATH)("startSession live Codex resume", () => {
939 it("keeps prior thread history when resuming with a changed runtime mode", async () => {
940 const workspaceDir = mkdtempSync(path.join(os.tmpdir(), "codex-live-resume-"));
941 writeFileSync(path.join(workspaceDir, "README.md"), "hello\n", "utf8");
942​
943 const manager = new CodexAppServerManager();
944​
945 try {
946 const firstSession = await manager.startSession({
947 threadId: asThreadId("thread-live"),
948 provider: "codex",
949 cwd: workspaceDir,
950 runtimeMode: "full-access",
951 providerOptions: {
952 codex: {
953 ...(process.env.CODEX_BINARY_PATH ? { binaryPath: process.env.CODEX_BINARY_PATH } : {}),
954 ...(process.env.CODEX_HOME_PATH ? { homePath: process.env.CODEX_HOME_PATH } : {}),
955 },
956 },
957 });
958​
959 const firstTurn = await manager.sendTurn({
960 threadId: firstSession.threadId,
961 input: `Reply with exactly the word ALPHA ${randomUUID()}`,
962 });
963​
964 expect(firstTurn.threadId).toBe(firstSession.threadId);
965​
966 await vi.waitFor(
967 async () => {
968 const snapshot = await manager.readThread(firstSession.threadId);
969 expect(snapshot.turns.length).toBeGreaterThan(0);
970 },
971 { timeout: 120_000, interval: 1_000 },
972 );
973​
974 const firstSnapshot = await manager.readThread(firstSession.threadId);
975 const originalThreadId = firstSnapshot.threadId;
976 const originalTurnCount = firstSnapshot.turns.length;
977​
978 manager.stopSession(firstSession.threadId);
979​
980 const resumedSession = await manager.startSession({
981 threadId: firstSession.threadId,
982 provider: "codex",
983 cwd: workspaceDir,
984 runtimeMode: "approval-required",
985 resumeCursor: firstSession.resumeCursor,
986 providerOptions: {
987 codex: {
988 ...(process.env.CODEX_BINARY_PATH ? { binaryPath: process.env.CODEX_BINARY_PATH } : {}),
989 ...(process.env.CODEX_HOME_PATH ? { homePath: process.env.CODEX_HOME_PATH } : {}),
990 },
991 },
992 });
993​
994 expect(resumedSession.threadId).toBe(originalThreadId);
995​
996 const resumedSnapshotBeforeTurn = await manager.readThread(resumedSession.threadId);
997 expect(resumedSnapshotBeforeTurn.threadId).toBe(originalThreadId);
998 expect(resumedSnapshotBeforeTurn.turns.length).toBeGreaterThanOrEqual(originalTurnCount);
999​
1000 await manager.sendTurn({
1001 threadId: resumedSession.threadId,
1002 input: `Reply with exactly the word BETA ${randomUUID()}`,
1003 });
1004​
1005 await vi.waitFor(
1006 async () => {
1007 const snapshot = await manager.readThread(resumedSession.threadId);
1008 expect(snapshot.turns.length).toBeGreaterThan(originalTurnCount);
1009 },
1010 { timeout: 120_000, interval: 1_000 },
1011 );
1012 } finally {
1013 manager.stopAll();
1014 rmSync(workspaceDir, { recursive: true, force: true });
1016 }, 180_000);
1017});