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

codexAppServerManager.test.ts

1,143 lines32.5 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 it("disposes an existing session before starting a replacement for the same thread", async () => {
475 const manager = new CodexAppServerManager();
476 const existingContext = {
477 session: {
478 provider: "codex",
479 status: "ready",
480 threadId: asThreadId("thread-1"),
481 runtimeMode: "full-access",
482 createdAt: "2026-02-10T00:00:00.000Z",
483 updatedAt: "2026-02-10T00:00:00.000Z",
484 },
485 };
486​
487 (
488 manager as unknown as {
489 sessions: Map<ThreadId, typeof existingContext>;
490 }
491 ).sessions.set(asThreadId("thread-1"), existingContext);
492​
493 const disposeSession = vi
494 .spyOn(
495 manager as unknown as {
496 disposeSession: (
497 context: typeof existingContext,
498 options?: { readonly emitLifecycleEvent?: boolean },
499 ) => void;
500 },
501 "disposeSession",
502 )
503 .mockImplementation(() => {});
504 const assertSupportedCodexCliVersion = vi
505 .spyOn(
506 manager as unknown as {
507 assertSupportedCodexCliVersion: (input: {
508 binaryPath: string;
509 cwd: string;
510 homePath?: string;
511 }) => void;
512 },
513 "assertSupportedCodexCliVersion",
514 )
515 .mockImplementation(() => {});
516 const processCwd = vi.spyOn(process, "cwd").mockImplementation(() => {
517 throw new Error("cwd missing");
518 });
519​
520 try {
521 await expect(
522 manager.startSession({
523 threadId: asThreadId("thread-1"),
524 provider: "codex",
525 binaryPath: "codex",
526 runtimeMode: "full-access",
527 }),
528 ).rejects.toThrow("cwd missing");
529​
530 expect(disposeSession).toHaveBeenCalledWith(existingContext, {
531 emitLifecycleEvent: false,
532 });
533 expect(assertSupportedCodexCliVersion).not.toHaveBeenCalled();
534 } finally {
535 disposeSession.mockRestore();
536 assertSupportedCodexCliVersion.mockRestore();
537 processCwd.mockRestore();
538 (
539 manager as unknown as {
540 sessions: Map<ThreadId, typeof existingContext>;
541 }
542 ).sessions.clear();
543 manager.stopAll();
544 }
545 });
546});
547​
548describe("sendTurn", () => {
549 it("sends text and image user input items to turn/start", async () => {
550 const { manager, context, requireSession, sendRequest, updateSession } =
551 createSendTurnHarness();
552​
553 const result = await manager.sendTurn({
554 threadId: asThreadId("thread_1"),
555 input: "Inspect this image",
556 attachments: [
557 {
558 type: "image",
559 url: "data:image/png;base64,AAAA",
560 },
561 ],
562 model: "gpt-5.3",
563 serviceTier: "fast",
564 effort: "high",
565 });
566​
567 expect(result).toEqual({
568 threadId: "thread_1",
569 turnId: "turn_1",
570 resumeCursor: { threadId: "thread_1" },
571 });
572 expect(requireSession).toHaveBeenCalledWith("thread_1");
573 expect(sendRequest).toHaveBeenCalledWith(context, "turn/start", {
574 threadId: "thread_1",
575 input: [
576 {
577 type: "text",
578 text: "Inspect this image",
579 text_elements: [],
580 },
581 {
582 type: "image",
583 url: "data:image/png;base64,AAAA",
584 },
585 ],
586 model: "gpt-5.3-codex",
587 serviceTier: "fast",
588 effort: "high",
589 });
590 expect(updateSession).toHaveBeenCalledWith(context, {
591 status: "running",
592 activeTurnId: "turn_1",
593 resumeCursor: { threadId: "thread_1" },
594 });
595 });
596​
597 it("supports image-only turns", async () => {
598 const { manager, context, sendRequest } = createSendTurnHarness();
599​
600 await manager.sendTurn({
601 threadId: asThreadId("thread_1"),
602 attachments: [
603 {
604 type: "image",
605 url: "data:image/png;base64,BBBB",
606 },
607 ],
608 });
609​
610 expect(sendRequest).toHaveBeenCalledWith(context, "turn/start", {
611 threadId: "thread_1",
612 input: [
613 {
614 type: "image",
615 url: "data:image/png;base64,BBBB",
616 },
617 ],
618 model: "gpt-5.3-codex",
619 });
620 });
621​
622 it("passes Codex plan mode as a collaboration preset on turn/start", async () => {
623 const { manager, context, sendRequest } = createSendTurnHarness();
624​
625 await manager.sendTurn({
626 threadId: asThreadId("thread_1"),
627 input: "Plan the work",
628 interactionMode: "plan",
629 });
630​
631 expect(sendRequest).toHaveBeenCalledWith(context, "turn/start", {
632 threadId: "thread_1",
633 input: [
634 {
635 type: "text",
636 text: "Plan the work",
637 text_elements: [],
638 },
639 ],
640 model: "gpt-5.3-codex",
641 collaborationMode: {
642 mode: "plan",
643 settings: {
644 model: "gpt-5.3-codex",
645 reasoning_effort: "medium",
646 developer_instructions: CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS,
647 },
648 },
649 });
650 });
651​
652 it("passes Codex default mode as a collaboration preset on turn/start", async () => {
653 const { manager, context, sendRequest } = createSendTurnHarness();
654​
655 await manager.sendTurn({
656 threadId: asThreadId("thread_1"),
657 input: "PLEASE IMPLEMENT THIS PLAN:\n- step 1",
658 interactionMode: "default",
659 });
660​
661 expect(sendRequest).toHaveBeenCalledWith(context, "turn/start", {
662 threadId: "thread_1",
663 input: [
664 {
665 type: "text",
666 text: "PLEASE IMPLEMENT THIS PLAN:\n- step 1",
667 text_elements: [],
668 },
669 ],
670 model: "gpt-5.3-codex",
671 collaborationMode: {
672 mode: "default",
673 settings: {
674 model: "gpt-5.3-codex",
675 reasoning_effort: "medium",
676 developer_instructions: CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS,
677 },
678 },
679 });
680 });
681​
682 it("keeps the session model when interaction mode is set without an explicit model", async () => {
683 const { manager, context, sendRequest } = createSendTurnHarness();
684 context.session.model = "gpt-5.2-codex";
685​
686 await manager.sendTurn({
687 threadId: asThreadId("thread_1"),
688 input: "Plan this with my current session model",
689 interactionMode: "plan",
690 });
691​
692 expect(sendRequest).toHaveBeenCalledWith(context, "turn/start", {
693 threadId: "thread_1",
694 input: [
695 {
696 type: "text",
697 text: "Plan this with my current session model",
698 text_elements: [],
699 },
700 ],
701 model: "gpt-5.2-codex",
702 collaborationMode: {
703 mode: "plan",
704 settings: {
705 model: "gpt-5.2-codex",
706 reasoning_effort: "medium",
707 developer_instructions: CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS,
708 },
709 },
710 });
711 });
712​
713 it("rejects empty turn input", async () => {
714 const { manager } = createSendTurnHarness();
715​
716 await expect(
717 manager.sendTurn({
718 threadId: asThreadId("thread_1"),
719 }),
720 ).rejects.toThrow("Turn input must include text or attachments.");
721 });
722});
723​
724describe("thread checkpoint control", () => {
725 it("reads thread turns from thread/read", async () => {
726 const { manager, context, requireSession, sendRequest } = createThreadControlHarness();
727 sendRequest.mockResolvedValue({
728 thread: {
729 id: "thread_1",
730 turns: [
731 {
732 id: "turn_1",
733 items: [{ type: "userMessage", content: [{ type: "text", text: "hello" }] }],
734 },
735 ],
736 },
737 });
738​
739 const result = await manager.readThread(asThreadId("thread_1"));
740​
741 expect(requireSession).toHaveBeenCalledWith("thread_1");
742 expect(sendRequest).toHaveBeenCalledWith(context, "thread/read", {
743 threadId: "thread_1",
744 includeTurns: true,
745 });
746 expect(result).toEqual({
747 threadId: "thread_1",
748 turns: [
749 {
750 id: "turn_1",
751 items: [{ type: "userMessage", content: [{ type: "text", text: "hello" }] }],
752 },
753 ],
754 });
755 });
756​
757 it("reads thread turns from flat thread/read responses", async () => {
758 const { manager, context, sendRequest } = createThreadControlHarness();
759 sendRequest.mockResolvedValue({
760 threadId: "thread_1",
761 turns: [
762 {
763 id: "turn_1",
764 items: [{ type: "userMessage", content: [{ type: "text", text: "hello" }] }],
765 },
766 ],
767 });
768​
769 const result = await manager.readThread(asThreadId("thread_1"));
770​
771 expect(sendRequest).toHaveBeenCalledWith(context, "thread/read", {
772 threadId: "thread_1",
773 includeTurns: true,
774 });
775 expect(result).toEqual({
776 threadId: "thread_1",
777 turns: [
778 {
779 id: "turn_1",
780 items: [{ type: "userMessage", content: [{ type: "text", text: "hello" }] }],
781 },
782 ],
783 });
784 });
785​
786 it("rolls back turns via thread/rollback and resets session running state", async () => {
787 const { manager, context, sendRequest, updateSession } = createThreadControlHarness();
788 sendRequest.mockResolvedValue({
789 thread: {
790 id: "thread_1",
791 turns: [],
792 },
793 });
794​
795 const result = await manager.rollbackThread(asThreadId("thread_1"), 2);
796​
797 expect(sendRequest).toHaveBeenCalledWith(context, "thread/rollback", {
798 threadId: "thread_1",
799 numTurns: 2,
800 });
801 expect(updateSession).toHaveBeenCalledWith(context, {
802 status: "ready",
803 activeTurnId: undefined,
804 });
805 expect(result).toEqual({
806 threadId: "thread_1",
807 turns: [],
808 });
809 });
810});
811​
812describe("respondToUserInput", () => {
813 it("serializes canonical answers to Codex native answer objects", async () => {
814 const { manager, context, requireSession, writeMessage, emitEvent } =
815 createPendingUserInputHarness();
816​
817 await manager.respondToUserInput(
818 asThreadId("thread_1"),
819 ApprovalRequestId.make("req-user-input-1"),
820 {
821 scope: "All request methods",
822 compat: "Keep current envelope",
823 },
824 );
825​
826 expect(requireSession).toHaveBeenCalledWith("thread_1");
827 expect(writeMessage).toHaveBeenCalledWith(context, {
828 id: 42,
829 result: {
830 answers: {
831 scope: { answers: ["All request methods"] },
832 compat: { answers: ["Keep current envelope"] },
833 },
834 },
835 });
836 expect(emitEvent).toHaveBeenCalledWith(
837 expect.objectContaining({
838 method: "item/tool/requestUserInput/answered",
839 payload: {
840 requestId: "req-user-input-1",
841 answers: {
842 scope: { answers: ["All request methods"] },
843 compat: { answers: ["Keep current envelope"] },
844 },
845 },
846 }),
847 );
848 });
849​
850 it("preserves explicit empty multi-select answers", async () => {
851 const { manager, context, requireSession, writeMessage, emitEvent } =
852 createPendingUserInputHarness();
853​
854 await manager.respondToUserInput(
855 asThreadId("thread_1"),
856 ApprovalRequestId.make("req-user-input-1"),
857 {
858 scope: [],
859 },
860 );
861​
862 expect(requireSession).toHaveBeenCalledWith("thread_1");
863 expect(writeMessage).toHaveBeenCalledWith(context, {
864 id: 42,
865 result: {
866 answers: {
867 scope: { answers: [] },
868 },
869 },
870 });
871 expect(emitEvent).toHaveBeenCalledWith(
872 expect.objectContaining({
873 method: "item/tool/requestUserInput/answered",
874 payload: {
875 requestId: "req-user-input-1",
876 answers: {
877 scope: { answers: [] },
878 },
879 },
880 }),
881 );
882 });
883​
884 it("tracks file-read approval requests with the correct method", () => {
885 const manager = new CodexAppServerManager();
886 const context = {
887 session: {
888 sessionId: "sess_1",
889 provider: "codex",
890 status: "ready",
891 threadId: asThreadId("thread_1"),
892 resumeCursor: { threadId: "thread_1" },
893 createdAt: "2026-02-10T00:00:00.000Z",
894 updatedAt: "2026-02-10T00:00:00.000Z",
895 },
896 pendingApprovals: new Map(),
897 pendingUserInputs: new Map(),
898 collabReceiverTurns: new Map(),
899 };
900 type ApprovalRequestContext = {
901 session: typeof context.session;
902 pendingApprovals: typeof context.pendingApprovals;
903 pendingUserInputs: typeof context.pendingUserInputs;
904 };
905​
906 (
907 manager as unknown as {
908 handleServerRequest: (
909 context: ApprovalRequestContext,
910 request: Record<string, unknown>,
911 ) => void;
912 }
913 ).handleServerRequest(context, {
914 jsonrpc: "2.0",
915 id: 42,
916 method: "item/fileRead/requestApproval",
917 params: {},
918 });
919​
920 const request = Array.from(context.pendingApprovals.values())[0];
921 expect(request?.requestKind).toBe("file-read");
922 expect(request?.method).toBe("item/fileRead/requestApproval");
923 });
924});
925​
926describe("collab child conversation routing", () => {
927 it("rewrites child notification turn ids onto the parent turn", () => {
928 const { manager, context, emitEvent } = createCollabNotificationHarness();
929​
930 (
931 manager as unknown as {
932 handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
933 }
934 ).handleServerNotification(context, {
935 method: "item/completed",
936 params: {
937 item: {
938 type: "collabAgentToolCall",
939 id: "call_collab_1",
940 receiverThreadIds: ["child_provider_1"],
941 },
942 threadId: "provider_parent",
943 turnId: "turn_parent",
944 },
945 });
946​
947 (
948 manager as unknown as {
949 handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
950 }
951 ).handleServerNotification(context, {
952 method: "item/agentMessage/delta",
953 params: {
954 threadId: "child_provider_1",
955 turnId: "turn_child_1",
956 itemId: "msg_child_1",
957 delta: "working",
958 },
959 });
960​
961 expect(emitEvent).toHaveBeenLastCalledWith(
962 expect.objectContaining({
963 method: "item/agentMessage/delta",
964 turnId: "turn_parent",
965 itemId: "msg_child_1",
966 }),
967 );
968 });
969​
970 it("suppresses child lifecycle notifications so they cannot replace the parent turn", () => {
971 const { manager, context, emitEvent, updateSession } = createCollabNotificationHarness();
972​
973 (
974 manager as unknown as {
975 handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
976 }
977 ).handleServerNotification(context, {
978 method: "item/completed",
979 params: {
980 item: {
981 type: "collabAgentToolCall",
982 id: "call_collab_1",
983 receiverThreadIds: ["child_provider_1"],
984 },
985 threadId: "provider_parent",
986 turnId: "turn_parent",
987 },
988 });
989 emitEvent.mockClear();
990 updateSession.mockClear();
991​
992 (
993 manager as unknown as {
994 handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
995 }
996 ).handleServerNotification(context, {
997 method: "turn/started",
998 params: {
999 threadId: "child_provider_1",
1000 turn: { id: "turn_child_1" },
1001 },
1002 });
1003​
1005 manager as unknown as {
1006 handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
1008 ).handleServerNotification(context, {
1009 method: "turn/completed",
1010 params: {
1011 threadId: "child_provider_1",
1012 turn: { id: "turn_child_1", status: "completed" },
1013 },
1014 });
1015​
1016 expect(emitEvent).not.toHaveBeenCalled();
1017 expect(updateSession).not.toHaveBeenCalled();
1018 });
1019​
1020 it("rewrites child approval requests onto the parent turn", () => {
1021 const { manager, context, emitEvent } = createCollabNotificationHarness();
1022​
1024 manager as unknown as {
1025 handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
1027 ).handleServerNotification(context, {
1028 method: "item/completed",
1029 params: {
1030 item: {
1031 type: "collabAgentToolCall",
1032 id: "call_collab_1",
1033 receiverThreadIds: ["child_provider_1"],
1034 },
1035 threadId: "provider_parent",
1036 turnId: "turn_parent",
1037 },
1038 });
1039 emitEvent.mockClear();
1040​
1042 manager as unknown as {
1043 handleServerRequest: (context: unknown, request: Record<string, unknown>) => void;
1045 ).handleServerRequest(context, {
1046 id: 42,
1047 method: "item/commandExecution/requestApproval",
1048 params: {
1049 threadId: "child_provider_1",
1050 turnId: "turn_child_1",
1051 itemId: "call_child_1",
1052 command: "bun install",
1053 },
1054 });
1055​
1056 expect(Array.from(context.pendingApprovals.values())[0]).toEqual(
1057 expect.objectContaining({
1058 turnId: "turn_parent",
1059 itemId: "call_child_1",
1060 }),
1061 );
1062 expect(emitEvent).toHaveBeenCalledWith(
1063 expect.objectContaining({
1064 method: "item/commandExecution/requestApproval",
1065 turnId: "turn_parent",
1066 itemId: "call_child_1",
1067 }),
1068 );
1069 });
1070});
1071​
1072describe.skipIf(!process.env.CODEX_BINARY_PATH)("startSession live Codex resume", () => {
1073 it("keeps prior thread history when resuming with a changed runtime mode", async () => {
1074 const workspaceDir = mkdtempSync(path.join(os.tmpdir(), "codex-live-resume-"));
1075 writeFileSync(path.join(workspaceDir, "README.md"), "hello\n", "utf8");
1076​
1077 const manager = new CodexAppServerManager();
1078​
1079 try {
1080 const firstSession = await manager.startSession({
1081 threadId: asThreadId("thread-live"),
1082 provider: "codex",
1083 cwd: workspaceDir,
1084 runtimeMode: "full-access",
1085 binaryPath: process.env.CODEX_BINARY_PATH!,
1086 ...(process.env.CODEX_HOME_PATH ? { homePath: process.env.CODEX_HOME_PATH } : {}),
1087 });
1088​
1089 const firstTurn = await manager.sendTurn({
1090 threadId: firstSession.threadId,
1091 input: `Reply with exactly the word ALPHA ${randomUUID()}`,
1092 });
1093​
1094 expect(firstTurn.threadId).toBe(firstSession.threadId);
1095​
1096 await vi.waitFor(
1097 async () => {
1098 const snapshot = await manager.readThread(firstSession.threadId);
1099 expect(snapshot.turns.length).toBeGreaterThan(0);
1100 },
1101 { timeout: 120_000, interval: 1_000 },
1102 );
1103​
1104 const firstSnapshot = await manager.readThread(firstSession.threadId);
1105 const originalThreadId = firstSnapshot.threadId;
1106 const originalTurnCount = firstSnapshot.turns.length;
1107​
1108 manager.stopSession(firstSession.threadId);
1109​
1110 const resumedSession = await manager.startSession({
1111 threadId: firstSession.threadId,
1112 provider: "codex",
1113 cwd: workspaceDir,
1114 runtimeMode: "approval-required",
1115 resumeCursor: firstSession.resumeCursor,
1116 binaryPath: process.env.CODEX_BINARY_PATH!,
1117 ...(process.env.CODEX_HOME_PATH ? { homePath: process.env.CODEX_HOME_PATH } : {}),
1118 });
1119​
1120 expect(resumedSession.threadId).toBe(originalThreadId);
1121​
1122 const resumedSnapshotBeforeTurn = await manager.readThread(resumedSession.threadId);
1123 expect(resumedSnapshotBeforeTurn.threadId).toBe(originalThreadId);
1124 expect(resumedSnapshotBeforeTurn.turns.length).toBeGreaterThanOrEqual(originalTurnCount);
1125​
1126 await manager.sendTurn({
1127 threadId: resumedSession.threadId,
1128 input: `Reply with exactly the word BETA ${randomUUID()}`,
1129 });
1130​
1131 await vi.waitFor(
1132 async () => {
1133 const snapshot = await manager.readThread(resumedSession.threadId);
1134 expect(snapshot.turns.length).toBeGreaterThan(originalTurnCount);
1135 },
1136 { timeout: 120_000, interval: 1_000 },
1137 );
1138 } finally {
1139 manager.stopAll();
1140 rmSync(workspaceDir, { recursive: true, force: true });
1142 }, 180_000);
1143});