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

CodexSessionRuntime.test.ts

623 lines17.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 {
13 buildCodexDeveloperInstructions,
14 CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS,
15 CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS,
16} from "../CodexDeveloperInstructions.ts";
17import { codexSessionAppServerArgs } from "./codexLaunchArgs.ts";
18import {
19 buildTurnStartParams,
20 hasConfiguredMcpServer,
21 isRecoverableThreadResumeError,
22 makeMemoryConsolidationNotificationFilter,
23 openCodexThread,
24} from "./CodexSessionRuntime.ts";
25const isCodexAppServerRequestError = Schema.is(CodexErrors.CodexAppServerRequestError);
26​
27describe("CodexSessionRuntimeIdentifierGenerationError", () => {
28 it("retains identifier purpose and the random source failure", () => {
29 const cause = new Error("random source unavailable");
30 const error = new CodexErrors.CodexAppServerIdentifierGenerationError({
31 purpose: "provider-event",
32 cause,
33 });
34​
35 NodeAssert.equal(error.purpose, "provider-event");
36 NodeAssert.strictEqual(error.cause, cause);
37 NodeAssert.equal(
38 error.message,
39 "Failed to generate Codex App Server identifier for provider-event.",
40 );
41 });
42});
43​
44function makeThreadOpenResponse(
45 threadId: string,
46): CodexRpc.ClientRequestResponsesByMethod["thread/start"] {
47 return {
48 cwd: "/tmp/project",
49 model: "gpt-5.3-codex",
50 modelProvider: "openai",
51 approvalPolicy: "never",
52 approvalsReviewer: "user",
53 sandbox: { type: "danger-full-access" },
54 thread: {
55 id: threadId,
56 createdAt: "2026-04-18T00:00:00.000Z",
57 source: { session: "cli" },
58 turns: [],
59 status: {
60 state: "idle",
61 activeFlags: [],
62 },
63 },
64 } as unknown as CodexRpc.ClientRequestResponsesByMethod["thread/start"];
66​
67describe("buildTurnStartParams", () => {
68 it("keeps invalid turn values only in the schema cause", () => {
69 const secret = "codex-turn-input-secret-sentinel";
70 const error = Effect.runSync(
71 buildTurnStartParams({
72 threadId: "provider-thread-1",
73 runtimeMode: "full-access",
74 attachments: [
75 {
76 type: "image",
77 url: { secret } as unknown as string,
78 },
79 ],
80 }).pipe(Effect.flip),
81 );
82 const { cause, ...directDiagnostics } = error;
83​
84 NodeAssert.equal(error.operation, "decode-request-payload");
85 NodeAssert.equal(error.method, "turn/start");
86 NodeAssert.ok((error.issueCount ?? 0) > 0);
87 NodeAssert.ok(error.issueKinds?.includes("Pointer"));
88 NodeAssert.ok((error.maximumPathDepth ?? 0) > 0);
89 NodeAssert.ok(Schema.isSchemaError(cause));
90 NodeAssert.doesNotMatch(error.message, new RegExp(secret));
91 NodeAssert.doesNotMatch(JSON.stringify(directDiagnostics), new RegExp(secret));
92 });
93​
94 it("includes plan collaboration mode when requested", () => {
95 const params = Effect.runSync(
96 buildTurnStartParams({
97 threadId: "provider-thread-1",
98 runtimeMode: "full-access",
99 prompt: "Make a plan",
100 model: "gpt-5.3-codex",
101 effort: "medium",
102 interactionMode: "plan",
103 }),
104 );
105​
106 NodeAssert.deepStrictEqual(params, {
107 threadId: "provider-thread-1",
108 approvalPolicy: "never",
109 approvalsReviewer: "user",
110 sandboxPolicy: {
111 type: "dangerFullAccess",
112 },
113 input: [
114 {
115 type: "text",
116 text: "Make a plan",
117 },
118 ],
119 model: "gpt-5.3-codex",
120 effort: "medium",
121 collaborationMode: {
122 mode: "plan",
123 settings: {
124 model: "gpt-5.3-codex",
125 reasoning_effort: "medium",
126 developer_instructions: buildCodexDeveloperInstructions("plan", {
127 model: "gpt-5.3-codex",
128 reasoningEffort: "medium",
129 }),
130 },
131 },
132 });
133 });
134​
135 it("includes default collaboration mode and image attachments", () => {
136 const params = Effect.runSync(
137 buildTurnStartParams({
138 threadId: "provider-thread-1",
139 runtimeMode: "auto-accept-edits",
140 prompt: "Implement it",
141 model: "gpt-5.3-codex",
142 interactionMode: "default",
143 attachments: [
144 {
145 type: "image",
146 url: "data:image/png;base64,abc",
147 },
148 ],
149 }),
150 );
151​
152 NodeAssert.deepStrictEqual(params, {
153 threadId: "provider-thread-1",
154 approvalPolicy: "on-request",
155 approvalsReviewer: "user",
156 sandboxPolicy: {
157 type: "workspaceWrite",
158 },
159 input: [
160 {
161 type: "text",
162 text: "Implement it",
163 },
164 {
165 type: "image",
166 url: "data:image/png;base64,abc",
167 },
168 ],
169 model: "gpt-5.3-codex",
170 collaborationMode: {
171 mode: "default",
172 settings: {
173 model: "gpt-5.3-codex",
174 reasoning_effort: "medium",
175 developer_instructions: buildCodexDeveloperInstructions("default", {
176 model: "gpt-5.3-codex",
177 reasoningEffort: "medium",
178 }),
179 },
180 },
181 });
182 });
183​
184 it("reports the same fallback model and effort in settings and instructions", () => {
185 const params = Effect.runSync(
186 buildTurnStartParams({
187 threadId: "provider-thread-1",
188 runtimeMode: "full-access",
189 prompt: "Go",
190 interactionMode: "default",
191 }),
192 );
193​
194 const settings = params.collaborationMode?.settings;
195 NodeAssert.equal(settings?.model, DEFAULT_MODEL);
196 NodeAssert.equal(settings?.reasoning_effort, "medium");
197 NodeAssert.ok(settings?.developer_instructions?.includes(`as ${DEFAULT_MODEL} with medium`));
198 });
199​
200 it.effect("routes approvals to the auto reviewer in auto mode", () =>
201 Effect.gen(function* () {
202 const params = yield* buildTurnStartParams({
203 threadId: "provider-thread-1",
204 runtimeMode: "auto",
205 prompt: "Ship it",
206 });
207​
208 NodeAssert.deepStrictEqual(params, {
209 threadId: "provider-thread-1",
210 approvalPolicy: "on-request",
211 approvalsReviewer: "auto_review",
212 sandboxPolicy: {
213 type: "workspaceWrite",
214 },
215 input: [
216 {
217 type: "text",
218 text: "Ship it",
219 },
220 ],
221 });
222 }),
223 );
224​
225 it("omits collaboration mode when interaction mode is absent", () => {
226 const params = Effect.runSync(
227 buildTurnStartParams({
228 threadId: "provider-thread-1",
229 runtimeMode: "approval-required",
230 prompt: "Review",
231 }),
232 );
233​
234 NodeAssert.deepStrictEqual(params, {
235 threadId: "provider-thread-1",
236 approvalPolicy: "untrusted",
237 approvalsReviewer: "user",
238 sandboxPolicy: {
239 type: "readOnly",
240 },
241 input: [
242 {
243 type: "text",
244 text: "Review",
245 },
246 ],
247 });
248 });
249});
250​
251describe("buildCodexDeveloperInstructions", () => {
252 it("appends runtime info after the mode instructions", () => {
253 const instructions = buildCodexDeveloperInstructions("default", {
254 model: "gpt-5.3-codex",
255 reasoningEffort: "high",
256 });
257​
258 NodeAssert.ok(instructions.startsWith(CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS));
259 NodeAssert.match(instructions, /T3 Code/);
260 NodeAssert.match(instructions, /Codex harness/);
261 NodeAssert.match(instructions, /as gpt-5\.3-codex with high reasoning effort/);
262 });
263​
264 it("includes runtime info alongside plan mode instructions", () => {
265 const instructions = buildCodexDeveloperInstructions("plan", {
266 model: "gpt-5.3-codex",
267 reasoningEffort: "medium",
268 });
269​
270 NodeAssert.ok(instructions.startsWith(CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS));
271 NodeAssert.match(instructions, /as gpt-5\.3-codex with medium reasoning effort/);
272 });
273​
274 it("varies with the model and effort of each turn", () => {
275 const first = buildCodexDeveloperInstructions("default", {
276 model: "gpt-5.3-codex",
277 reasoningEffort: "medium",
278 });
279 const second = buildCodexDeveloperInstructions("default", {
280 model: "gpt-5.4",
281 reasoningEffort: "high",
282 });
283​
284 NodeAssert.notEqual(first, second);
285 });
286​
287 it("flattens multiline metadata into single-line runtime info", () => {
288 const instructions = buildCodexDeveloperInstructions("default", {
289 model: "gpt\n5.3\ncodex",
290 reasoningEffort: " high\neffort ",
291 });
292​
293 NodeAssert.match(instructions, /as gpt 5\.3 codex with high effort reasoning effort/);
294 NodeAssert.doesNotMatch(instructions, /<runtime_info>[^<]*\n/);
295 });
296});
297​
298describe("T3 browser developer instructions", () => {
299 it("prefers the product-native preview tools in both collaboration modes", () => {
300 for (const instructions of [
301 CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS,
302 CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS,
303 ]) {
304 NodeAssert.match(instructions, /t3-code/);
305 NodeAssert.match(instructions, /preview_status/);
306 NodeAssert.match(instructions, /preview_open/);
307 NodeAssert.match(instructions, /Do not switch to global browser skills/);
308 }
309 });
310});
311​
312describe("hasConfiguredMcpServer", () => {
313 it("detects inline Codex MCP configuration arguments", () => {
314 NodeAssert.equal(hasConfiguredMcpServer(undefined), false);
315 NodeAssert.equal(hasConfiguredMcpServer(["--model", "gpt-5.4"]), false);
316 NodeAssert.equal(
317 hasConfiguredMcpServer(["-c", 'mcp_servers.t3-code.url="http://127.0.0.1/mcp"']),
318 true,
319 );
320 });
321});
322​
323function makeThreadStartedNotification(
324 threadId: string,
325 source: EffectCodexSchema.V2ThreadStartedNotification["thread"]["source"],
326 threadSource?: string,
327) {
328 return {
329 method: "thread/started" as const,
330 params: {
331 thread: {
332 cliVersion: "0.0.0",
333 createdAt: 0,
334 cwd: "/tmp/project",
335 ephemeral: true,
336 id: threadId,
337 modelProvider: "openai",
338 preview: "",
339 sessionId: threadId,
340 source,
341 status: { type: "idle" as const },
342 ...(threadSource ? { threadSource } : {}),
343 turns: [],
344 updatedAt: 0,
345 },
346 },
347 };
349​
350describe("makeMemoryConsolidationNotificationFilter", () => {
351 it("suppresses memory consolidation without hiding other Codex subagents", () => {
352 const shouldSuppress = makeMemoryConsolidationNotificationFilter();
353​
354 NodeAssert.equal(
355 shouldSuppress(
356 makeThreadStartedNotification("memory-thread", "unknown", "memory_consolidation"),
357 ),
358 true,
359 );
360 NodeAssert.equal(
361 shouldSuppress({
362 method: "item/agentMessage/delta",
363 params: {
364 delta: "internal memory update",
365 itemId: "memory-message",
366 threadId: "memory-thread",
367 turnId: "memory-turn",
368 },
369 }),
370 true,
371 );
372 NodeAssert.equal(
373 shouldSuppress({
374 method: "serverRequest/resolved",
375 params: {
376 requestId: "memory-approval",
377 threadId: "memory-thread",
378 },
379 }),
380 false,
381 );
382 NodeAssert.equal(
383 shouldSuppress({
384 method: "warning",
385 params: {
386 message: "internal warning",
387 threadId: "memory-thread",
388 },
389 }),
390 true,
391 );
392 NodeAssert.equal(
393 shouldSuppress({
394 method: "item/agentMessage/delta",
395 params: {
396 delta: "normal reply",
397 itemId: "root-message",
398 threadId: "root-thread",
399 turnId: "root-turn",
400 },
401 }),
402 false,
403 );
404​
405 NodeAssert.equal(
406 shouldSuppress(
407 makeThreadStartedNotification("legacy-memory-thread", {
408 subAgent: "memory_consolidation",
409 }),
410 ),
411 true,
412 );
413​
414 for (const source of [
415 { subAgent: "review" as const },
416 { subAgent: "compact" as const },
417 {
418 subAgent: {
419 thread_spawn: {
420 depth: 1,
421 parent_thread_id: "root-thread",
422 },
423 },
424 },
425 ]) {
426 NodeAssert.equal(
427 shouldSuppress(makeThreadStartedNotification("visible-subagent", source)),
428 false,
429 );
430 }
431 });
432​
433 it("forgets memory consolidation threads after they close", () => {
434 const shouldSuppress = makeMemoryConsolidationNotificationFilter();
435 shouldSuppress(
436 makeThreadStartedNotification("memory-thread", "unknown", "memory_consolidation"),
437 );
438​
439 NodeAssert.equal(
440 shouldSuppress({
441 method: "thread/closed",
442 params: { threadId: "memory-thread" },
443 }),
444 true,
445 );
446 NodeAssert.equal(
447 shouldSuppress({
448 method: "item/agentMessage/delta",
449 params: {
450 delta: "later message",
451 itemId: "later-message",
452 threadId: "memory-thread",
453 turnId: "later-turn",
454 },
455 }),
456 false,
457 );
458 });
459});
460​
461describe("codexSessionAppServerArgs", () => {
462 it("keeps the app-server subcommand when explicit args are provided", () => {
463 NodeAssert.deepStrictEqual(codexSessionAppServerArgs(["-c", "model=gpt-5"], undefined), [
464 "app-server",
465 "-c",
466 "model=gpt-5",
467 ]);
468 });
469​
470 it("keeps launch args when explicit app-server args are provided", () => {
471 NodeAssert.deepStrictEqual(
472 codexSessionAppServerArgs(
473 ["-c", "mcp_servers.t3-code.url=http://127.0.0.1/mcp"],
474 "--strict-config --enable foo",
475 ),
476 [
477 "app-server",
478 "--strict-config",
479 "--enable",
480 "foo",
481 "-c",
482 "mcp_servers.t3-code.url=http://127.0.0.1/mcp",
483 ],
484 );
485 });
486});
487​
488describe("isRecoverableThreadResumeError", () => {
489 it("matches missing thread errors", () => {
490 NodeAssert.equal(
491 isRecoverableThreadResumeError(
492 new CodexErrors.CodexAppServerRequestError({
493 code: -32603,
494 errorMessage: "Thread does not exist",
495 }),
496 ),
497 true,
498 );
499 });
500​
501 it("matches a missing rollout for a known thread id", () => {
502 NodeAssert.equal(
503 isRecoverableThreadResumeError(
504 new CodexErrors.CodexAppServerRequestError({
505 code: -32603,
506 errorMessage: "no rollout found for thread id 019fdf74-aaa9-7950-b252-7cc7a8650470",
507 }),
508 ),
509 true,
510 );
511 });
512​
513 it("ignores non-recoverable resume errors", () => {
514 NodeAssert.equal(
515 isRecoverableThreadResumeError(
516 new CodexErrors.CodexAppServerRequestError({
517 code: -32603,
518 errorMessage: "Permission denied",
519 }),
520 ),
521 false,
522 );
523 });
524​
525 it("ignores unrelated missing-resource errors that do not mention threads", () => {
526 NodeAssert.equal(
527 isRecoverableThreadResumeError(
528 new CodexErrors.CodexAppServerRequestError({
529 code: -32603,
530 errorMessage: "Config file not found",
531 }),
532 ),
533 false,
534 );
535 NodeAssert.equal(
536 isRecoverableThreadResumeError(
537 new CodexErrors.CodexAppServerRequestError({
538 code: -32603,
539 errorMessage: "Model does not exist",
540 }),
541 ),
542 false,
543 );
544 });
545});
546​
547describe("openCodexThread", () => {
548 it.effect("falls back to thread/start when resume fails recoverably", () =>
549 Effect.gen(function* () {
550 const calls: Array<{ method: "thread/start" | "thread/resume"; payload: unknown }> = [];
551 const started = makeThreadOpenResponse("fresh-thread");
552 const client = {
553 request: <M extends "thread/start" | "thread/resume">(
554 method: M,
555 payload: CodexRpc.ClientRequestParamsByMethod[M],
556 ) => {
557 calls.push({ method, payload });
558 if (method === "thread/resume") {
559 return Effect.fail(
560 new CodexErrors.CodexAppServerRequestError({
561 code: -32603,
562 errorMessage: "thread not found",
563 }),
564 );
565 }
566 return Effect.succeed(started as CodexRpc.ClientRequestResponsesByMethod[M]);
567 },
568 };
569​
570 const opened = yield* openCodexThread({
571 client,
572 threadId: ThreadId.make("thread-1"),
573 runtimeMode: "full-access",
574 cwd: "/tmp/project",
575 requestedModel: "gpt-5.3-codex",
576 serviceTier: undefined,
577 resumeThreadId: "stale-thread",
578 });
579​
580 NodeAssert.equal(opened.thread.id, "fresh-thread");
581 NodeAssert.deepStrictEqual(
582 calls.map((call) => call.method),
583 ["thread/resume", "thread/start"],
584 );
585 }),
586 );
587​
588 it.effect("propagates non-recoverable resume failures", () =>
589 Effect.gen(function* () {
590 const client = {
591 request: <M extends "thread/start" | "thread/resume">(
592 method: M,
593 _payload: CodexRpc.ClientRequestParamsByMethod[M],
594 ) => {
595 if (method === "thread/resume") {
596 return Effect.fail(
597 new CodexErrors.CodexAppServerRequestError({
598 code: -32603,
599 errorMessage: "timed out waiting for server",
600 }),
601 );
602 }
603 return Effect.succeed(
604 makeThreadOpenResponse("fresh-thread") as CodexRpc.ClientRequestResponsesByMethod[M],
605 );
606 },
607 };
608​
609 const error = yield* openCodexThread({
610 client,
611 threadId: ThreadId.make("thread-1"),
612 runtimeMode: "full-access",
613 cwd: "/tmp/project",
614 requestedModel: "gpt-5.3-codex",
615 serviceTier: undefined,
616 resumeThreadId: "stale-thread",
617 }).pipe(Effect.flip);
618​
619 NodeAssert.ok(isCodexAppServerRequestError(error));
620 NodeAssert.equal(error.errorMessage, "timed out waiting for server");
621 }),
622 );
623});