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

CodexSessionRuntime.test.ts

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