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

CodexSessionRuntime.test.ts

1,042 lines31.7 KB

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