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

codexAppServerManager.test.ts

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