Open History to see the last commit
1import * as NodeAssert from "node:assert/strict";
2
3import { it } from "@effect/vitest";
4import * as Effect from "effect/Effect";
5import * as Schema from "effect/Schema";
6import { describe } from "vite-plus/test";
7import { DEFAULT_MODEL, ThreadId } from "@t3tools/contracts";
8import * as CodexErrors from "effect-codex-app-server/errors";
9import * as CodexRpc from "effect-codex-app-server/rpc";
10import * as EffectCodexSchema from "effect-codex-app-server/schema";
11
12import { buildCodexDeveloperInstructions } from "../CodexDeveloperInstructions.ts";
13import { codexSessionAppServerArgs } from "./codexLaunchArgs.ts";
14import {
15 buildTurnStartParams,
16 describeMcpElicitation,
17 hasConfiguredMcpServer,
18 isRecoverableThreadResumeError,
19 makeMemoryConsolidationNotificationFilter,
20 openCodexThread,
21 toMcpElicitationResponse,
22} from "./CodexSessionRuntime.ts";
23const isCodexAppServerRequestError = Schema.is(CodexErrors.CodexAppServerRequestError);
24
25describe("CodexSessionRuntimeIdentifierGenerationError", () => {
26 it("retains identifier purpose and the random source failure", () => {
27 const cause = new Error("random source unavailable");
28 const error = new CodexErrors.CodexAppServerIdentifierGenerationError({
29 purpose: "provider-event",
30 cause,
31 });
32
33 NodeAssert.equal(error.purpose, "provider-event");
34 NodeAssert.strictEqual(error.cause, cause);
35 NodeAssert.equal(
36 error.message,
37 "Failed to generate Codex App Server identifier for provider-event.",
38 );
39 });
40});
41
42function makeThreadOpenResponse(
43 threadId: string,
44): CodexRpc.ClientRequestResponsesByMethod["thread/start"] {
45 return {
46 cwd: "/tmp/project",
47 model: "gpt-5.3-codex",
48 modelProvider: "openai",
49 approvalPolicy: "never",
50 approvalsReviewer: "user",
51 sandbox: { type: "danger-full-access" },
52 thread: {
53 id: threadId,
54 createdAt: "2026-04-18T00:00:00.000Z",
55 source: { session: "cli" },
56 turns: [],
57 status: {
58 state: "idle",
59 activeFlags: [],
60 },
61 },
62 } as unknown as CodexRpc.ClientRequestResponsesByMethod["thread/start"];
63}
64
65describe("buildTurnStartParams", () => {
66 it("keeps invalid turn values only in the schema cause", () => {
67 const secret = "codex-turn-input-secret-sentinel";
68 const error = Effect.runSync(
69 buildTurnStartParams({
70 threadId: "provider-thread-1",
71 runtimeMode: "full-access",
72 attachments: [
73 {
74 type: "image",
75 url: { secret } as unknown as string,
76 },
77 ],
78 }).pipe(Effect.flip),
79 );
80 const { cause, ...directDiagnostics } = error;
81
82 NodeAssert.equal(error.operation, "decode-request-payload");
83 NodeAssert.equal(error.method, "turn/start");
84 NodeAssert.ok((error.issueCount ?? 0) > 0);
85 NodeAssert.ok(error.issueKinds?.includes("Pointer"));
86 NodeAssert.ok((error.maximumPathDepth ?? 0) > 0);
87 NodeAssert.ok(Schema.isSchemaError(cause));
88 NodeAssert.doesNotMatch(error.message, new RegExp(secret));
89 NodeAssert.doesNotMatch(JSON.stringify(directDiagnostics), new RegExp(secret));
90 });
91
92 it("includes plan collaboration mode when requested", () => {
93 const params = Effect.runSync(
94 buildTurnStartParams({
95 threadId: "provider-thread-1",
96 runtimeMode: "full-access",
97 prompt: "Make a plan",
98 model: "gpt-5.3-codex",
99 effort: "medium",
100 interactionMode: "plan",
101 }),
102 );
103
104 NodeAssert.deepStrictEqual(params, {
105 threadId: "provider-thread-1",
106 approvalPolicy: "never",
107 approvalsReviewer: "user",
108 sandboxPolicy: {
109 type: "dangerFullAccess",
110 },
111 input: [
112 {
113 type: "text",
114 text: "Make a plan",
115 },
116 ],
117 model: "gpt-5.3-codex",
118 effort: "medium",
119 collaborationMode: {
120 mode: "plan",
121 settings: {
122 model: "gpt-5.3-codex",
123 reasoning_effort: "medium",
124 developer_instructions: buildCodexDeveloperInstructions("plan", {
125 model: "gpt-5.3-codex",
126 reasoningEffort: "medium",
127 }),
128 },
129 },
130 });
131 });
132
133 it("includes default collaboration mode and image attachments", () => {
134 const params = Effect.runSync(
135 buildTurnStartParams({
136 threadId: "provider-thread-1",
137 runtimeMode: "auto-accept-edits",
138 prompt: "Implement it",
139 model: "gpt-5.3-codex",
140 interactionMode: "default",
141 attachments: [
142 {
143 type: "image",
144 url: "data:image/png;base64,abc",
145 },
146 ],
147 }),
148 );
149
150 NodeAssert.deepStrictEqual(params, {
151 threadId: "provider-thread-1",
152 approvalPolicy: "on-request",
153 approvalsReviewer: "user",
154 sandboxPolicy: {
155 type: "workspaceWrite",
156 },
157 input: [
158 {
159 type: "text",
160 text: "Implement it",
161 },
162 {
163 type: "image",
164 url: "data:image/png;base64,abc",
165 },
166 ],
167 model: "gpt-5.3-codex",
168 collaborationMode: {
169 mode: "default",
170 settings: {
171 model: "gpt-5.3-codex",
172 reasoning_effort: "medium",
173 developer_instructions: buildCodexDeveloperInstructions("default", {
174 model: "gpt-5.3-codex",
175 reasoningEffort: "medium",
176 }),
177 },
178 },
179 });
180 });
181
182 it("reports the same fallback model and effort in settings and instructions", () => {
183 const params = Effect.runSync(
184 buildTurnStartParams({
185 threadId: "provider-thread-1",
186 runtimeMode: "full-access",
187 prompt: "Go",
188 interactionMode: "default",
189 }),
190 );
191
192 const settings = params.collaborationMode?.settings;
193 NodeAssert.equal(settings?.model, DEFAULT_MODEL);
194 NodeAssert.equal(settings?.reasoning_effort, "medium");
195 NodeAssert.ok(settings?.developer_instructions?.includes(`as ${DEFAULT_MODEL} with medium`));
196 });
197
198 it.effect("routes approvals to the auto reviewer in auto mode", () =>
199 Effect.gen(function* () {
200 const params = yield* buildTurnStartParams({
201 threadId: "provider-thread-1",
202 runtimeMode: "auto",
203 prompt: "Ship it",
204 });
205
206 NodeAssert.deepStrictEqual(params, {
207 threadId: "provider-thread-1",
208 approvalPolicy: "on-request",
209 approvalsReviewer: "auto_review",
210 sandboxPolicy: {
211 type: "workspaceWrite",
212 },
213 input: [
214 {
215 type: "text",
216 text: "Ship it",
217 },
218 ],
219 });
220 }),
221 );
222
223 it("omits collaboration mode when interaction mode is absent", () => {
224 const params = Effect.runSync(
225 buildTurnStartParams({
226 threadId: "provider-thread-1",
227 runtimeMode: "approval-required",
228 prompt: "Review",
229 }),
230 );
231
232 NodeAssert.deepStrictEqual(params, {
233 threadId: "provider-thread-1",
234 approvalPolicy: "untrusted",
235 approvalsReviewer: "user",
236 sandboxPolicy: {
237 type: "readOnly",
238 },
239 input: [
240 {
241 type: "text",
242 text: "Review",
243 },
244 ],
245 });
246 });
247});
248
249describe("Codex MCP elicitation approvals", () => {
250 const request = {
251 mode: "form",
252 message: "Allow ChatGPT to use Safari?",
253 serverName: "computer-use",
254 threadId: "provider-thread-1",
255 turnId: "turn-1",
256 _meta: {
257 app_name: "Safari",
258 persist: ["session", "always"],
259 },
260 requestedSchema: {
261 type: "object",
262 properties: {
263 approval: {
264 type: "string",
265 oneOf: [
266 { const: "once", title: "Allow once" },
267 { const: "session", title: "Allow for this session" },
268 { const: "always", title: "Always allow Safari" },
269 ],
270 },
271 },
272 required: ["approval"],
273 },
274 } satisfies EffectCodexSchema.McpServerElicitationRequestParams;
275
276 it("preserves the app name and advertised persistence choices", () => {
277 NodeAssert.deepStrictEqual(describeMcpElicitation(request), {
278 appName: "Safari",
279 options: [
280 { decision: "cancel", label: "Cancel" },
281 { decision: "decline", label: "Decline" },
282 { decision: "acceptForSession", label: "Allow for this session" },
283 { decision: "acceptAlways", label: "Always allow Safari" },
284 { decision: "accept", label: "Approve" },
285 ],
286 });
287 });
288
289 it("extracts the app name from a Computer Use request without metadata", () => {
290 const { _meta, ...requestWithoutMetadata } = request;
291
292 NodeAssert.equal(describeMcpElicitation(requestWithoutMetadata).appName, "Safari");
293 });
294
295 it("returns the accepted form option to Codex", () => {
296 NodeAssert.deepStrictEqual(toMcpElicitationResponse(request, "accept"), {
297 action: "accept",
298 content: { approval: "once" },
299 });
300 });
301
302 it("returns session-scoped approval in the MCP response", () => {
303 NodeAssert.deepStrictEqual(toMcpElicitationResponse(request, "acceptForSession"), {
304 action: "accept",
305 _meta: { persist: "session" },
306 content: { approval: "session" },
307 });
308 });
309
310 it("returns persistent approval in the MCP response", () => {
311 NodeAssert.deepStrictEqual(toMcpElicitationResponse(request, "acceptAlways"), {
312 action: "accept",
313 _meta: { persist: "always" },
314 content: { approval: "always" },
315 });
316 });
317
318 it("returns rejection without form content", () => {
319 NodeAssert.deepStrictEqual(toMcpElicitationResponse(request, "decline"), {
320 action: "decline",
321 });
322 });
323
324 it("returns cancellation without form content", () => {
325 NodeAssert.deepStrictEqual(toMcpElicitationResponse(request, "cancel"), {
326 action: "cancel",
327 });
328 });
329
330 it("supports boolean permanent-approval fields", () => {
331 const booleanRequest = {
332 ...request,
333 _meta: { app_name: "Safari" },
334 requestedSchema: {
335 type: "object",
336 properties: {
337 always: { type: "boolean", title: "Always allow Safari" },
338 },
339 },
340 } satisfies EffectCodexSchema.McpServerElicitationRequestParams;
341
342 NodeAssert.ok(
343 describeMcpElicitation(booleanRequest).options.some(
344 (option) => option.decision === "acceptAlways",
345 ),
346 );
347 NodeAssert.deepStrictEqual(toMcpElicitationResponse(booleanRequest, "acceptAlways"), {
348 action: "accept",
349 _meta: { persist: "always" },
350 content: { always: true },
351 });
352 });
353
354 it("preserves valid nullable MCP form fields and persistence choices", () => {
355 const nullableRequest = {
356 ...request,
357 _meta: {
358 app_name: null,
359 appName: "Safari",
360 connector_name: null,
361 persist: null,
362 target: null,
363 tool_params: null,
364 },
365 requestedSchema: {
366 type: "object",
367 properties: {
368 approval: {
369 type: "string",
370 title: null,
371 description: null,
372 default: null,
373 enum: ["once", "always"],
374 enumNames: null,
375 },
376 },
377 required: ["approval"],
378 },
379 } satisfies EffectCodexSchema.McpServerElicitationRequestParams;
380
381 NodeAssert.equal(describeMcpElicitation(nullableRequest).appName, "Safari");
382 NodeAssert.ok(
383 describeMcpElicitation(nullableRequest).options.some(
384 (option) => option.decision === "acceptAlways",
385 ),
386 );
387 NodeAssert.deepStrictEqual(toMcpElicitationResponse(nullableRequest, "acceptAlways"), {
388 action: "accept",
389 _meta: { persist: "always" },
390 content: { approval: "always" },
391 });
392 });
393
394 it("declines required form fields that an approval prompt cannot collect", () => {
395 const inputRequest = {
396 ...request,
397 requestedSchema: {
398 type: "object",
399 properties: {
400 email: { type: "string", format: "email" },
401 },
402 required: ["email"],
403 },
404 } satisfies EffectCodexSchema.McpServerElicitationRequestParams;
405
406 NodeAssert.deepStrictEqual(toMcpElicitationResponse(inputRequest, "accept"), {
407 action: "decline",
408 });
409 });
410
411 it("does not approve URL elicitations without opening their requested URL", () => {
412 const urlRequest = {
413 mode: "url",
414 message: "Finish signing in to continue.",
415 serverName: "computer-use",
416 threadId: "provider-thread-1",
417 turnId: "turn-1",
418 elicitationId: "sign-in-1",
419 url: "https://example.com/authorize",
420 } satisfies EffectCodexSchema.McpServerElicitationRequestParams;
421
422 NodeAssert.deepStrictEqual(toMcpElicitationResponse(urlRequest, "accept"), {
423 action: "decline",
424 });
425 });
426
427 it("omits persistence choices that cannot satisfy required form fields", () => {
428 const onceOnlyRequest = {
429 ...request,
430 _meta: { app_name: "Safari", persist: ["session", "always"] },
431 requestedSchema: {
432 type: "object",
433 properties: {
434 approval: {
435 type: "string",
436 enum: ["once"],
437 },
438 },
439 required: ["approval"],
440 },
441 } satisfies EffectCodexSchema.McpServerElicitationRequestParams;
442
443 NodeAssert.deepStrictEqual(describeMcpElicitation(onceOnlyRequest).options, [
444 { decision: "cancel", label: "Cancel" },
445 { decision: "decline", label: "Decline" },
446 { decision: "accept", label: "Approve" },
447 ]);
448 });
449});
450
451describe("buildCodexDeveloperInstructions", () => {
452 it("appends runtime info after the mode instructions", () => {
453 const instructions = buildCodexDeveloperInstructions("default", {
454 model: "gpt-5.3-codex",
455 reasoningEffort: "high",
456 });
457
458 NodeAssert.match(instructions, /^<collaboration_mode># Collaboration Mode: Default/);
459 NodeAssert.match(instructions, /T3 Code/);
460 NodeAssert.match(instructions, /Codex harness/);
461 NodeAssert.match(instructions, /as gpt-5\.3-codex with high reasoning effort/);
462 });
463
464 it("describes Markdown media support in the runtime context in both modes", () => {
465 for (const mode of ["default", "plan"] as const) {
466 const instructions = buildCodexDeveloperInstructions(mode, {
467 model: "gpt-5.3-codex",
468 reasoningEffort: "high",
469 });
470 NodeAssert.match(
471 instructions,
472 /<runtime_info>.*embed images and videos.*Markdown.*<\/runtime_info>/,
473 );
474 }
475 });
476
477 it("includes runtime info alongside plan mode instructions", () => {
478 const instructions = buildCodexDeveloperInstructions("plan", {
479 model: "gpt-5.3-codex",
480 reasoningEffort: "medium",
481 });
482
483 NodeAssert.match(instructions, /^<collaboration_mode># Plan Mode/);
484 NodeAssert.match(instructions, /as gpt-5\.3-codex with medium reasoning effort/);
485 });
486
487 it("varies with the model and effort of each turn", () => {
488 const first = buildCodexDeveloperInstructions("default", {
489 model: "gpt-5.3-codex",
490 reasoningEffort: "medium",
491 });
492 const second = buildCodexDeveloperInstructions("default", {
493 model: "gpt-5.4",
494 reasoningEffort: "high",
495 });
496
497 NodeAssert.notEqual(first, second);
498 });
499
500 it("flattens multiline metadata into single-line runtime info", () => {
501 const instructions = buildCodexDeveloperInstructions("default", {
502 model: "gpt\n5.3\ncodex",
503 reasoningEffort: " high\neffort ",
504 });
505
506 NodeAssert.match(instructions, /as gpt 5\.3 codex with high effort reasoning effort/);
507 NodeAssert.doesNotMatch(instructions, /<runtime_info>[^<]*\n/);
508 });
509});
510
511describe("T3 browser developer instructions", () => {
512 const runtime = { model: "gpt-5.3-codex", reasoningEffort: "high" };
513
514 it("prefers the product-native preview tools in both collaboration modes", () => {
515 for (const mode of ["default", "plan"] as const) {
516 const instructions = buildCodexDeveloperInstructions(mode, runtime, true);
517 NodeAssert.match(instructions, /t3-code/);
518 NodeAssert.match(instructions, /preview_status/);
519 NodeAssert.match(instructions, /preview_open/);
520 NodeAssert.match(instructions, /Do not switch to global browser skills/);
521 }
522 });
523
524 it("omits the browser block entirely when the preview tools are not attached", () => {
525 for (const mode of ["default", "plan"] as const) {
526 const instructions = buildCodexDeveloperInstructions(mode, runtime, false);
527 NodeAssert.doesNotMatch(instructions, /preview_status/);
528 NodeAssert.doesNotMatch(instructions, /preview_open/);
529 NodeAssert.doesNotMatch(instructions, /T3 Code collaborative browser/);
530 // Steering away from other browser automation must go with the tools;
531 // keeping it would leave the model talked out of its only option.
532 NodeAssert.doesNotMatch(instructions, /Do not switch to global browser skills/);
533 // The rest of the collaboration mode is untouched.
534 NodeAssert.match(instructions, /<collaboration_mode>/);
535 NodeAssert.match(instructions, /<\/collaboration_mode>/);
536 }
537 });
538
539 it("tracks the turn's MCP configuration rather than defaulting to on", () => {
540 NodeAssert.match(buildCodexDeveloperInstructions("default", runtime, true), /preview_open/);
541 NodeAssert.doesNotMatch(
542 buildCodexDeveloperInstructions("default", runtime, false),
543 /preview_open/,
544 );
545 });
546});
547
548describe("hasConfiguredMcpServer", () => {
549 it("detects inline Codex MCP configuration arguments", () => {
550 NodeAssert.equal(hasConfiguredMcpServer(undefined), false);
551 NodeAssert.equal(hasConfiguredMcpServer(["--model", "gpt-5.4"]), false);
552 NodeAssert.equal(
553 hasConfiguredMcpServer(["-c", 'mcp_servers.t3-code.url="http://127.0.0.1/mcp"']),
554 true,
555 );
556 });
557});
558
559function makeThreadStartedNotification(
560 threadId: string,
561 source: EffectCodexSchema.V2ThreadStartedNotification["thread"]["source"],
562 threadSource?: string,
563) {
564 return {
565 method: "thread/started" as const,
566 params: {
567 thread: {
568 cliVersion: "0.0.0",
569 createdAt: 0,
570 cwd: "/tmp/project",
571 ephemeral: true,
572 id: threadId,
573 modelProvider: "openai",
574 preview: "",
575 sessionId: threadId,
576 source,
577 status: { type: "idle" as const },
578 ...(threadSource ? { threadSource } : {}),
579 turns: [],
580 updatedAt: 0,
581 },
582 },
583 };
584}
585
586describe("makeMemoryConsolidationNotificationFilter", () => {
587 it("suppresses memory consolidation without hiding other Codex subagents", () => {
588 const shouldSuppress = makeMemoryConsolidationNotificationFilter();
589
590 NodeAssert.equal(
591 shouldSuppress(
592 makeThreadStartedNotification("memory-thread", "unknown", "memory_consolidation"),
593 ),
594 true,
595 );
596 NodeAssert.equal(
597 shouldSuppress({
598 method: "item/agentMessage/delta",
599 params: {
600 delta: "internal memory update",
601 itemId: "memory-message",
602 threadId: "memory-thread",
603 turnId: "memory-turn",
604 },
605 }),
606 true,
607 );
608 NodeAssert.equal(
609 shouldSuppress({
610 method: "serverRequest/resolved",
611 params: {
612 requestId: "memory-approval",
613 threadId: "memory-thread",
614 },
615 }),
616 false,
617 );
618 NodeAssert.equal(
619 shouldSuppress({
620 method: "warning",
621 params: {
622 message: "internal warning",
623 threadId: "memory-thread",
624 },
625 }),
626 true,
627 );
628 NodeAssert.equal(
629 shouldSuppress({
630 method: "item/agentMessage/delta",
631 params: {
632 delta: "normal reply",
633 itemId: "root-message",
634 threadId: "root-thread",
635 turnId: "root-turn",
636 },
637 }),
638 false,
639 );
640
641 NodeAssert.equal(
642 shouldSuppress(
643 makeThreadStartedNotification("legacy-memory-thread", {
644 subAgent: "memory_consolidation",
645 }),
646 ),
647 true,
648 );
649
650 for (const source of [
651 { subAgent: "review" as const },
652 { subAgent: "compact" as const },
653 {
654 subAgent: {
655 thread_spawn: {
656 depth: 1,
657 parent_thread_id: "root-thread",
658 },
659 },
660 },
661 ]) {
662 NodeAssert.equal(
663 shouldSuppress(makeThreadStartedNotification("visible-subagent", source)),
664 false,
665 );
666 }
667 });
668
669 it("forgets memory consolidation threads after they close", () => {
670 const shouldSuppress = makeMemoryConsolidationNotificationFilter();
671 shouldSuppress(
672 makeThreadStartedNotification("memory-thread", "unknown", "memory_consolidation"),
673 );
674
675 NodeAssert.equal(
676 shouldSuppress({
677 method: "thread/closed",
678 params: { threadId: "memory-thread" },
679 }),
680 true,
681 );
682 NodeAssert.equal(
683 shouldSuppress({
684 method: "item/agentMessage/delta",
685 params: {
686 delta: "later message",
687 itemId: "later-message",
688 threadId: "memory-thread",
689 turnId: "later-turn",
690 },
691 }),
692 false,
693 );
694 });
695});
696
697describe("codexSessionAppServerArgs", () => {
698 it("keeps the app-server subcommand when explicit args are provided", () => {
699 NodeAssert.deepStrictEqual(codexSessionAppServerArgs(["-c", "model=gpt-5"], undefined), [
700 "app-server",
701 "-c",
702 "model=gpt-5",
703 ]);
704 });
705
706 it("keeps launch args when explicit app-server args are provided", () => {
707 NodeAssert.deepStrictEqual(
708 codexSessionAppServerArgs(
709 ["-c", "mcp_servers.t3-code.url=http://127.0.0.1/mcp"],
710 "--strict-config --enable foo",
711 ),
712 [
713 "app-server",
714 "--strict-config",
715 "--enable",
716 "foo",
717 "-c",
718 "mcp_servers.t3-code.url=http://127.0.0.1/mcp",
719 ],
720 );
721 });
722});
723
724describe("isRecoverableThreadResumeError", () => {
725 it("matches missing thread errors", () => {
726 NodeAssert.equal(
727 isRecoverableThreadResumeError(
728 new CodexErrors.CodexAppServerRequestError({
729 code: -32603,
730 errorMessage: "Thread does not exist",
731 }),
732 ),
733 true,
734 );
735 });
736
737 it("matches a missing rollout for a known thread id", () => {
738 NodeAssert.equal(
739 isRecoverableThreadResumeError(
740 new CodexErrors.CodexAppServerRequestError({
741 code: -32603,
742 errorMessage: "no rollout found for thread id 019fdf74-aaa9-7950-b252-7cc7a8650470",
743 }),
744 ),
745 true,
746 );
747 });
748
749 it("ignores non-recoverable resume errors", () => {
750 NodeAssert.equal(
751 isRecoverableThreadResumeError(
752 new CodexErrors.CodexAppServerRequestError({
753 code: -32603,
754 errorMessage: "Permission denied",
755 }),
756 ),
757 false,
758 );
759 });
760
761 it("ignores unrelated missing-resource errors that do not mention threads", () => {
762 NodeAssert.equal(
763 isRecoverableThreadResumeError(
764 new CodexErrors.CodexAppServerRequestError({
765 code: -32603,
766 errorMessage: "Config file not found",
767 }),
768 ),
769 false,
770 );
771 NodeAssert.equal(
772 isRecoverableThreadResumeError(
773 new CodexErrors.CodexAppServerRequestError({
774 code: -32603,
775 errorMessage: "Model does not exist",
776 }),
777 ),
778 false,
779 );
780 });
781});
782
783describe("openCodexThread", () => {
784 it.effect("unarchives an archived session and resumes the same thread", () =>
785 Effect.gen(function* () {
786 const calls: Array<{ method: string; payload: unknown }> = [];
787 const opened = yield* openCodexThread({
788 client: {
789 request: () => Effect.die("An archived session must not start fresh"),
790 raw: {
791 request: (method, payload) =>
792 Effect.suspend(() => {
793 calls.push({ method, payload });
794 if (calls.length === 1) {
795 return Effect.fail(
796 new CodexErrors.CodexAppServerRequestError({
797 code: -32600,
798 errorMessage:
799 "session saved-thread is archived. Run `codex unarchive saved-thread` to unarchive it first.",
800 }),
801 );
802 }
803 return Effect.succeed(makeThreadOpenResponse("saved-thread"));
804 }),
805 },
806 },
807 threadId: ThreadId.make("thread-1"),
808 runtimeMode: "auto",
809 cwd: "/tmp/project",
810 requestedModel: "gpt-5.3-codex",
811 serviceTier: "fast",
812 resumeThreadId: "saved-thread",
813 });
814
815 NodeAssert.equal(opened.thread.id, "saved-thread");
816 NodeAssert.deepStrictEqual(
817 calls.map((call) => call.method),
818 ["thread/resume", "thread/unarchive", "thread/resume"],
819 );
820 NodeAssert.deepStrictEqual(calls[1]?.payload, { threadId: "saved-thread" });
821 NodeAssert.deepStrictEqual(calls[2]?.payload, calls[0]?.payload);
822 }),
823 );
824
825 it.effect(
826 "propagates unarchive and retry failures without starting fresh or retrying again",
827 () =>
828 Effect.gen(function* () {
829 for (const failAt of [2, 3]) {
830 for (const errorMessage of ["thread not found", "session saved-thread is archived"]) {
831 const failure = new CodexErrors.CodexAppServerRequestError({
832 code: -32600,
833 errorMessage,
834 });
835 const calls: string[] = [];
836 const error = yield* openCodexThread({
837 client: {
838 request: () => Effect.die("An archived session must not start fresh"),
839 raw: {
840 request: (method) =>
841 Effect.suspend(() => {
842 calls.push(method);
843 if (calls.length === failAt) return Effect.fail(failure);
844 if (calls.length === 1) {
845 return Effect.fail(
846 new CodexErrors.CodexAppServerRequestError({
847 code: -32600,
848 errorMessage:
849 "Run `codex unarchive saved-thread` to unarchive it first.",
850 }),
851 );
852 }
853 return Effect.succeed({});
854 }),
855 },
856 },
857 threadId: ThreadId.make("thread-1"),
858 runtimeMode: "full-access",
859 cwd: "/tmp/project",
860 requestedModel: undefined,
861 serviceTier: undefined,
862 resumeThreadId: "saved-thread",
863 }).pipe(Effect.flip);
864
865 NodeAssert.strictEqual(error, failure);
866 NodeAssert.deepStrictEqual(
867 calls,
868 ["thread/resume", "thread/unarchive", "thread/resume"].slice(0, failAt),
869 );
870 }
871 }
872 }),
873 );
874
875 it.effect("resumes metadata when historical turns contain unknown error values", () =>
876 Effect.gen(function* () {
877 const response = makeThreadOpenResponse("saved-thread");
878 const calls: unknown[] = [];
879 const opened = yield* openCodexThread({
880 client: {
881 request: () => Effect.die("A valid resumed thread must not start fresh"),
882 raw: {
883 request: (method, payload) => {
884 calls.push({ method, payload });
885 return Effect.succeed({
886 ...response,
887 thread: {
888 ...response.thread,
889 turns: [
890 {
891 id: "old-turn",
892 status: "failed",
893 items: [],
894 error: {
895 message: "Historical provider error",
896 codexErrorInfo: "misalignment_policy_violation",
897 },
898 },
899 ],
900 },
901 });
902 },
903 },
904 },
905 threadId: ThreadId.make("thread-1"),
906 runtimeMode: "auto",
907 cwd: "/tmp/project",
908 requestedModel: "gpt-5.3-codex",
909 serviceTier: "fast",
910 resumeThreadId: "saved-thread",
911 });
912
913 NodeAssert.deepStrictEqual(opened, {
914 cwd: response.cwd,
915 model: response.model,
916 thread: { id: "saved-thread" },
917 });
918 NodeAssert.deepStrictEqual(calls, [
919 {
920 method: "thread/resume",
921 payload: {
922 threadId: "saved-thread",
923 cwd: "/tmp/project",
924 model: "gpt-5.3-codex",
925 serviceTier: "fast",
926 approvalPolicy: "on-request",
927 sandbox: "workspace-write",
928 approvalsReviewer: "auto_review",
929 excludeTurns: true,
930 },
931 },
932 ]);
933 }),
934 );
935
936 it.effect("rejects malformed required resume metadata without starting a fresh thread", () =>
937 Effect.gen(function* () {
938 for (const invalidMetadata of [
939 { cwd: null },
940 { model: 42 },
941 { thread: { id: null } },
942 { thread: {} },
943 ]) {
944 const error = yield* openCodexThread({
945 client: {
946 request: () => Effect.die("Invalid resume metadata must not start a fresh thread"),
947 raw: {
948 request: () =>
949 Effect.succeed({ ...makeThreadOpenResponse("saved-thread"), ...invalidMetadata }),
950 },
951 },
952 threadId: ThreadId.make("thread-1"),
953 runtimeMode: "full-access",
954 cwd: "/tmp/project",
955 requestedModel: "gpt-5.3-codex",
956 serviceTier: undefined,
957 resumeThreadId: "saved-thread",
958 }).pipe(Effect.flip);
959
960 NodeAssert.ok(isCodexAppServerRequestError(error));
961 NodeAssert.equal(error.operation, "decode-payload");
962 NodeAssert.equal(error.method, "thread/resume");
963 }
964 }),
965 );
966
967 it.effect("falls back to thread/start when resume fails recoverably", () =>
968 Effect.gen(function* () {
969 const calls: Array<{ method: string; payload: unknown }> = [];
970 const started = makeThreadOpenResponse("fresh-thread");
971 const client = {
972 raw: {
973 request: (
974 method: "thread/resume" | "thread/unarchive",
975 payload: CodexRpc.ClientRequestParamsByMethod["thread/resume" | "thread/unarchive"],
976 ) => {
977 calls.push({ method, payload });
978 return Effect.fail(
979 new CodexErrors.CodexAppServerRequestError({
980 code: -32603,
981 errorMessage: "thread not found",
982 }),
983 );
984 },
985 },
986 request: (
987 method: "thread/start",
988 payload: CodexRpc.ClientRequestParamsByMethod["thread/start"],
989 ) => {
990 calls.push({ method, payload });
991 return Effect.succeed(started);
992 },
993 };
994
995 const opened = yield* openCodexThread({
996 client,
997 threadId: ThreadId.make("thread-1"),
998 runtimeMode: "full-access",
999 cwd: "/tmp/project",
1000 requestedModel: "gpt-5.3-codex",
1001 serviceTier: undefined,
1002 resumeThreadId: "stale-thread",
1003 });
1004
1005 NodeAssert.equal(opened.thread.id, "fresh-thread");
1006 NodeAssert.deepStrictEqual(
1007 calls.map((call) => call.method),
1008 ["thread/resume", "thread/start"],
1009 );
1010 }),
1011 );
1012
1013 it.effect("propagates non-recoverable resume failures", () =>
1014 Effect.gen(function* () {
1015 const client = {
1016 request: () => Effect.die("Non-recoverable resume failures must not start a fresh thread"),
1017 raw: {
1018 request: () =>
1019 Effect.fail(
1020 new CodexErrors.CodexAppServerRequestError({
1021 code: -32603,
1022 errorMessage: "timed out waiting for server",
1023 }),
1024 ),
1025 },
1026 };
1027
1028 const error = yield* openCodexThread({
1029 client,
1030 threadId: ThreadId.make("thread-1"),
1031 runtimeMode: "full-access",
1032 cwd: "/tmp/project",
1033 requestedModel: "gpt-5.3-codex",
1034 serviceTier: undefined,
1035 resumeThreadId: "stale-thread",
1036 }).pipe(Effect.flip);
1037
1038 NodeAssert.ok(isCodexAppServerRequestError(error));
1039 NodeAssert.equal(error.errorMessage, "timed out waiting for server");
1040 }),
1041 );
1042});