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

CodexSessionRuntime.test.ts

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