Open History to see the last commit
1import { describe, expect, it, vi } from "vitest";
2import { randomUUID } from "node:crypto";
3import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
4import os from "node:os";
5import path from "node:path";
6import { ApprovalRequestId, ThreadId } from "@t3tools/contracts";
7
8import {
9 buildCodexInitializeParams,
10 CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS,
11 CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS,
12 CodexAppServerManager,
13 classifyCodexStderrLine,
14 isRecoverableThreadResumeError,
15 normalizeCodexModelSlug,
16 readCodexAccountSnapshot,
17 resolveCodexModelForAccount,
18} from "./codexAppServerManager";
19
20const asThreadId = (value: string): ThreadId => ThreadId.makeUnsafe(value);
21
22function createSendTurnHarness() {
23 const manager = new CodexAppServerManager();
24 const context = {
25 session: {
26 provider: "codex",
27 status: "ready",
28 threadId: "thread_1",
29 runtimeMode: "full-access",
30 model: "gpt-5.3-codex",
31 resumeCursor: { threadId: "thread_1" },
32 createdAt: "2026-02-10T00:00:00.000Z",
33 updatedAt: "2026-02-10T00:00:00.000Z",
34 },
35 account: {
36 type: "unknown",
37 planType: null,
38 sparkEnabled: true,
39 },
40 };
41
42 const requireSession = vi
43 .spyOn(
44 manager as unknown as { requireSession: (sessionId: string) => unknown },
45 "requireSession",
46 )
47 .mockReturnValue(context);
48 const sendRequest = vi
49 .spyOn(
50 manager as unknown as { sendRequest: (...args: unknown[]) => Promise<unknown> },
51 "sendRequest",
52 )
53 .mockResolvedValue({
54 turn: {
55 id: "turn_1",
56 },
57 });
58 const updateSession = vi
59 .spyOn(manager as unknown as { updateSession: (...args: unknown[]) => void }, "updateSession")
60 .mockImplementation(() => {});
61
62 return { manager, context, requireSession, sendRequest, updateSession };
63}
64
65function createThreadControlHarness() {
66 const manager = new CodexAppServerManager();
67 const context = {
68 session: {
69 provider: "codex",
70 status: "ready",
71 threadId: "thread_1",
72 runtimeMode: "full-access",
73 model: "gpt-5.3-codex",
74 resumeCursor: { threadId: "thread_1" },
75 createdAt: "2026-02-10T00:00:00.000Z",
76 updatedAt: "2026-02-10T00:00:00.000Z",
77 },
78 };
79
80 const requireSession = vi
81 .spyOn(
82 manager as unknown as { requireSession: (sessionId: string) => unknown },
83 "requireSession",
84 )
85 .mockReturnValue(context);
86 const sendRequest = vi.spyOn(
87 manager as unknown as { sendRequest: (...args: unknown[]) => Promise<unknown> },
88 "sendRequest",
89 );
90 const updateSession = vi
91 .spyOn(manager as unknown as { updateSession: (...args: unknown[]) => void }, "updateSession")
92 .mockImplementation(() => {});
93
94 return { manager, context, requireSession, sendRequest, updateSession };
95}
96
97function createPendingUserInputHarness() {
98 const manager = new CodexAppServerManager();
99 const context = {
100 session: {
101 provider: "codex",
102 status: "ready",
103 threadId: "thread_1",
104 runtimeMode: "full-access",
105 model: "gpt-5.3-codex",
106 resumeCursor: { threadId: "thread_1" },
107 createdAt: "2026-02-10T00:00:00.000Z",
108 updatedAt: "2026-02-10T00:00:00.000Z",
109 },
110 pendingUserInputs: new Map([
111 [
112 ApprovalRequestId.makeUnsafe("req-user-input-1"),
113 {
114 requestId: ApprovalRequestId.makeUnsafe("req-user-input-1"),
115 jsonRpcId: 42,
116 threadId: asThreadId("thread_1"),
117 },
118 ],
119 ]),
120 };
121
122 const requireSession = vi
123 .spyOn(
124 manager as unknown as { requireSession: (sessionId: string) => unknown },
125 "requireSession",
126 )
127 .mockReturnValue(context);
128 const writeMessage = vi
129 .spyOn(manager as unknown as { writeMessage: (...args: unknown[]) => void }, "writeMessage")
130 .mockImplementation(() => {});
131 const emitEvent = vi
132 .spyOn(manager as unknown as { emitEvent: (...args: unknown[]) => void }, "emitEvent")
133 .mockImplementation(() => {});
134
135 return { manager, context, requireSession, writeMessage, emitEvent };
136}
137
138describe("classifyCodexStderrLine", () => {
139 it("ignores empty lines", () => {
140 expect(classifyCodexStderrLine(" ")).toBeNull();
141 });
142
143 it("ignores non-error structured codex logs", () => {
144 const line =
145 "2026-02-08T04:24:19.241256Z WARN codex_core::features: unknown feature key in config: skills";
146 expect(classifyCodexStderrLine(line)).toBeNull();
147 });
148
149 it("ignores known benign rollout path errors", () => {
150 const line =
151 "\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";
152 expect(classifyCodexStderrLine(line)).toBeNull();
153 });
154
155 it("keeps unknown structured errors", () => {
156 const line = "2026-02-08T04:24:20.085687Z ERROR codex_core::runtime: unrecoverable failure";
157 expect(classifyCodexStderrLine(line)).toEqual({
158 message: line,
159 });
160 });
161
162 it("keeps plain stderr messages", () => {
163 const line = "fatal: permission denied";
164 expect(classifyCodexStderrLine(line)).toEqual({
165 message: line,
166 });
167 });
168});
169
170describe("normalizeCodexModelSlug", () => {
171 it("maps 5.3 aliases to gpt-5.3-codex", () => {
172 expect(normalizeCodexModelSlug("5.3")).toBe("gpt-5.3-codex");
173 expect(normalizeCodexModelSlug("gpt-5.3")).toBe("gpt-5.3-codex");
174 });
175
176 it("prefers codex id when model differs", () => {
177 expect(normalizeCodexModelSlug("gpt-5.3", "gpt-5.3-codex")).toBe("gpt-5.3-codex");
178 });
179
180 it("keeps non-aliased models as-is", () => {
181 expect(normalizeCodexModelSlug("gpt-5.2-codex")).toBe("gpt-5.2-codex");
182 expect(normalizeCodexModelSlug("gpt-5.2")).toBe("gpt-5.2");
183 });
184});
185
186describe("isRecoverableThreadResumeError", () => {
187 it("matches not-found resume errors", () => {
188 expect(
189 isRecoverableThreadResumeError(new Error("thread/resume failed: thread not found")),
190 ).toBe(true);
191 });
192
193 it("ignores non-resume errors", () => {
194 expect(
195 isRecoverableThreadResumeError(new Error("thread/start failed: permission denied")),
196 ).toBe(false);
197 });
198
199 it("ignores non-recoverable resume errors", () => {
200 expect(
201 isRecoverableThreadResumeError(
202 new Error("thread/resume failed: timed out waiting for server"),
203 ),
204 ).toBe(false);
205 });
206});
207
208describe("readCodexAccountSnapshot", () => {
209 it("disables spark for chatgpt plus accounts", () => {
210 expect(
211 readCodexAccountSnapshot({
212 type: "chatgpt",
213 email: "plus@example.com",
214 planType: "plus",
215 }),
216 ).toEqual({
217 type: "chatgpt",
218 planType: "plus",
219 sparkEnabled: false,
220 });
221 });
222
223 it("keeps spark enabled for chatgpt pro accounts", () => {
224 expect(
225 readCodexAccountSnapshot({
226 type: "chatgpt",
227 email: "pro@example.com",
228 planType: "pro",
229 }),
230 ).toEqual({
231 type: "chatgpt",
232 planType: "pro",
233 sparkEnabled: true,
234 });
235 });
236
237 it("keeps spark enabled for api key accounts", () => {
238 expect(
239 readCodexAccountSnapshot({
240 type: "apiKey",
241 }),
242 ).toEqual({
243 type: "apiKey",
244 planType: null,
245 sparkEnabled: true,
246 });
247 });
248});
249
250describe("resolveCodexModelForAccount", () => {
251 it("falls back from spark to default for unsupported chatgpt plans", () => {
252 expect(
253 resolveCodexModelForAccount("gpt-5.3-codex-spark", {
254 type: "chatgpt",
255 planType: "plus",
256 sparkEnabled: false,
257 }),
258 ).toBe("gpt-5.3-codex");
259 });
260
261 it("keeps spark for supported plans", () => {
262 expect(
263 resolveCodexModelForAccount("gpt-5.3-codex-spark", {
264 type: "chatgpt",
265 planType: "pro",
266 sparkEnabled: true,
267 }),
268 ).toBe("gpt-5.3-codex-spark");
269 });
270});
271
272describe("startSession", () => {
273 it("enables Codex experimental api capabilities during initialize", () => {
274 expect(buildCodexInitializeParams()).toEqual({
275 clientInfo: {
276 name: "t3code_desktop",
277 title: "T3 Code Desktop",
278 version: "0.1.0",
279 },
280 capabilities: {
281 experimentalApi: true,
282 },
283 });
284 });
285
286 it("emits session/startFailed when resolving cwd throws before process launch", async () => {
287 const manager = new CodexAppServerManager();
288 const events: Array<{ method: string; kind: string; message?: string }> = [];
289 manager.on("event", (event) => {
290 events.push({
291 method: event.method,
292 kind: event.kind,
293 ...(event.message ? { message: event.message } : {}),
294 });
295 });
296
297 const processCwd = vi.spyOn(process, "cwd").mockImplementation(() => {
298 throw new Error("cwd missing");
299 });
300 try {
301 await expect(
302 manager.startSession({
303 threadId: asThreadId("thread-1"),
304 provider: "codex",
305 runtimeMode: "full-access",
306 }),
307 ).rejects.toThrow("cwd missing");
308 expect(events).toHaveLength(1);
309 expect(events[0]).toEqual({
310 method: "session/startFailed",
311 kind: "error",
312 message: "cwd missing",
313 });
314 } finally {
315 processCwd.mockRestore();
316 manager.stopAll();
317 }
318 });
319});
320
321describe("sendTurn", () => {
322 it("sends text and image user input items to turn/start", async () => {
323 const { manager, context, requireSession, sendRequest, updateSession } =
324 createSendTurnHarness();
325
326 const result = await manager.sendTurn({
327 threadId: asThreadId("thread_1"),
328 input: "Inspect this image",
329 attachments: [
330 {
331 type: "image",
332 url: "data:image/png;base64,AAAA",
333 },
334 ],
335 model: "gpt-5.3",
336 serviceTier: "fast",
337 effort: "high",
338 });
339
340 expect(result).toEqual({
341 threadId: "thread_1",
342 turnId: "turn_1",
343 resumeCursor: { threadId: "thread_1" },
344 });
345 expect(requireSession).toHaveBeenCalledWith("thread_1");
346 expect(sendRequest).toHaveBeenCalledWith(context, "turn/start", {
347 threadId: "thread_1",
348 input: [
349 {
350 type: "text",
351 text: "Inspect this image",
352 text_elements: [],
353 },
354 {
355 type: "image",
356 url: "data:image/png;base64,AAAA",
357 },
358 ],
359 model: "gpt-5.3-codex",
360 serviceTier: "fast",
361 effort: "high",
362 });
363 expect(updateSession).toHaveBeenCalledWith(context, {
364 status: "running",
365 activeTurnId: "turn_1",
366 resumeCursor: { threadId: "thread_1" },
367 });
368 });
369
370 it("supports image-only turns", async () => {
371 const { manager, context, sendRequest } = createSendTurnHarness();
372
373 await manager.sendTurn({
374 threadId: asThreadId("thread_1"),
375 attachments: [
376 {
377 type: "image",
378 url: "data:image/png;base64,BBBB",
379 },
380 ],
381 });
382
383 expect(sendRequest).toHaveBeenCalledWith(context, "turn/start", {
384 threadId: "thread_1",
385 input: [
386 {
387 type: "image",
388 url: "data:image/png;base64,BBBB",
389 },
390 ],
391 model: "gpt-5.3-codex",
392 });
393 });
394
395 it("passes Codex plan mode as a collaboration preset on turn/start", async () => {
396 const { manager, context, sendRequest } = createSendTurnHarness();
397
398 await manager.sendTurn({
399 threadId: asThreadId("thread_1"),
400 input: "Plan the work",
401 interactionMode: "plan",
402 });
403
404 expect(sendRequest).toHaveBeenCalledWith(context, "turn/start", {
405 threadId: "thread_1",
406 input: [
407 {
408 type: "text",
409 text: "Plan the work",
410 text_elements: [],
411 },
412 ],
413 model: "gpt-5.3-codex",
414 collaborationMode: {
415 mode: "plan",
416 settings: {
417 model: "gpt-5.3-codex",
418 reasoning_effort: "medium",
419 developer_instructions: CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS,
420 },
421 },
422 });
423 });
424
425 it("passes Codex default mode as a collaboration preset on turn/start", async () => {
426 const { manager, context, sendRequest } = createSendTurnHarness();
427
428 await manager.sendTurn({
429 threadId: asThreadId("thread_1"),
430 input: "PLEASE IMPLEMENT THIS PLAN:\n- step 1",
431 interactionMode: "default",
432 });
433
434 expect(sendRequest).toHaveBeenCalledWith(context, "turn/start", {
435 threadId: "thread_1",
436 input: [
437 {
438 type: "text",
439 text: "PLEASE IMPLEMENT THIS PLAN:\n- step 1",
440 text_elements: [],
441 },
442 ],
443 model: "gpt-5.3-codex",
444 collaborationMode: {
445 mode: "default",
446 settings: {
447 model: "gpt-5.3-codex",
448 reasoning_effort: "medium",
449 developer_instructions: CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS,
450 },
451 },
452 });
453 });
454
455 it("keeps the session model when interaction mode is set without an explicit model", async () => {
456 const { manager, context, sendRequest } = createSendTurnHarness();
457 context.session.model = "gpt-5.2-codex";
458
459 await manager.sendTurn({
460 threadId: asThreadId("thread_1"),
461 input: "Plan this with my current session model",
462 interactionMode: "plan",
463 });
464
465 expect(sendRequest).toHaveBeenCalledWith(context, "turn/start", {
466 threadId: "thread_1",
467 input: [
468 {
469 type: "text",
470 text: "Plan this with my current session model",
471 text_elements: [],
472 },
473 ],
474 model: "gpt-5.2-codex",
475 collaborationMode: {
476 mode: "plan",
477 settings: {
478 model: "gpt-5.2-codex",
479 reasoning_effort: "medium",
480 developer_instructions: CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS,
481 },
482 },
483 });
484 });
485
486 it("rejects empty turn input", async () => {
487 const { manager } = createSendTurnHarness();
488
489 await expect(
490 manager.sendTurn({
491 threadId: asThreadId("thread_1"),
492 }),
493 ).rejects.toThrow("Turn input must include text or attachments.");
494 });
495});
496
497describe("thread checkpoint control", () => {
498 it("reads thread turns from thread/read", async () => {
499 const { manager, context, requireSession, sendRequest } = createThreadControlHarness();
500 sendRequest.mockResolvedValue({
501 thread: {
502 id: "thread_1",
503 turns: [
504 {
505 id: "turn_1",
506 items: [{ type: "userMessage", content: [{ type: "text", text: "hello" }] }],
507 },
508 ],
509 },
510 });
511
512 const result = await manager.readThread(asThreadId("thread_1"));
513
514 expect(requireSession).toHaveBeenCalledWith("thread_1");
515 expect(sendRequest).toHaveBeenCalledWith(context, "thread/read", {
516 threadId: "thread_1",
517 includeTurns: true,
518 });
519 expect(result).toEqual({
520 threadId: "thread_1",
521 turns: [
522 {
523 id: "turn_1",
524 items: [{ type: "userMessage", content: [{ type: "text", text: "hello" }] }],
525 },
526 ],
527 });
528 });
529
530 it("reads thread turns from flat thread/read responses", async () => {
531 const { manager, context, sendRequest } = createThreadControlHarness();
532 sendRequest.mockResolvedValue({
533 threadId: "thread_1",
534 turns: [
535 {
536 id: "turn_1",
537 items: [{ type: "userMessage", content: [{ type: "text", text: "hello" }] }],
538 },
539 ],
540 });
541
542 const result = await manager.readThread(asThreadId("thread_1"));
543
544 expect(sendRequest).toHaveBeenCalledWith(context, "thread/read", {
545 threadId: "thread_1",
546 includeTurns: true,
547 });
548 expect(result).toEqual({
549 threadId: "thread_1",
550 turns: [
551 {
552 id: "turn_1",
553 items: [{ type: "userMessage", content: [{ type: "text", text: "hello" }] }],
554 },
555 ],
556 });
557 });
558
559 it("rolls back turns via thread/rollback and resets session running state", async () => {
560 const { manager, context, sendRequest, updateSession } = createThreadControlHarness();
561 sendRequest.mockResolvedValue({
562 thread: {
563 id: "thread_1",
564 turns: [],
565 },
566 });
567
568 const result = await manager.rollbackThread(asThreadId("thread_1"), 2);
569
570 expect(sendRequest).toHaveBeenCalledWith(context, "thread/rollback", {
571 threadId: "thread_1",
572 numTurns: 2,
573 });
574 expect(updateSession).toHaveBeenCalledWith(context, {
575 status: "ready",
576 activeTurnId: undefined,
577 });
578 expect(result).toEqual({
579 threadId: "thread_1",
580 turns: [],
581 });
582 });
583});
584
585describe("respondToUserInput", () => {
586 it("serializes canonical answers to Codex native answer objects", async () => {
587 const { manager, context, requireSession, writeMessage, emitEvent } =
588 createPendingUserInputHarness();
589
590 await manager.respondToUserInput(
591 asThreadId("thread_1"),
592 ApprovalRequestId.makeUnsafe("req-user-input-1"),
593 {
594 scope: "All request methods",
595 compat: "Keep current envelope",
596 },
597 );
598
599 expect(requireSession).toHaveBeenCalledWith("thread_1");
600 expect(writeMessage).toHaveBeenCalledWith(context, {
601 id: 42,
602 result: {
603 answers: {
604 scope: { answers: ["All request methods"] },
605 compat: { answers: ["Keep current envelope"] },
606 },
607 },
608 });
609 expect(emitEvent).toHaveBeenCalledWith(
610 expect.objectContaining({
611 method: "item/tool/requestUserInput/answered",
612 payload: {
613 requestId: "req-user-input-1",
614 answers: {
615 scope: { answers: ["All request methods"] },
616 compat: { answers: ["Keep current envelope"] },
617 },
618 },
619 }),
620 );
621 });
622
623 it("preserves explicit empty multi-select answers", async () => {
624 const { manager, context, requireSession, writeMessage, emitEvent } =
625 createPendingUserInputHarness();
626
627 await manager.respondToUserInput(
628 asThreadId("thread_1"),
629 ApprovalRequestId.makeUnsafe("req-user-input-1"),
630 {
631 scope: [],
632 },
633 );
634
635 expect(requireSession).toHaveBeenCalledWith("thread_1");
636 expect(writeMessage).toHaveBeenCalledWith(context, {
637 id: 42,
638 result: {
639 answers: {
640 scope: { answers: [] },
641 },
642 },
643 });
644 expect(emitEvent).toHaveBeenCalledWith(
645 expect.objectContaining({
646 method: "item/tool/requestUserInput/answered",
647 payload: {
648 requestId: "req-user-input-1",
649 answers: {
650 scope: { answers: [] },
651 },
652 },
653 }),
654 );
655 });
656
657 it("tracks file-read approval requests with the correct method", () => {
658 const manager = new CodexAppServerManager();
659 const context = {
660 session: {
661 sessionId: "sess_1",
662 provider: "codex",
663 status: "ready",
664 threadId: asThreadId("thread_1"),
665 resumeCursor: { threadId: "thread_1" },
666 createdAt: "2026-02-10T00:00:00.000Z",
667 updatedAt: "2026-02-10T00:00:00.000Z",
668 },
669 pendingApprovals: new Map(),
670 pendingUserInputs: new Map(),
671 };
672 type ApprovalRequestContext = {
673 session: typeof context.session;
674 pendingApprovals: typeof context.pendingApprovals;
675 pendingUserInputs: typeof context.pendingUserInputs;
676 };
677
678 (
679 manager as unknown as {
680 handleServerRequest: (
681 context: ApprovalRequestContext,
682 request: Record<string, unknown>,
683 ) => void;
684 }
685 ).handleServerRequest(context, {
686 jsonrpc: "2.0",
687 id: 42,
688 method: "item/fileRead/requestApproval",
689 params: {},
690 });
691
692 const request = Array.from(context.pendingApprovals.values())[0];
693 expect(request?.requestKind).toBe("file-read");
694 expect(request?.method).toBe("item/fileRead/requestApproval");
695 });
696});
697
698describe.skipIf(!process.env.CODEX_BINARY_PATH)("startSession live Codex resume", () => {
699 it(
700 "keeps prior thread history when resuming with a changed runtime mode",
701 async () => {
702 const workspaceDir = mkdtempSync(path.join(os.tmpdir(), "codex-live-resume-"));
703 writeFileSync(path.join(workspaceDir, "README.md"), "hello\n", "utf8");
704
705 const manager = new CodexAppServerManager();
706
707 try {
708 const firstSession = await manager.startSession({
709 threadId: asThreadId("thread-live"),
710 provider: "codex",
711 cwd: workspaceDir,
712 runtimeMode: "full-access",
713 providerOptions: {
714 codex: {
715 ...(process.env.CODEX_BINARY_PATH
716 ? { binaryPath: process.env.CODEX_BINARY_PATH }
717 : {}),
718 ...(process.env.CODEX_HOME_PATH
719 ? { homePath: process.env.CODEX_HOME_PATH }
720 : {}),
721 },
722 },
723 });
724
725 const firstTurn = await manager.sendTurn({
726 threadId: firstSession.threadId,
727 input: `Reply with exactly the word ALPHA ${randomUUID()}`,
728 });
729
730 expect(firstTurn.threadId).toBe(firstSession.threadId);
731
732 await vi.waitFor(async () => {
733 const snapshot = await manager.readThread(firstSession.threadId);
734 expect(snapshot.turns.length).toBeGreaterThan(0);
735 }, { timeout: 120_000, interval: 1_000 });
736
737 const firstSnapshot = await manager.readThread(firstSession.threadId);
738 const originalThreadId = firstSnapshot.threadId;
739 const originalTurnCount = firstSnapshot.turns.length;
740
741 manager.stopSession(firstSession.threadId);
742
743 const resumedSession = await manager.startSession({
744 threadId: firstSession.threadId,
745 provider: "codex",
746 cwd: workspaceDir,
747 runtimeMode: "approval-required",
748 resumeCursor: firstSession.resumeCursor,
749 providerOptions: {
750 codex: {
751 ...(process.env.CODEX_BINARY_PATH
752 ? { binaryPath: process.env.CODEX_BINARY_PATH }
753 : {}),
754 ...(process.env.CODEX_HOME_PATH
755 ? { homePath: process.env.CODEX_HOME_PATH }
756 : {}),
757 },
758 },
759 });
760
761 expect(resumedSession.threadId).toBe(originalThreadId);
762
763 const resumedSnapshotBeforeTurn = await manager.readThread(resumedSession.threadId);
764 expect(resumedSnapshotBeforeTurn.threadId).toBe(originalThreadId);
765 expect(resumedSnapshotBeforeTurn.turns.length).toBeGreaterThanOrEqual(originalTurnCount);
766
767 await manager.sendTurn({
768 threadId: resumedSession.threadId,
769 input: `Reply with exactly the word BETA ${randomUUID()}`,
770 });
771
772 await vi.waitFor(async () => {
773 const snapshot = await manager.readThread(resumedSession.threadId);
774 expect(snapshot.turns.length).toBeGreaterThan(originalTurnCount);
775 }, { timeout: 120_000, interval: 1_000 });
776 } finally {
777 manager.stopAll();
778 rmSync(workspaceDir, { recursive: true, force: true });
779 }
780 },
781 180_000,
782 );
783});