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

codexAppServerManager.test.ts

1,070 lines30.4 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.make(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.make("req-user-input-1"),
115 {
116 requestId: ApprovalRequestId.make("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("process stderr events", () => {
211 it("emits classified stderr lines as notifications", () => {
212 const manager = new CodexAppServerManager();
213 const emitEvent = vi
214 .spyOn(manager as unknown as { emitEvent: (...args: unknown[]) => void }, "emitEvent")
215 .mockImplementation(() => {});
216​
217 (
218 manager as unknown as {
219 emitNotificationEvent: (
220 context: { session: { threadId: ThreadId } },
221 method: string,
222 message: string,
223 ) => void;
224 }
225 ).emitNotificationEvent(
226 {
227 session: {
228 threadId: asThreadId("thread-1"),
229 },
230 },
231 "process/stderr",
232 "fatal: permission denied",
233 );
234​
235 expect(emitEvent).toHaveBeenCalledWith(
236 expect.objectContaining({
237 kind: "notification",
238 method: "process/stderr",
239 threadId: "thread-1",
240 message: "fatal: permission denied",
241 }),
242 );
243 });
244});
245​
246describe("normalizeCodexModelSlug", () => {
247 it("maps 5.3 aliases to gpt-5.3-codex", () => {
248 expect(normalizeCodexModelSlug("5.3")).toBe("gpt-5.3-codex");
249 expect(normalizeCodexModelSlug("gpt-5.3")).toBe("gpt-5.3-codex");
250 });
251​
252 it("prefers codex id when model differs", () => {
253 expect(normalizeCodexModelSlug("gpt-5.3", "gpt-5.3-codex")).toBe("gpt-5.3-codex");
254 });
255​
256 it("keeps non-aliased models as-is", () => {
257 expect(normalizeCodexModelSlug("gpt-5.2-codex")).toBe("gpt-5.2-codex");
258 expect(normalizeCodexModelSlug("gpt-5.2")).toBe("gpt-5.2");
259 });
260});
261​
262describe("isRecoverableThreadResumeError", () => {
263 it("matches not-found resume errors", () => {
264 expect(
265 isRecoverableThreadResumeError(new Error("thread/resume failed: thread not found")),
266 ).toBe(true);
267 });
268​
269 it("ignores non-resume errors", () => {
270 expect(
271 isRecoverableThreadResumeError(new Error("thread/start failed: permission denied")),
272 ).toBe(false);
273 });
274​
275 it("ignores non-recoverable resume errors", () => {
276 expect(
277 isRecoverableThreadResumeError(
278 new Error("thread/resume failed: timed out waiting for server"),
279 ),
280 ).toBe(false);
281 });
282});
283​
284describe("readCodexAccountSnapshot", () => {
285 it("disables spark for chatgpt plus accounts", () => {
286 expect(
287 readCodexAccountSnapshot({
288 type: "chatgpt",
289 email: "plus@example.com",
290 planType: "plus",
291 }),
292 ).toEqual({
293 type: "chatgpt",
294 planType: "plus",
295 sparkEnabled: false,
296 });
297 });
298​
299 it("keeps spark enabled for chatgpt pro accounts", () => {
300 expect(
301 readCodexAccountSnapshot({
302 type: "chatgpt",
303 email: "pro@example.com",
304 planType: "pro",
305 }),
306 ).toEqual({
307 type: "chatgpt",
308 planType: "pro",
309 sparkEnabled: true,
310 });
311 });
312​
313 it("disables spark for api key accounts", () => {
314 expect(
315 readCodexAccountSnapshot({
316 type: "apiKey",
317 }),
318 ).toEqual({
319 type: "apiKey",
320 planType: null,
321 sparkEnabled: false,
322 });
323 });
324​
325 it("disables spark for unknown chatgpt plans", () => {
326 expect(
327 readCodexAccountSnapshot({
328 type: "chatgpt",
329 email: "unknown@example.com",
330 }),
331 ).toEqual({
332 type: "chatgpt",
333 planType: "unknown",
334 sparkEnabled: false,
335 });
336 });
337});
338​
339describe("resolveCodexModelForAccount", () => {
340 it("falls back from spark to default for unsupported chatgpt plans", () => {
341 expect(
342 resolveCodexModelForAccount("gpt-5.3-codex-spark", {
343 type: "chatgpt",
344 planType: "plus",
345 sparkEnabled: false,
346 }),
347 ).toBe("gpt-5.3-codex");
348 });
349​
350 it("keeps spark for supported plans", () => {
351 expect(
352 resolveCodexModelForAccount("gpt-5.3-codex-spark", {
353 type: "chatgpt",
354 planType: "pro",
355 sparkEnabled: true,
356 }),
357 ).toBe("gpt-5.3-codex-spark");
358 });
359​
360 it("falls back from spark to default for api key auth", () => {
361 expect(
362 resolveCodexModelForAccount("gpt-5.3-codex-spark", {
363 type: "apiKey",
364 planType: null,
365 sparkEnabled: false,
366 }),
367 ).toBe("gpt-5.3-codex");
368 });
369});
370​
371describe("startSession", () => {
372 it("enables Codex experimental api capabilities during initialize", () => {
373 expect(buildCodexInitializeParams()).toEqual({
374 clientInfo: {
375 name: "t3code_desktop",
376 title: "T3 Code Desktop",
377 version: "0.1.0",
378 },
379 capabilities: {
380 experimentalApi: true,
381 },
382 });
383 });
384​
385 it("emits session/startFailed when resolving cwd throws before process launch", async () => {
386 const manager = new CodexAppServerManager();
387 const events: Array<{ method: string; kind: string; message?: string }> = [];
388 manager.on("event", (event) => {
389 events.push({
390 method: event.method,
391 kind: event.kind,
392 ...(event.message ? { message: event.message } : {}),
393 });
394 });
395​
396 const processCwd = vi.spyOn(process, "cwd").mockImplementation(() => {
397 throw new Error("cwd missing");
398 });
399 try {
400 await expect(
401 manager.startSession({
402 threadId: asThreadId("thread-1"),
403 provider: "codex",
404 binaryPath: "codex",
405 runtimeMode: "full-access",
406 }),
407 ).rejects.toThrow("cwd missing");
408 expect(events).toHaveLength(1);
409 expect(events[0]).toEqual({
410 method: "session/startFailed",
411 kind: "error",
412 message: "cwd missing",
413 });
414 } finally {
415 processCwd.mockRestore();
416 manager.stopAll();
417 }
418 });
419​
420 it("fails fast with an upgrade message when codex is below the minimum supported version", async () => {
421 const manager = new CodexAppServerManager();
422 const events: Array<{ method: string; kind: string; message?: string }> = [];
423 manager.on("event", (event) => {
424 events.push({
425 method: event.method,
426 kind: event.kind,
427 ...(event.message ? { message: event.message } : {}),
428 });
429 });
430​
431 const versionCheck = vi
432 .spyOn(
433 manager as unknown as {
434 assertSupportedCodexCliVersion: (input: {
435 binaryPath: string;
436 cwd: string;
437 homePath?: string;
438 }) => void;
439 },
440 "assertSupportedCodexCliVersion",
441 )
442 .mockImplementation(() => {
443 throw new Error(
444 "Codex CLI v0.36.0 is too old for T3 Code. Upgrade to v0.37.0 or newer and restart T3 Code.",
445 );
446 });
447​
448 try {
449 await expect(
450 manager.startSession({
451 threadId: asThreadId("thread-1"),
452 provider: "codex",
453 binaryPath: "codex",
454 runtimeMode: "full-access",
455 }),
456 ).rejects.toThrow(
457 "Codex CLI v0.36.0 is too old for T3 Code. Upgrade to v0.37.0 or newer and restart T3 Code.",
458 );
459 expect(versionCheck).toHaveBeenCalledTimes(1);
460 expect(events).toEqual([
461 {
462 method: "session/startFailed",
463 kind: "error",
464 message:
465 "Codex CLI v0.36.0 is too old for T3 Code. Upgrade to v0.37.0 or newer and restart T3 Code.",
466 },
467 ]);
468 } finally {
469 versionCheck.mockRestore();
470 manager.stopAll();
471 }
472 });
473});
474​
475describe("sendTurn", () => {
476 it("sends text and image user input items to turn/start", async () => {
477 const { manager, context, requireSession, sendRequest, updateSession } =
478 createSendTurnHarness();
479​
480 const result = await manager.sendTurn({
481 threadId: asThreadId("thread_1"),
482 input: "Inspect this image",
483 attachments: [
484 {
485 type: "image",
486 url: "data:image/png;base64,AAAA",
487 },
488 ],
489 model: "gpt-5.3",
490 serviceTier: "fast",
491 effort: "high",
492 });
493​
494 expect(result).toEqual({
495 threadId: "thread_1",
496 turnId: "turn_1",
497 resumeCursor: { threadId: "thread_1" },
498 });
499 expect(requireSession).toHaveBeenCalledWith("thread_1");
500 expect(sendRequest).toHaveBeenCalledWith(context, "turn/start", {
501 threadId: "thread_1",
502 input: [
503 {
504 type: "text",
505 text: "Inspect this image",
506 text_elements: [],
507 },
508 {
509 type: "image",
510 url: "data:image/png;base64,AAAA",
511 },
512 ],
513 model: "gpt-5.3-codex",
514 serviceTier: "fast",
515 effort: "high",
516 });
517 expect(updateSession).toHaveBeenCalledWith(context, {
518 status: "running",
519 activeTurnId: "turn_1",
520 resumeCursor: { threadId: "thread_1" },
521 });
522 });
523​
524 it("supports image-only turns", async () => {
525 const { manager, context, sendRequest } = createSendTurnHarness();
526​
527 await manager.sendTurn({
528 threadId: asThreadId("thread_1"),
529 attachments: [
530 {
531 type: "image",
532 url: "data:image/png;base64,BBBB",
533 },
534 ],
535 });
536​
537 expect(sendRequest).toHaveBeenCalledWith(context, "turn/start", {
538 threadId: "thread_1",
539 input: [
540 {
541 type: "image",
542 url: "data:image/png;base64,BBBB",
543 },
544 ],
545 model: "gpt-5.3-codex",
546 });
547 });
548​
549 it("passes Codex plan mode as a collaboration preset on turn/start", async () => {
550 const { manager, context, sendRequest } = createSendTurnHarness();
551​
552 await manager.sendTurn({
553 threadId: asThreadId("thread_1"),
554 input: "Plan the work",
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 the work",
564 text_elements: [],
565 },
566 ],
567 model: "gpt-5.3-codex",
568 collaborationMode: {
569 mode: "plan",
570 settings: {
571 model: "gpt-5.3-codex",
572 reasoning_effort: "medium",
573 developer_instructions: CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS,
574 },
575 },
576 });
577 });
578​
579 it("passes Codex default mode as a collaboration preset on turn/start", async () => {
580 const { manager, context, sendRequest } = createSendTurnHarness();
581​
582 await manager.sendTurn({
583 threadId: asThreadId("thread_1"),
584 input: "PLEASE IMPLEMENT THIS PLAN:\n- step 1",
585 interactionMode: "default",
586 });
587​
588 expect(sendRequest).toHaveBeenCalledWith(context, "turn/start", {
589 threadId: "thread_1",
590 input: [
591 {
592 type: "text",
593 text: "PLEASE IMPLEMENT THIS PLAN:\n- step 1",
594 text_elements: [],
595 },
596 ],
597 model: "gpt-5.3-codex",
598 collaborationMode: {
599 mode: "default",
600 settings: {
601 model: "gpt-5.3-codex",
602 reasoning_effort: "medium",
603 developer_instructions: CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS,
604 },
605 },
606 });
607 });
608​
609 it("keeps the session model when interaction mode is set without an explicit model", async () => {
610 const { manager, context, sendRequest } = createSendTurnHarness();
611 context.session.model = "gpt-5.2-codex";
612​
613 await manager.sendTurn({
614 threadId: asThreadId("thread_1"),
615 input: "Plan this with my current session model",
616 interactionMode: "plan",
617 });
618​
619 expect(sendRequest).toHaveBeenCalledWith(context, "turn/start", {
620 threadId: "thread_1",
621 input: [
622 {
623 type: "text",
624 text: "Plan this with my current session model",
625 text_elements: [],
626 },
627 ],
628 model: "gpt-5.2-codex",
629 collaborationMode: {
630 mode: "plan",
631 settings: {
632 model: "gpt-5.2-codex",
633 reasoning_effort: "medium",
634 developer_instructions: CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS,
635 },
636 },
637 });
638 });
639​
640 it("rejects empty turn input", async () => {
641 const { manager } = createSendTurnHarness();
642​
643 await expect(
644 manager.sendTurn({
645 threadId: asThreadId("thread_1"),
646 }),
647 ).rejects.toThrow("Turn input must include text or attachments.");
648 });
649});
650​
651describe("thread checkpoint control", () => {
652 it("reads thread turns from thread/read", async () => {
653 const { manager, context, requireSession, sendRequest } = createThreadControlHarness();
654 sendRequest.mockResolvedValue({
655 thread: {
656 id: "thread_1",
657 turns: [
658 {
659 id: "turn_1",
660 items: [{ type: "userMessage", content: [{ type: "text", text: "hello" }] }],
661 },
662 ],
663 },
664 });
665​
666 const result = await manager.readThread(asThreadId("thread_1"));
667​
668 expect(requireSession).toHaveBeenCalledWith("thread_1");
669 expect(sendRequest).toHaveBeenCalledWith(context, "thread/read", {
670 threadId: "thread_1",
671 includeTurns: true,
672 });
673 expect(result).toEqual({
674 threadId: "thread_1",
675 turns: [
676 {
677 id: "turn_1",
678 items: [{ type: "userMessage", content: [{ type: "text", text: "hello" }] }],
679 },
680 ],
681 });
682 });
683​
684 it("reads thread turns from flat thread/read responses", async () => {
685 const { manager, context, sendRequest } = createThreadControlHarness();
686 sendRequest.mockResolvedValue({
687 threadId: "thread_1",
688 turns: [
689 {
690 id: "turn_1",
691 items: [{ type: "userMessage", content: [{ type: "text", text: "hello" }] }],
692 },
693 ],
694 });
695​
696 const result = await manager.readThread(asThreadId("thread_1"));
697​
698 expect(sendRequest).toHaveBeenCalledWith(context, "thread/read", {
699 threadId: "thread_1",
700 includeTurns: true,
701 });
702 expect(result).toEqual({
703 threadId: "thread_1",
704 turns: [
705 {
706 id: "turn_1",
707 items: [{ type: "userMessage", content: [{ type: "text", text: "hello" }] }],
708 },
709 ],
710 });
711 });
712​
713 it("rolls back turns via thread/rollback and resets session running state", async () => {
714 const { manager, context, sendRequest, updateSession } = createThreadControlHarness();
715 sendRequest.mockResolvedValue({
716 thread: {
717 id: "thread_1",
718 turns: [],
719 },
720 });
721​
722 const result = await manager.rollbackThread(asThreadId("thread_1"), 2);
723​
724 expect(sendRequest).toHaveBeenCalledWith(context, "thread/rollback", {
725 threadId: "thread_1",
726 numTurns: 2,
727 });
728 expect(updateSession).toHaveBeenCalledWith(context, {
729 status: "ready",
730 activeTurnId: undefined,
731 });
732 expect(result).toEqual({
733 threadId: "thread_1",
734 turns: [],
735 });
736 });
737});
738​
739describe("respondToUserInput", () => {
740 it("serializes canonical answers to Codex native answer objects", async () => {
741 const { manager, context, requireSession, writeMessage, emitEvent } =
742 createPendingUserInputHarness();
743​
744 await manager.respondToUserInput(
745 asThreadId("thread_1"),
746 ApprovalRequestId.make("req-user-input-1"),
747 {
748 scope: "All request methods",
749 compat: "Keep current envelope",
750 },
751 );
752​
753 expect(requireSession).toHaveBeenCalledWith("thread_1");
754 expect(writeMessage).toHaveBeenCalledWith(context, {
755 id: 42,
756 result: {
757 answers: {
758 scope: { answers: ["All request methods"] },
759 compat: { answers: ["Keep current envelope"] },
760 },
761 },
762 });
763 expect(emitEvent).toHaveBeenCalledWith(
764 expect.objectContaining({
765 method: "item/tool/requestUserInput/answered",
766 payload: {
767 requestId: "req-user-input-1",
768 answers: {
769 scope: { answers: ["All request methods"] },
770 compat: { answers: ["Keep current envelope"] },
771 },
772 },
773 }),
774 );
775 });
776​
777 it("preserves explicit empty multi-select answers", async () => {
778 const { manager, context, requireSession, writeMessage, emitEvent } =
779 createPendingUserInputHarness();
780​
781 await manager.respondToUserInput(
782 asThreadId("thread_1"),
783 ApprovalRequestId.make("req-user-input-1"),
784 {
785 scope: [],
786 },
787 );
788​
789 expect(requireSession).toHaveBeenCalledWith("thread_1");
790 expect(writeMessage).toHaveBeenCalledWith(context, {
791 id: 42,
792 result: {
793 answers: {
794 scope: { answers: [] },
795 },
796 },
797 });
798 expect(emitEvent).toHaveBeenCalledWith(
799 expect.objectContaining({
800 method: "item/tool/requestUserInput/answered",
801 payload: {
802 requestId: "req-user-input-1",
803 answers: {
804 scope: { answers: [] },
805 },
806 },
807 }),
808 );
809 });
810​
811 it("tracks file-read approval requests with the correct method", () => {
812 const manager = new CodexAppServerManager();
813 const context = {
814 session: {
815 sessionId: "sess_1",
816 provider: "codex",
817 status: "ready",
818 threadId: asThreadId("thread_1"),
819 resumeCursor: { threadId: "thread_1" },
820 createdAt: "2026-02-10T00:00:00.000Z",
821 updatedAt: "2026-02-10T00:00:00.000Z",
822 },
823 pendingApprovals: new Map(),
824 pendingUserInputs: new Map(),
825 collabReceiverTurns: new Map(),
826 };
827 type ApprovalRequestContext = {
828 session: typeof context.session;
829 pendingApprovals: typeof context.pendingApprovals;
830 pendingUserInputs: typeof context.pendingUserInputs;
831 };
832​
833 (
834 manager as unknown as {
835 handleServerRequest: (
836 context: ApprovalRequestContext,
837 request: Record<string, unknown>,
838 ) => void;
839 }
840 ).handleServerRequest(context, {
841 jsonrpc: "2.0",
842 id: 42,
843 method: "item/fileRead/requestApproval",
844 params: {},
845 });
846​
847 const request = Array.from(context.pendingApprovals.values())[0];
848 expect(request?.requestKind).toBe("file-read");
849 expect(request?.method).toBe("item/fileRead/requestApproval");
850 });
851});
852​
853describe("collab child conversation routing", () => {
854 it("rewrites child notification turn ids onto the parent turn", () => {
855 const { manager, context, emitEvent } = createCollabNotificationHarness();
856​
857 (
858 manager as unknown as {
859 handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
860 }
861 ).handleServerNotification(context, {
862 method: "item/completed",
863 params: {
864 item: {
865 type: "collabAgentToolCall",
866 id: "call_collab_1",
867 receiverThreadIds: ["child_provider_1"],
868 },
869 threadId: "provider_parent",
870 turnId: "turn_parent",
871 },
872 });
873​
874 (
875 manager as unknown as {
876 handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
877 }
878 ).handleServerNotification(context, {
879 method: "item/agentMessage/delta",
880 params: {
881 threadId: "child_provider_1",
882 turnId: "turn_child_1",
883 itemId: "msg_child_1",
884 delta: "working",
885 },
886 });
887​
888 expect(emitEvent).toHaveBeenLastCalledWith(
889 expect.objectContaining({
890 method: "item/agentMessage/delta",
891 turnId: "turn_parent",
892 itemId: "msg_child_1",
893 }),
894 );
895 });
896​
897 it("suppresses child lifecycle notifications so they cannot replace the parent turn", () => {
898 const { manager, context, emitEvent, updateSession } = createCollabNotificationHarness();
899​
900 (
901 manager as unknown as {
902 handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
903 }
904 ).handleServerNotification(context, {
905 method: "item/completed",
906 params: {
907 item: {
908 type: "collabAgentToolCall",
909 id: "call_collab_1",
910 receiverThreadIds: ["child_provider_1"],
911 },
912 threadId: "provider_parent",
913 turnId: "turn_parent",
914 },
915 });
916 emitEvent.mockClear();
917 updateSession.mockClear();
918​
919 (
920 manager as unknown as {
921 handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
922 }
923 ).handleServerNotification(context, {
924 method: "turn/started",
925 params: {
926 threadId: "child_provider_1",
927 turn: { id: "turn_child_1" },
928 },
929 });
930​
931 (
932 manager as unknown as {
933 handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
934 }
935 ).handleServerNotification(context, {
936 method: "turn/completed",
937 params: {
938 threadId: "child_provider_1",
939 turn: { id: "turn_child_1", status: "completed" },
940 },
941 });
942​
943 expect(emitEvent).not.toHaveBeenCalled();
944 expect(updateSession).not.toHaveBeenCalled();
945 });
946​
947 it("rewrites child approval requests onto the parent turn", () => {
948 const { manager, context, emitEvent } = createCollabNotificationHarness();
949​
950 (
951 manager as unknown as {
952 handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
953 }
954 ).handleServerNotification(context, {
955 method: "item/completed",
956 params: {
957 item: {
958 type: "collabAgentToolCall",
959 id: "call_collab_1",
960 receiverThreadIds: ["child_provider_1"],
961 },
962 threadId: "provider_parent",
963 turnId: "turn_parent",
964 },
965 });
966 emitEvent.mockClear();
967​
968 (
969 manager as unknown as {
970 handleServerRequest: (context: unknown, request: Record<string, unknown>) => void;
971 }
972 ).handleServerRequest(context, {
973 id: 42,
974 method: "item/commandExecution/requestApproval",
975 params: {
976 threadId: "child_provider_1",
977 turnId: "turn_child_1",
978 itemId: "call_child_1",
979 command: "bun install",
980 },
981 });
982​
983 expect(Array.from(context.pendingApprovals.values())[0]).toEqual(
984 expect.objectContaining({
985 turnId: "turn_parent",
986 itemId: "call_child_1",
987 }),
988 );
989 expect(emitEvent).toHaveBeenCalledWith(
990 expect.objectContaining({
991 method: "item/commandExecution/requestApproval",
992 turnId: "turn_parent",
993 itemId: "call_child_1",
994 }),
995 );
996 });
997});
998​
999describe.skipIf(!process.env.CODEX_BINARY_PATH)("startSession live Codex resume", () => {
1000 it("keeps prior thread history when resuming with a changed runtime mode", async () => {
1001 const workspaceDir = mkdtempSync(path.join(os.tmpdir(), "codex-live-resume-"));
1002 writeFileSync(path.join(workspaceDir, "README.md"), "hello\n", "utf8");
1003​
1004 const manager = new CodexAppServerManager();
1005​
1006 try {
1007 const firstSession = await manager.startSession({
1008 threadId: asThreadId("thread-live"),
1009 provider: "codex",
1010 cwd: workspaceDir,
1011 runtimeMode: "full-access",
1012 binaryPath: process.env.CODEX_BINARY_PATH!,
1013 ...(process.env.CODEX_HOME_PATH ? { homePath: process.env.CODEX_HOME_PATH } : {}),
1014 });
1015​
1016 const firstTurn = await manager.sendTurn({
1017 threadId: firstSession.threadId,
1018 input: `Reply with exactly the word ALPHA ${randomUUID()}`,
1019 });
1020​
1021 expect(firstTurn.threadId).toBe(firstSession.threadId);
1022​
1023 await vi.waitFor(
1024 async () => {
1025 const snapshot = await manager.readThread(firstSession.threadId);
1026 expect(snapshot.turns.length).toBeGreaterThan(0);
1027 },
1028 { timeout: 120_000, interval: 1_000 },
1029 );
1030​
1031 const firstSnapshot = await manager.readThread(firstSession.threadId);
1032 const originalThreadId = firstSnapshot.threadId;
1033 const originalTurnCount = firstSnapshot.turns.length;
1034​
1035 manager.stopSession(firstSession.threadId);
1036​
1037 const resumedSession = await manager.startSession({
1038 threadId: firstSession.threadId,
1039 provider: "codex",
1040 cwd: workspaceDir,
1041 runtimeMode: "approval-required",
1042 resumeCursor: firstSession.resumeCursor,
1043 binaryPath: process.env.CODEX_BINARY_PATH!,
1044 ...(process.env.CODEX_HOME_PATH ? { homePath: process.env.CODEX_HOME_PATH } : {}),
1045 });
1046​
1047 expect(resumedSession.threadId).toBe(originalThreadId);
1048​
1049 const resumedSnapshotBeforeTurn = await manager.readThread(resumedSession.threadId);
1050 expect(resumedSnapshotBeforeTurn.threadId).toBe(originalThreadId);
1051 expect(resumedSnapshotBeforeTurn.turns.length).toBeGreaterThanOrEqual(originalTurnCount);
1052​
1053 await manager.sendTurn({
1054 threadId: resumedSession.threadId,
1055 input: `Reply with exactly the word BETA ${randomUUID()}`,
1056 });
1057​
1058 await vi.waitFor(
1059 async () => {
1060 const snapshot = await manager.readThread(resumedSession.threadId);
1061 expect(snapshot.turns.length).toBeGreaterThan(originalTurnCount);
1062 },
1063 { timeout: 120_000, interval: 1_000 },
1064 );
1065 } finally {
1066 manager.stopAll();
1067 rmSync(workspaceDir, { recursive: true, force: true });
1069 }, 180_000);
1070});