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