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

CodexSessionRuntime.test.ts

649 lines18.8 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 codexDefaultModeDeveloperInstructions,
15 codexPlanModeDeveloperInstructions,
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(codexDefaultModeDeveloperInstructions(true)));
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(codexPlanModeDeveloperInstructions(true)));
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 codexDefaultModeDeveloperInstructions(true),
302 codexPlanModeDeveloperInstructions(true),
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 it("omits the browser block entirely when the preview tools are not attached", () => {
312 for (const instructions of [
313 codexDefaultModeDeveloperInstructions(false),
314 codexPlanModeDeveloperInstructions(false),
315 ]) {
316 NodeAssert.doesNotMatch(instructions, /preview_status/);
317 NodeAssert.doesNotMatch(instructions, /preview_open/);
318 NodeAssert.doesNotMatch(instructions, /T3 Code collaborative browser/);
319 // Steering away from other browser automation must go with the tools;
320 // keeping it would leave the model talked out of its only option.
321 NodeAssert.doesNotMatch(instructions, /Do not switch to global browser skills/);
322 // The rest of the collaboration mode is untouched.
323 NodeAssert.match(instructions, /<collaboration_mode>/);
324 NodeAssert.match(instructions, /<\/collaboration_mode>/);
325 }
326 });
327​
328 it("tracks the turn's MCP configuration rather than defaulting to on", () => {
329 const runtime = { model: "gpt-5.3-codex", reasoningEffort: "high" };
330 NodeAssert.match(buildCodexDeveloperInstructions("default", runtime, true), /preview_open/);
331 NodeAssert.doesNotMatch(
332 buildCodexDeveloperInstructions("default", runtime, false),
333 /preview_open/,
334 );
335 });
336});
337​
338describe("hasConfiguredMcpServer", () => {
339 it("detects inline Codex MCP configuration arguments", () => {
340 NodeAssert.equal(hasConfiguredMcpServer(undefined), false);
341 NodeAssert.equal(hasConfiguredMcpServer(["--model", "gpt-5.4"]), false);
342 NodeAssert.equal(
343 hasConfiguredMcpServer(["-c", 'mcp_servers.t3-code.url="http://127.0.0.1/mcp"']),
344 true,
345 );
346 });
347});
348​
349function makeThreadStartedNotification(
350 threadId: string,
351 source: EffectCodexSchema.V2ThreadStartedNotification["thread"]["source"],
352 threadSource?: string,
353) {
354 return {
355 method: "thread/started" as const,
356 params: {
357 thread: {
358 cliVersion: "0.0.0",
359 createdAt: 0,
360 cwd: "/tmp/project",
361 ephemeral: true,
362 id: threadId,
363 modelProvider: "openai",
364 preview: "",
365 sessionId: threadId,
366 source,
367 status: { type: "idle" as const },
368 ...(threadSource ? { threadSource } : {}),
369 turns: [],
370 updatedAt: 0,
371 },
372 },
373 };
375​
376describe("makeMemoryConsolidationNotificationFilter", () => {
377 it("suppresses memory consolidation without hiding other Codex subagents", () => {
378 const shouldSuppress = makeMemoryConsolidationNotificationFilter();
379​
380 NodeAssert.equal(
381 shouldSuppress(
382 makeThreadStartedNotification("memory-thread", "unknown", "memory_consolidation"),
383 ),
384 true,
385 );
386 NodeAssert.equal(
387 shouldSuppress({
388 method: "item/agentMessage/delta",
389 params: {
390 delta: "internal memory update",
391 itemId: "memory-message",
392 threadId: "memory-thread",
393 turnId: "memory-turn",
394 },
395 }),
396 true,
397 );
398 NodeAssert.equal(
399 shouldSuppress({
400 method: "serverRequest/resolved",
401 params: {
402 requestId: "memory-approval",
403 threadId: "memory-thread",
404 },
405 }),
406 false,
407 );
408 NodeAssert.equal(
409 shouldSuppress({
410 method: "warning",
411 params: {
412 message: "internal warning",
413 threadId: "memory-thread",
414 },
415 }),
416 true,
417 );
418 NodeAssert.equal(
419 shouldSuppress({
420 method: "item/agentMessage/delta",
421 params: {
422 delta: "normal reply",
423 itemId: "root-message",
424 threadId: "root-thread",
425 turnId: "root-turn",
426 },
427 }),
428 false,
429 );
430​
431 NodeAssert.equal(
432 shouldSuppress(
433 makeThreadStartedNotification("legacy-memory-thread", {
434 subAgent: "memory_consolidation",
435 }),
436 ),
437 true,
438 );
439​
440 for (const source of [
441 { subAgent: "review" as const },
442 { subAgent: "compact" as const },
443 {
444 subAgent: {
445 thread_spawn: {
446 depth: 1,
447 parent_thread_id: "root-thread",
448 },
449 },
450 },
451 ]) {
452 NodeAssert.equal(
453 shouldSuppress(makeThreadStartedNotification("visible-subagent", source)),
454 false,
455 );
456 }
457 });
458​
459 it("forgets memory consolidation threads after they close", () => {
460 const shouldSuppress = makeMemoryConsolidationNotificationFilter();
461 shouldSuppress(
462 makeThreadStartedNotification("memory-thread", "unknown", "memory_consolidation"),
463 );
464​
465 NodeAssert.equal(
466 shouldSuppress({
467 method: "thread/closed",
468 params: { threadId: "memory-thread" },
469 }),
470 true,
471 );
472 NodeAssert.equal(
473 shouldSuppress({
474 method: "item/agentMessage/delta",
475 params: {
476 delta: "later message",
477 itemId: "later-message",
478 threadId: "memory-thread",
479 turnId: "later-turn",
480 },
481 }),
482 false,
483 );
484 });
485});
486​
487describe("codexSessionAppServerArgs", () => {
488 it("keeps the app-server subcommand when explicit args are provided", () => {
489 NodeAssert.deepStrictEqual(codexSessionAppServerArgs(["-c", "model=gpt-5"], undefined), [
490 "app-server",
491 "-c",
492 "model=gpt-5",
493 ]);
494 });
495​
496 it("keeps launch args when explicit app-server args are provided", () => {
497 NodeAssert.deepStrictEqual(
498 codexSessionAppServerArgs(
499 ["-c", "mcp_servers.t3-code.url=http://127.0.0.1/mcp"],
500 "--strict-config --enable foo",
501 ),
502 [
503 "app-server",
504 "--strict-config",
505 "--enable",
506 "foo",
507 "-c",
508 "mcp_servers.t3-code.url=http://127.0.0.1/mcp",
509 ],
510 );
511 });
512});
513​
514describe("isRecoverableThreadResumeError", () => {
515 it("matches missing thread errors", () => {
516 NodeAssert.equal(
517 isRecoverableThreadResumeError(
518 new CodexErrors.CodexAppServerRequestError({
519 code: -32603,
520 errorMessage: "Thread does not exist",
521 }),
522 ),
523 true,
524 );
525 });
526​
527 it("matches a missing rollout for a known thread id", () => {
528 NodeAssert.equal(
529 isRecoverableThreadResumeError(
530 new CodexErrors.CodexAppServerRequestError({
531 code: -32603,
532 errorMessage: "no rollout found for thread id 019fdf74-aaa9-7950-b252-7cc7a8650470",
533 }),
534 ),
535 true,
536 );
537 });
538​
539 it("ignores non-recoverable resume errors", () => {
540 NodeAssert.equal(
541 isRecoverableThreadResumeError(
542 new CodexErrors.CodexAppServerRequestError({
543 code: -32603,
544 errorMessage: "Permission denied",
545 }),
546 ),
547 false,
548 );
549 });
550​
551 it("ignores unrelated missing-resource errors that do not mention threads", () => {
552 NodeAssert.equal(
553 isRecoverableThreadResumeError(
554 new CodexErrors.CodexAppServerRequestError({
555 code: -32603,
556 errorMessage: "Config file not found",
557 }),
558 ),
559 false,
560 );
561 NodeAssert.equal(
562 isRecoverableThreadResumeError(
563 new CodexErrors.CodexAppServerRequestError({
564 code: -32603,
565 errorMessage: "Model does not exist",
566 }),
567 ),
568 false,
569 );
570 });
571});
572​
573describe("openCodexThread", () => {
574 it.effect("falls back to thread/start when resume fails recoverably", () =>
575 Effect.gen(function* () {
576 const calls: Array<{ method: "thread/start" | "thread/resume"; payload: unknown }> = [];
577 const started = makeThreadOpenResponse("fresh-thread");
578 const client = {
579 request: <M extends "thread/start" | "thread/resume">(
580 method: M,
581 payload: CodexRpc.ClientRequestParamsByMethod[M],
582 ) => {
583 calls.push({ method, payload });
584 if (method === "thread/resume") {
585 return Effect.fail(
586 new CodexErrors.CodexAppServerRequestError({
587 code: -32603,
588 errorMessage: "thread not found",
589 }),
590 );
591 }
592 return Effect.succeed(started as CodexRpc.ClientRequestResponsesByMethod[M]);
593 },
594 };
595​
596 const opened = yield* openCodexThread({
597 client,
598 threadId: ThreadId.make("thread-1"),
599 runtimeMode: "full-access",
600 cwd: "/tmp/project",
601 requestedModel: "gpt-5.3-codex",
602 serviceTier: undefined,
603 resumeThreadId: "stale-thread",
604 });
605​
606 NodeAssert.equal(opened.thread.id, "fresh-thread");
607 NodeAssert.deepStrictEqual(
608 calls.map((call) => call.method),
609 ["thread/resume", "thread/start"],
610 );
611 }),
612 );
613​
614 it.effect("propagates non-recoverable resume failures", () =>
615 Effect.gen(function* () {
616 const client = {
617 request: <M extends "thread/start" | "thread/resume">(
618 method: M,
619 _payload: CodexRpc.ClientRequestParamsByMethod[M],
620 ) => {
621 if (method === "thread/resume") {
622 return Effect.fail(
623 new CodexErrors.CodexAppServerRequestError({
624 code: -32603,
625 errorMessage: "timed out waiting for server",
626 }),
627 );
628 }
629 return Effect.succeed(
630 makeThreadOpenResponse("fresh-thread") as CodexRpc.ClientRequestResponsesByMethod[M],
631 );
632 },
633 };
634​
635 const error = yield* openCodexThread({
636 client,
637 threadId: ThreadId.make("thread-1"),
638 runtimeMode: "full-access",
639 cwd: "/tmp/project",
640 requestedModel: "gpt-5.3-codex",
641 serviceTier: undefined,
642 resumeThreadId: "stale-thread",
643 }).pipe(Effect.flip);
644​
645 NodeAssert.ok(isCodexAppServerRequestError(error));
646 NodeAssert.equal(error.errorMessage, "timed out waiting for server");
647 }),
648 );
649});