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

CodexSessionRuntime.test.ts

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