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

CodexSessionRuntime.test.ts

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