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

CodexSessionRuntime.test.ts

471 lines13.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";
10​
11import {
12 buildCodexDeveloperInstructions,
13 CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS,
14 CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS,
15} from "../CodexDeveloperInstructions.ts";
16import { codexSessionAppServerArgs } from "./codexLaunchArgs.ts";
17import {
18 buildTurnStartParams,
19 hasConfiguredMcpServer,
20 isRecoverableThreadResumeError,
21 openCodexThread,
22} from "./CodexSessionRuntime.ts";
23const isCodexAppServerRequestError = Schema.is(CodexErrors.CodexAppServerRequestError);
24​
25describe("CodexSessionRuntimeIdentifierGenerationError", () => {
26 it("retains identifier purpose and the random source failure", () => {
27 const cause = new Error("random source unavailable");
28 const error = new CodexErrors.CodexAppServerIdentifierGenerationError({
29 purpose: "provider-event",
30 cause,
31 });
32​
33 NodeAssert.equal(error.purpose, "provider-event");
34 NodeAssert.strictEqual(error.cause, cause);
35 NodeAssert.equal(
36 error.message,
37 "Failed to generate Codex App Server identifier for provider-event.",
38 );
39 });
40});
41​
42function makeThreadOpenResponse(
43 threadId: string,
44): CodexRpc.ClientRequestResponsesByMethod["thread/start"] {
45 return {
46 cwd: "/tmp/project",
47 model: "gpt-5.3-codex",
48 modelProvider: "openai",
49 approvalPolicy: "never",
50 approvalsReviewer: "user",
51 sandbox: { type: "danger-full-access" },
52 thread: {
53 id: threadId,
54 createdAt: "2026-04-18T00:00:00.000Z",
55 source: { session: "cli" },
56 turns: [],
57 status: {
58 state: "idle",
59 activeFlags: [],
60 },
61 },
62 } as unknown as CodexRpc.ClientRequestResponsesByMethod["thread/start"];
64​
65describe("buildTurnStartParams", () => {
66 it("keeps invalid turn values only in the schema cause", () => {
67 const secret = "codex-turn-input-secret-sentinel";
68 const error = Effect.runSync(
69 buildTurnStartParams({
70 threadId: "provider-thread-1",
71 runtimeMode: "full-access",
72 attachments: [
73 {
74 type: "image",
75 url: { secret } as unknown as string,
76 },
77 ],
78 }).pipe(Effect.flip),
79 );
80 const { cause, ...directDiagnostics } = error;
81​
82 NodeAssert.equal(error.operation, "decode-request-payload");
83 NodeAssert.equal(error.method, "turn/start");
84 NodeAssert.ok((error.issueCount ?? 0) > 0);
85 NodeAssert.ok(error.issueKinds?.includes("Pointer"));
86 NodeAssert.ok((error.maximumPathDepth ?? 0) > 0);
87 NodeAssert.ok(Schema.isSchemaError(cause));
88 NodeAssert.doesNotMatch(error.message, new RegExp(secret));
89 NodeAssert.doesNotMatch(JSON.stringify(directDiagnostics), new RegExp(secret));
90 });
91​
92 it("includes plan collaboration mode when requested", () => {
93 const params = Effect.runSync(
94 buildTurnStartParams({
95 threadId: "provider-thread-1",
96 runtimeMode: "full-access",
97 prompt: "Make a plan",
98 model: "gpt-5.3-codex",
99 effort: "medium",
100 interactionMode: "plan",
101 }),
102 );
103​
104 NodeAssert.deepStrictEqual(params, {
105 threadId: "provider-thread-1",
106 approvalPolicy: "never",
107 approvalsReviewer: "user",
108 sandboxPolicy: {
109 type: "dangerFullAccess",
110 },
111 input: [
112 {
113 type: "text",
114 text: "Make a plan",
115 },
116 ],
117 model: "gpt-5.3-codex",
118 effort: "medium",
119 collaborationMode: {
120 mode: "plan",
121 settings: {
122 model: "gpt-5.3-codex",
123 reasoning_effort: "medium",
124 developer_instructions: buildCodexDeveloperInstructions("plan", {
125 model: "gpt-5.3-codex",
126 reasoningEffort: "medium",
127 }),
128 },
129 },
130 });
131 });
132​
133 it("includes default collaboration mode and image attachments", () => {
134 const params = Effect.runSync(
135 buildTurnStartParams({
136 threadId: "provider-thread-1",
137 runtimeMode: "auto-accept-edits",
138 prompt: "Implement it",
139 model: "gpt-5.3-codex",
140 interactionMode: "default",
141 attachments: [
142 {
143 type: "image",
144 url: "data:image/png;base64,abc",
145 },
146 ],
147 }),
148 );
149​
150 NodeAssert.deepStrictEqual(params, {
151 threadId: "provider-thread-1",
152 approvalPolicy: "on-request",
153 approvalsReviewer: "user",
154 sandboxPolicy: {
155 type: "workspaceWrite",
156 },
157 input: [
158 {
159 type: "text",
160 text: "Implement it",
161 },
162 {
163 type: "image",
164 url: "data:image/png;base64,abc",
165 },
166 ],
167 model: "gpt-5.3-codex",
168 collaborationMode: {
169 mode: "default",
170 settings: {
171 model: "gpt-5.3-codex",
172 reasoning_effort: "medium",
173 developer_instructions: buildCodexDeveloperInstructions("default", {
174 model: "gpt-5.3-codex",
175 reasoningEffort: "medium",
176 }),
177 },
178 },
179 });
180 });
181​
182 it("reports the same fallback model and effort in settings and instructions", () => {
183 const params = Effect.runSync(
184 buildTurnStartParams({
185 threadId: "provider-thread-1",
186 runtimeMode: "full-access",
187 prompt: "Go",
188 interactionMode: "default",
189 }),
190 );
191​
192 const settings = params.collaborationMode?.settings;
193 NodeAssert.equal(settings?.model, DEFAULT_MODEL);
194 NodeAssert.equal(settings?.reasoning_effort, "medium");
195 NodeAssert.ok(settings?.developer_instructions?.includes(`as ${DEFAULT_MODEL} with medium`));
196 });
197​
198 it.effect("routes approvals to the auto reviewer in auto mode", () =>
199 Effect.gen(function* () {
200 const params = yield* buildTurnStartParams({
201 threadId: "provider-thread-1",
202 runtimeMode: "auto",
203 prompt: "Ship it",
204 });
205​
206 NodeAssert.deepStrictEqual(params, {
207 threadId: "provider-thread-1",
208 approvalPolicy: "on-request",
209 approvalsReviewer: "auto_review",
210 sandboxPolicy: {
211 type: "workspaceWrite",
212 },
213 input: [
214 {
215 type: "text",
216 text: "Ship it",
217 },
218 ],
219 });
220 }),
221 );
222​
223 it("omits collaboration mode when interaction mode is absent", () => {
224 const params = Effect.runSync(
225 buildTurnStartParams({
226 threadId: "provider-thread-1",
227 runtimeMode: "approval-required",
228 prompt: "Review",
229 }),
230 );
231​
232 NodeAssert.deepStrictEqual(params, {
233 threadId: "provider-thread-1",
234 approvalPolicy: "untrusted",
235 approvalsReviewer: "user",
236 sandboxPolicy: {
237 type: "readOnly",
238 },
239 input: [
240 {
241 type: "text",
242 text: "Review",
243 },
244 ],
245 });
246 });
247});
248​
249describe("buildCodexDeveloperInstructions", () => {
250 it("appends runtime info after the mode instructions", () => {
251 const instructions = buildCodexDeveloperInstructions("default", {
252 model: "gpt-5.3-codex",
253 reasoningEffort: "high",
254 });
255​
256 NodeAssert.ok(instructions.startsWith(CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS));
257 NodeAssert.match(instructions, /T3 Code/);
258 NodeAssert.match(instructions, /Codex harness/);
259 NodeAssert.match(instructions, /as gpt-5\.3-codex with high reasoning effort/);
260 });
261​
262 it("includes runtime info alongside plan mode instructions", () => {
263 const instructions = buildCodexDeveloperInstructions("plan", {
264 model: "gpt-5.3-codex",
265 reasoningEffort: "medium",
266 });
267​
268 NodeAssert.ok(instructions.startsWith(CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS));
269 NodeAssert.match(instructions, /as gpt-5\.3-codex with medium reasoning effort/);
270 });
271​
272 it("varies with the model and effort of each turn", () => {
273 const first = buildCodexDeveloperInstructions("default", {
274 model: "gpt-5.3-codex",
275 reasoningEffort: "medium",
276 });
277 const second = buildCodexDeveloperInstructions("default", {
278 model: "gpt-5.4",
279 reasoningEffort: "high",
280 });
281​
282 NodeAssert.notEqual(first, second);
283 });
284​
285 it("flattens multiline metadata into single-line runtime info", () => {
286 const instructions = buildCodexDeveloperInstructions("default", {
287 model: "gpt\n5.3\ncodex",
288 reasoningEffort: " high\neffort ",
289 });
290​
291 NodeAssert.match(instructions, /as gpt 5\.3 codex with high effort reasoning effort/);
292 NodeAssert.doesNotMatch(instructions, /<runtime_info>[^<]*\n/);
293 });
294});
295​
296describe("T3 browser developer instructions", () => {
297 it("prefers the product-native preview tools in both collaboration modes", () => {
298 for (const instructions of [
299 CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS,
300 CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS,
301 ]) {
302 NodeAssert.match(instructions, /t3-code/);
303 NodeAssert.match(instructions, /preview_status/);
304 NodeAssert.match(instructions, /preview_open/);
305 NodeAssert.match(instructions, /Do not switch to global browser skills/);
306 }
307 });
308});
309​
310describe("hasConfiguredMcpServer", () => {
311 it("detects inline Codex MCP configuration arguments", () => {
312 NodeAssert.equal(hasConfiguredMcpServer(undefined), false);
313 NodeAssert.equal(hasConfiguredMcpServer(["--model", "gpt-5.4"]), false);
314 NodeAssert.equal(
315 hasConfiguredMcpServer(["-c", 'mcp_servers.t3-code.url="http://127.0.0.1/mcp"']),
316 true,
317 );
318 });
319});
320​
321describe("codexSessionAppServerArgs", () => {
322 it("keeps the app-server subcommand when explicit args are provided", () => {
323 NodeAssert.deepStrictEqual(codexSessionAppServerArgs(["-c", "model=gpt-5"], undefined), [
324 "app-server",
325 "-c",
326 "model=gpt-5",
327 ]);
328 });
329​
330 it("keeps launch args when explicit app-server args are provided", () => {
331 NodeAssert.deepStrictEqual(
332 codexSessionAppServerArgs(
333 ["-c", "mcp_servers.t3-code.url=http://127.0.0.1/mcp"],
334 "--strict-config --enable foo",
335 ),
336 [
337 "app-server",
338 "--strict-config",
339 "--enable",
340 "foo",
341 "-c",
342 "mcp_servers.t3-code.url=http://127.0.0.1/mcp",
343 ],
344 );
345 });
346});
347​
348describe("isRecoverableThreadResumeError", () => {
349 it("matches missing thread errors", () => {
350 NodeAssert.equal(
351 isRecoverableThreadResumeError(
352 new CodexErrors.CodexAppServerRequestError({
353 code: -32603,
354 errorMessage: "Thread does not exist",
355 }),
356 ),
357 true,
358 );
359 });
360​
361 it("ignores non-recoverable resume errors", () => {
362 NodeAssert.equal(
363 isRecoverableThreadResumeError(
364 new CodexErrors.CodexAppServerRequestError({
365 code: -32603,
366 errorMessage: "Permission denied",
367 }),
368 ),
369 false,
370 );
371 });
372​
373 it("ignores unrelated missing-resource errors that do not mention threads", () => {
374 NodeAssert.equal(
375 isRecoverableThreadResumeError(
376 new CodexErrors.CodexAppServerRequestError({
377 code: -32603,
378 errorMessage: "Config file not found",
379 }),
380 ),
381 false,
382 );
383 NodeAssert.equal(
384 isRecoverableThreadResumeError(
385 new CodexErrors.CodexAppServerRequestError({
386 code: -32603,
387 errorMessage: "Model does not exist",
388 }),
389 ),
390 false,
391 );
392 });
393});
394​
395describe("openCodexThread", () => {
396 it.effect("falls back to thread/start when resume fails recoverably", () =>
397 Effect.gen(function* () {
398 const calls: Array<{ method: "thread/start" | "thread/resume"; payload: unknown }> = [];
399 const started = makeThreadOpenResponse("fresh-thread");
400 const client = {
401 request: <M extends "thread/start" | "thread/resume">(
402 method: M,
403 payload: CodexRpc.ClientRequestParamsByMethod[M],
404 ) => {
405 calls.push({ method, payload });
406 if (method === "thread/resume") {
407 return Effect.fail(
408 new CodexErrors.CodexAppServerRequestError({
409 code: -32603,
410 errorMessage: "thread not found",
411 }),
412 );
413 }
414 return Effect.succeed(started as CodexRpc.ClientRequestResponsesByMethod[M]);
415 },
416 };
417​
418 const opened = yield* openCodexThread({
419 client,
420 threadId: ThreadId.make("thread-1"),
421 runtimeMode: "full-access",
422 cwd: "/tmp/project",
423 requestedModel: "gpt-5.3-codex",
424 serviceTier: undefined,
425 resumeThreadId: "stale-thread",
426 });
427​
428 NodeAssert.equal(opened.thread.id, "fresh-thread");
429 NodeAssert.deepStrictEqual(
430 calls.map((call) => call.method),
431 ["thread/resume", "thread/start"],
432 );
433 }),
434 );
435​
436 it.effect("propagates non-recoverable resume failures", () =>
437 Effect.gen(function* () {
438 const client = {
439 request: <M extends "thread/start" | "thread/resume">(
440 method: M,
441 _payload: CodexRpc.ClientRequestParamsByMethod[M],
442 ) => {
443 if (method === "thread/resume") {
444 return Effect.fail(
445 new CodexErrors.CodexAppServerRequestError({
446 code: -32603,
447 errorMessage: "timed out waiting for server",
448 }),
449 );
450 }
451 return Effect.succeed(
452 makeThreadOpenResponse("fresh-thread") as CodexRpc.ClientRequestResponsesByMethod[M],
453 );
454 },
455 };
456​
457 const error = yield* openCodexThread({
458 client,
459 threadId: ThreadId.make("thread-1"),
460 runtimeMode: "full-access",
461 cwd: "/tmp/project",
462 requestedModel: "gpt-5.3-codex",
463 serviceTier: undefined,
464 resumeThreadId: "stale-thread",
465 }).pipe(Effect.flip);
466​
467 NodeAssert.ok(isCodexAppServerRequestError(error));
468 NodeAssert.equal(error.errorMessage, "timed out waiting for server");
469 }),
470 );
471});