Open History to see the last commit
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"];
63}
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 sandboxPolicy: {
108 type: "dangerFullAccess",
109 },
110 input: [
111 {
112 type: "text",
113 text: "Make a plan",
114 },
115 ],
116 model: "gpt-5.3-codex",
117 effort: "medium",
118 collaborationMode: {
119 mode: "plan",
120 settings: {
121 model: "gpt-5.3-codex",
122 reasoning_effort: "medium",
123 developer_instructions: buildCodexDeveloperInstructions("plan", {
124 model: "gpt-5.3-codex",
125 reasoningEffort: "medium",
126 }),
127 },
128 },
129 });
130 });
131
132 it("includes default collaboration mode and image attachments", () => {
133 const params = Effect.runSync(
134 buildTurnStartParams({
135 threadId: "provider-thread-1",
136 runtimeMode: "auto-accept-edits",
137 prompt: "Implement it",
138 model: "gpt-5.3-codex",
139 interactionMode: "default",
140 attachments: [
141 {
142 type: "image",
143 url: "data:image/png;base64,abc",
144 },
145 ],
146 }),
147 );
148
149 NodeAssert.deepStrictEqual(params, {
150 threadId: "provider-thread-1",
151 approvalPolicy: "on-request",
152 sandboxPolicy: {
153 type: "workspaceWrite",
154 },
155 input: [
156 {
157 type: "text",
158 text: "Implement it",
159 },
160 {
161 type: "image",
162 url: "data:image/png;base64,abc",
163 },
164 ],
165 model: "gpt-5.3-codex",
166 collaborationMode: {
167 mode: "default",
168 settings: {
169 model: "gpt-5.3-codex",
170 reasoning_effort: "medium",
171 developer_instructions: buildCodexDeveloperInstructions("default", {
172 model: "gpt-5.3-codex",
173 reasoningEffort: "medium",
174 }),
175 },
176 },
177 });
178 });
179
180 it("reports the same fallback model and effort in settings and instructions", () => {
181 const params = Effect.runSync(
182 buildTurnStartParams({
183 threadId: "provider-thread-1",
184 runtimeMode: "full-access",
185 prompt: "Go",
186 interactionMode: "default",
187 }),
188 );
189
190 const settings = params.collaborationMode?.settings;
191 NodeAssert.equal(settings?.model, DEFAULT_MODEL);
192 NodeAssert.equal(settings?.reasoning_effort, "medium");
193 NodeAssert.ok(settings?.developer_instructions?.includes(`as ${DEFAULT_MODEL} with medium`));
194 });
195
196 it("omits collaboration mode when interaction mode is absent", () => {
197 const params = Effect.runSync(
198 buildTurnStartParams({
199 threadId: "provider-thread-1",
200 runtimeMode: "approval-required",
201 prompt: "Review",
202 }),
203 );
204
205 NodeAssert.deepStrictEqual(params, {
206 threadId: "provider-thread-1",
207 approvalPolicy: "untrusted",
208 sandboxPolicy: {
209 type: "readOnly",
210 },
211 input: [
212 {
213 type: "text",
214 text: "Review",
215 },
216 ],
217 });
218 });
219});
220
221describe("buildCodexDeveloperInstructions", () => {
222 it("appends runtime info after the mode instructions", () => {
223 const instructions = buildCodexDeveloperInstructions("default", {
224 model: "gpt-5.3-codex",
225 reasoningEffort: "high",
226 });
227
228 NodeAssert.ok(instructions.startsWith(CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS));
229 NodeAssert.match(instructions, /T3 Code/);
230 NodeAssert.match(instructions, /Codex harness/);
231 NodeAssert.match(instructions, /as gpt-5\.3-codex with high reasoning effort/);
232 });
233
234 it("includes runtime info alongside plan mode instructions", () => {
235 const instructions = buildCodexDeveloperInstructions("plan", {
236 model: "gpt-5.3-codex",
237 reasoningEffort: "medium",
238 });
239
240 NodeAssert.ok(instructions.startsWith(CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS));
241 NodeAssert.match(instructions, /as gpt-5\.3-codex with medium reasoning effort/);
242 });
243
244 it("varies with the model and effort of each turn", () => {
245 const first = buildCodexDeveloperInstructions("default", {
246 model: "gpt-5.3-codex",
247 reasoningEffort: "medium",
248 });
249 const second = buildCodexDeveloperInstructions("default", {
250 model: "gpt-5.4",
251 reasoningEffort: "high",
252 });
253
254 NodeAssert.notEqual(first, second);
255 });
256
257 it("flattens multiline metadata into single-line runtime info", () => {
258 const instructions = buildCodexDeveloperInstructions("default", {
259 model: "gpt\n5.3\ncodex",
260 reasoningEffort: " high\neffort ",
261 });
262
263 NodeAssert.match(instructions, /as gpt 5\.3 codex with high effort reasoning effort/);
264 NodeAssert.doesNotMatch(instructions, /<runtime_info>[^<]*\n/);
265 });
266});
267
268describe("T3 browser developer instructions", () => {
269 it("prefers the product-native preview tools in both collaboration modes", () => {
270 for (const instructions of [
271 CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS,
272 CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS,
273 ]) {
274 NodeAssert.match(instructions, /t3-code/);
275 NodeAssert.match(instructions, /preview_status/);
276 NodeAssert.match(instructions, /preview_open/);
277 NodeAssert.match(instructions, /Do not switch to global browser skills/);
278 }
279 });
280});
281
282describe("hasConfiguredMcpServer", () => {
283 it("detects inline Codex MCP configuration arguments", () => {
284 NodeAssert.equal(hasConfiguredMcpServer(undefined), false);
285 NodeAssert.equal(hasConfiguredMcpServer(["--model", "gpt-5.4"]), false);
286 NodeAssert.equal(
287 hasConfiguredMcpServer(["-c", 'mcp_servers.t3-code.url="http://127.0.0.1/mcp"']),
288 true,
289 );
290 });
291});
292
293describe("codexSessionAppServerArgs", () => {
294 it("keeps the app-server subcommand when explicit args are provided", () => {
295 NodeAssert.deepStrictEqual(codexSessionAppServerArgs(["-c", "model=gpt-5"], undefined), [
296 "app-server",
297 "-c",
298 "model=gpt-5",
299 ]);
300 });
301
302 it("keeps launch args when explicit app-server args are provided", () => {
303 NodeAssert.deepStrictEqual(
304 codexSessionAppServerArgs(
305 ["-c", "mcp_servers.t3-code.url=http://127.0.0.1/mcp"],
306 "--strict-config --enable foo",
307 ),
308 [
309 "app-server",
310 "--strict-config",
311 "--enable",
312 "foo",
313 "-c",
314 "mcp_servers.t3-code.url=http://127.0.0.1/mcp",
315 ],
316 );
317 });
318});
319
320describe("isRecoverableThreadResumeError", () => {
321 it("matches missing thread errors", () => {
322 NodeAssert.equal(
323 isRecoverableThreadResumeError(
324 new CodexErrors.CodexAppServerRequestError({
325 code: -32603,
326 errorMessage: "Thread does not exist",
327 }),
328 ),
329 true,
330 );
331 });
332
333 it("ignores non-recoverable resume errors", () => {
334 NodeAssert.equal(
335 isRecoverableThreadResumeError(
336 new CodexErrors.CodexAppServerRequestError({
337 code: -32603,
338 errorMessage: "Permission denied",
339 }),
340 ),
341 false,
342 );
343 });
344
345 it("ignores unrelated missing-resource errors that do not mention threads", () => {
346 NodeAssert.equal(
347 isRecoverableThreadResumeError(
348 new CodexErrors.CodexAppServerRequestError({
349 code: -32603,
350 errorMessage: "Config file not found",
351 }),
352 ),
353 false,
354 );
355 NodeAssert.equal(
356 isRecoverableThreadResumeError(
357 new CodexErrors.CodexAppServerRequestError({
358 code: -32603,
359 errorMessage: "Model does not exist",
360 }),
361 ),
362 false,
363 );
364 });
365});
366
367describe("openCodexThread", () => {
368 it.effect("falls back to thread/start when resume fails recoverably", () =>
369 Effect.gen(function* () {
370 const calls: Array<{ method: "thread/start" | "thread/resume"; payload: unknown }> = [];
371 const started = makeThreadOpenResponse("fresh-thread");
372 const client = {
373 request: <M extends "thread/start" | "thread/resume">(
374 method: M,
375 payload: CodexRpc.ClientRequestParamsByMethod[M],
376 ) => {
377 calls.push({ method, payload });
378 if (method === "thread/resume") {
379 return Effect.fail(
380 new CodexErrors.CodexAppServerRequestError({
381 code: -32603,
382 errorMessage: "thread not found",
383 }),
384 );
385 }
386 return Effect.succeed(started as CodexRpc.ClientRequestResponsesByMethod[M]);
387 },
388 };
389
390 const opened = yield* openCodexThread({
391 client,
392 threadId: ThreadId.make("thread-1"),
393 runtimeMode: "full-access",
394 cwd: "/tmp/project",
395 requestedModel: "gpt-5.3-codex",
396 serviceTier: undefined,
397 resumeThreadId: "stale-thread",
398 });
399
400 NodeAssert.equal(opened.thread.id, "fresh-thread");
401 NodeAssert.deepStrictEqual(
402 calls.map((call) => call.method),
403 ["thread/resume", "thread/start"],
404 );
405 }),
406 );
407
408 it.effect("propagates non-recoverable resume failures", () =>
409 Effect.gen(function* () {
410 const client = {
411 request: <M extends "thread/start" | "thread/resume">(
412 method: M,
413 _payload: CodexRpc.ClientRequestParamsByMethod[M],
414 ) => {
415 if (method === "thread/resume") {
416 return Effect.fail(
417 new CodexErrors.CodexAppServerRequestError({
418 code: -32603,
419 errorMessage: "timed out waiting for server",
420 }),
421 );
422 }
423 return Effect.succeed(
424 makeThreadOpenResponse("fresh-thread") as CodexRpc.ClientRequestResponsesByMethod[M],
425 );
426 },
427 };
428
429 const error = yield* openCodexThread({
430 client,
431 threadId: ThreadId.make("thread-1"),
432 runtimeMode: "full-access",
433 cwd: "/tmp/project",
434 requestedModel: "gpt-5.3-codex",
435 serviceTier: undefined,
436 resumeThreadId: "stale-thread",
437 }).pipe(Effect.flip);
438
439 NodeAssert.ok(isCodexAppServerRequestError(error));
440 NodeAssert.equal(error.errorMessage, "timed out waiting for server");
441 }),
442 );
443});