Open History to see the last commit
1import * as CodexInstallation from "../CodexInstallation.ts";
2import * as CodexManagedTokenBroker from "../CodexManagedTokenBroker.ts";
3import * as ServerSecretStore from "../../auth/ServerSecretStore.ts";
4import * as ServerEnvironment from "../../environment/ServerEnvironment.ts";
5// @effect-diagnostics nodeBuiltinImport:off
6import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
7import * as NodeServices from "@effect/platform-node/NodeServices";
8import * as NodePath from "node:path";
9import { expect, it } from "@effect/vitest";
10import { EnvironmentId, ProviderInstanceId, ProviderSessionId, ThreadId } from "@t3tools/contracts";
11import * as HostProcess from "@t3tools/shared/HostProcess";
12import * as Effect from "effect/Effect";
13import * as Exit from "effect/Exit";
14import * as Deferred from "effect/Deferred";
15import * as Fiber from "effect/Fiber";
16import * as FileSystem from "effect/FileSystem";
17import * as Layer from "effect/Layer";
18import * as Option from "effect/Option";
19import * as PlatformError from "effect/PlatformError";
20import * as Queue from "effect/Queue";
21import * as Schema from "effect/Schema";
22import * as Sink from "effect/Sink";
23import * as Stream from "effect/Stream";
24import * as TestClock from "effect/testing/TestClock";
25import { HttpClient, HttpClientResponse } from "effect/http";
26import * as ChildProcess from "effect/process/ChildProcess";
27import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
28
29import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
30import * as ServerConfig from "../../config.ts";
31import * as ServerSettings from "../../serverSettings.ts";
32import * as ResetCreditCoordinator from "../resetCreditCoordinator.ts";
33import * as ProviderLatestVersions from "@t3tools/provider-core/server/ProviderLatestVersions";
34import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
35import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
36import * as ModelManifest from "../ModelManifest.ts";
37import {
38 createProviderVersionAdvisory,
39 resolveLatestProviderVersion,
40} from "@t3tools/provider-core/server/maintenanceResolver";
41import { CodexDriver } from "./CodexDriver.ts";
42import * as CodexAdapterV2 from "../../orchestration-v2/Adapters/CodexAdapterV2.ts";
43import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
44import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
45import * as ProviderCredentialStore from "../ProviderCredentialStore.ts";
46import * as ProviderHostLive from "../ProviderHostLive.ts";
47
48const layerDeps = ServerConfig.layerTest(process.cwd(), {
49 prefix: "t3-codex-driver-maintenance-",
50}).pipe(
51 Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
52 Layer.provideMerge(IdAllocator.layer),
53 Layer.provideMerge(McpProviderSessions.layer),
54 Layer.provideMerge(
55 Layer.mock(CodexAdapterV2.CodexAppServerClientFactory)({
56 open: () => Effect.die("Maintenance resolution must not open a Codex session"),
57 }),
58 ),
59 Layer.provideMerge(
60 Layer.mock(CodexInstallation.CodexInstallation)({
61 managedDirectory: "unused-managed-installation",
62 }),
63 ),
64 Layer.provideMerge(Layer.mock(ServerSecretStore.ServerSecretStore)({})),
65 Layer.provideMerge(
66 Layer.mock(CodexManagedTokenBroker.CodexManagedTokenBroker)({
67 endpoint: Effect.succeed("unused-private-pipe"),
68 awaitIdle: Effect.void,
69 }),
70 ),
71 Layer.provideMerge(
72 Layer.succeed(ServerEnvironment.ServerEnvironmentIdentity, {
73 getEnvironmentId: Effect.succeed(EnvironmentId.make("00000000-0000-4000-8000-000000000001")),
74 }),
75 ),
76 Layer.provideMerge(ServerSettings.layerTest()),
77 Layer.provideMerge(ModelManifest.layerTest),
78 Layer.provideMerge(ResetCreditCoordinator.layerTest),
79 Layer.provideMerge(
80 Layer.mock(BackgroundPolicy.BackgroundPolicy)({
81 shouldRunScopeWork: () => Effect.succeed(false),
82 }),
83 ),
84 Layer.provideMerge(
85 Layer.succeed(
86 ProviderEventLoggers.ProviderEventLoggers,
87 ProviderEventLoggers.NoOpProviderEventLoggers,
88 ),
89 ),
90 Layer.provideMerge(ProviderLatestVersions.layer),
91 Layer.provideMerge(
92 Layer.succeed(
93 HttpClient.HttpClient,
94 HttpClient.make(() => Effect.die("Disabled Codex must not make an HTTP request")),
95 ),
96 ),
97);
98const layerTest = ProviderHostLive.layer.pipe(Layer.provideMerge(layerDeps));
99
100// The `#!/bin/sh` stub below cannot be resolved as an executable on Windows.
101const windowsHost = HostProcess.Platform.defaultValue() === "win32";
102
103const noSpawn = ChildProcessSpawner.make(() =>
104 Effect.die("Disabled Codex must not spawn a process"),
105);
106const encodeCredentials = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));
107
108it.layer(layerTest)("CodexDriver", (it) => {
109 const checkManagedAccount = (replacementTiming: "unchanged" | "during-probe") =>
110 Effect.gen(function* () {
111 const instanceId = ProviderInstanceId.make("restored-managed-account");
112 const credentials = new Map<string, Uint8Array>();
113 const catalogTokens: Array<string | undefined> = [];
114 const probeEntered = yield* Deferred.make<void>();
115 const resumeProbe = yield* Deferred.make<void>();
116 const secrets = ServerSecretStore.ServerSecretStore.of({
117 get: (key) => Effect.sync(() => Option.fromUndefinedOr(credentials.get(key))),
118 set: (key, value) =>
119 Effect.sync(() => {
120 credentials.set(key, value);
121 }),
122 remove: (key) =>
123 Effect.sync(() => {
124 credentials.delete(key);
125 }),
126 create: () => Effect.die("unused"),
127 getOrCreateRandom: () => Effect.die("unused"),
128 });
129 yield* Effect.gen(function* () {
130 const store = yield* ProviderCredentialStore.make("codex-chatgpt", instanceId);
131 const json = yield* encodeCredentials({
132 clientId: "oaiapp_test",
133 accessToken: "dummy-owned-access",
134 refreshToken: "dummy-refresh",
135 expiresAt: Number.MAX_SAFE_INTEGER,
136 earliestRefreshAt: null,
137 scopes: ["chatgpt.tokens.use.direct"],
138 subject: "test-user",
139 email: "account@example.test",
140 });
141 yield* store.set(new TextEncoder().encode(json));
142 const replacement = yield* encodeCredentials({
143 clientId: "oaiapp_replacement",
144 subject: "replacement-user",
145 email: "replacement@example.test",
146 accessToken: "replacement-access",
147 refreshToken: "replacement-refresh",
148 expiresAt: Number.MAX_SAFE_INTEGER,
149 earliestRefreshAt: null,
150 scopes: ["chatgpt.tokens.use.direct"],
151 });
152 const replaceAccount = store.set(new TextEncoder().encode(replacement)).pipe(Effect.orDie);
153 const executable = {
154 executablePath: "/user/bin/codex",
155 managedVersionDirectory: null,
156 source: "local" as const,
157 version: "0.156.1",
158 };
159 const installation = yield* CodexInstallation.CodexInstallation;
160 const serverConfig = yield* ServerConfig.ServerConfig;
161 const sharedHome = NodePath.join(serverConfig.stateDir, "shared-codex-home");
162 const launches: Array<
163 Parameters<CodexAdapterV2.CodexAppServerClientFactoryShape["open"]>[0]
164 > = [];
165
166 let interruptedChecks = 0;
167 let failAcquire = false;
168 const startupChecksInterrupted = yield* Deferred.make<void>();
169 const acquire = () =>
170 Effect.suspend(() => {
171 if (failAcquire)
172 return Effect.fail(
173 new CodexInstallation.CodexInstallationError({
174 operation: "acquire",
175 detail: "The fixture runtime is unavailable",
176 }),
177 );
178 if (interruptedChecks === 2) return Effect.succeed(executable);
179 interruptedChecks += 1;
180 return (
181 interruptedChecks === 2
182 ? Deferred.succeed(startupChecksInterrupted, undefined)
183 : Effect.void
184 ).pipe(Effect.andThen(Effect.interrupt));
185 });
186 const instance = yield* CodexDriver.create({
187 instanceId,
188 displayName: "Restored account",
189 enabled: true,
190 environment: [{ name: "OPENAI_API_KEY", value: "ambient-key", sensitive: true }],
191 config: { ...CodexDriver.defaultConfig(), setupMode: "managed", homePath: sharedHome },
192 }).pipe(
193 Effect.provideService(
194 CodexAdapterV2.CodexAppServerClientFactory,
195 CodexAdapterV2.CodexAppServerClientFactory.of({
196 open: (launch) =>
197 Effect.sync(() => launches.push(launch)).pipe(
198 Effect.andThen(Effect.die("The fixture stops after recording the launch")),
199 ),
200 }),
201 ),
202 Effect.provideService(
203 CodexInstallation.CodexInstallation,
204 CodexInstallation.CodexInstallation.of({
205 ...installation,
206 managedDirectory: "unused-managed-installation",
207 resolve: () => Effect.succeed(executable),
208 acquire,
209 }),
210 ),
211 Effect.provideService(
212 ChildProcessSpawner.ChildProcessSpawner,
213 ChildProcessSpawner.make(() =>
214 Effect.gen(function* () {
215 if (replacementTiming === "during-probe") {
216 yield* Deferred.succeed(probeEntered, undefined);
217 yield* Deferred.await(resumeProbe);
218 }
219 return yield* PlatformError.badArgument({
220 module: "ChildProcessSpawner",
221 method: "spawn",
222 description: "The fixture app-server is unavailable",
223 });
224 }),
225 ),
226 ),
227 );
228 const observedAccount = yield* Deferred.make<void>();
229 const disconnected = yield* instance.snapshot.streamChanges.pipe(
230 Stream.tap((provider) =>
231 provider.auth.status === "authenticated"
232 ? Deferred.succeed(observedAccount, undefined).pipe(Effect.asVoid)
233 : Effect.void,
234 ),
235 Stream.filter((provider) => provider.auth.status === "unauthenticated"),
236 Stream.runHead,
237 Effect.forkScoped,
238 );
239 yield* Deferred.await(startupChecksInterrupted);
240 const refresh = yield* instance.snapshot.refresh.pipe(Effect.forkChild);
241 if (replacementTiming === "during-probe") {
242 yield* Deferred.await(probeEntered);
243 yield* replaceAccount;
244 yield* Deferred.succeed(resumeProbe, undefined);
245 }
246 const restored = yield* Fiber.join(refresh);
247 if (replacementTiming === "during-probe") {
248 expect(catalogTokens).toEqual([]);
249 expect(restored.models).toEqual([]);
250 expect(restored.auth.email).toBe("replacement@example.test");
251 expect(restored.auth.profileId).toBe("oaiapp_replacement");
252 return;
253 }
254 expect(catalogTokens).toEqual(["Bearer dummy-owned-access"]);
255 expect(restored.auth.email).toBe("account@example.test");
256 expect(restored.runtimePaths?.homePath).toBe(sharedHome);
257 expect(restored.runtimePaths?.shadowHomePath).toContain(
258 NodePath.join("providers", "codex", instanceId, "shadow"),
259 );
260 const scan = yield* instance.snapshotForCwd!(serverConfig.stateDir).pipe(Effect.exit);
261 expect(Exit.isFailure(scan)).toBe(true);
262 failAcquire = true;
263 const runtimeScan = yield* instance.snapshotForCwd!(serverConfig.stateDir).pipe(
264 Effect.exit,
265 );
266 failAcquire = false;
267 expect(Exit.isFailure(runtimeScan)).toBe(true);
268 yield* Deferred.await(observedAccount);
269
270 const threadId = ThreadId.make("managed-account-thread");
271 yield* instance.orchestrationAdapter
272 .openSession({
273 threadId,
274 providerSessionId: ProviderSessionId.make("managed-account-session"),
275 modelSelection: { instanceId, model: "gpt-5.4" },
276 runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
277 runtimeMode: "full-access",
278 interactionMode: "default",
279 cwd: serverConfig.stateDir,
280 }),
281 })
282 .pipe(Effect.scoped, Effect.exit);
283 expect(launches).toHaveLength(1);
284 const launch = launches[0]!;
285 expect(launch.settings.binaryPath).toBe(executable.executablePath);
286 expect(launch.settings.launchArgs).toContain("openai_token_sharing");
287 expect(launch.environment.ACCESS_TOKEN).toBeUndefined();
288 expect(launch.settings.launchArgs).toContain("__managed-chatgpt-token");
289 expect(launch.settings.launchArgs).not.toContain("dummy-owned-access");
290 expect(launch.environment.OPENAI_API_KEY).toBeUndefined();
291 expect(launch.environment.CODEX_HOME).toBe(launch.settings.homePath);
292 const before = yield* instance.auth!.subscribe("test-owner").pipe(Stream.runHead);
293 expect(Option.getOrThrow(before).phase).toBe("idle");
294 yield* instance.auth!.logout(Effect.void);
295 const after = Option.getOrThrow(yield* Fiber.join(disconnected));
296 expect(after.auth.status).toBe("unauthenticated");
297 expect(after.auth.email).toBeUndefined();
298 expect(after.installed).toBe(true);
299 expect(after.models).toEqual([]);
300 expect(Option.isNone(yield* store.get)).toBe(true);
301 const signedOutScan = yield* instance.snapshotForCwd!(serverConfig.stateDir);
302 expect(signedOutScan.skills).toEqual([]);
303 }).pipe(
304 Effect.provideService(ServerSecretStore.ServerSecretStore, secrets),
305 Effect.provideService(
306 HttpClient.HttpClient,
307 HttpClient.make((request) =>
308 Effect.sync(() => {
309 expect([
310 "https://auth.openai.com/.well-known/openid-configuration",
311 "https://auth.openai.com/revoke",
312 "https://api.openai.com/v1/models",
313 ]).toContain(request.url);
314 if (request.url.endsWith("/models")) {
315 catalogTokens.push(request.headers.authorization);
316 return HttpClientResponse.fromWeb(request, Response.json({ models: [] }));
317 }
318 return HttpClientResponse.fromWeb(
319 request,
320 request.url.endsWith("/revoke")
321 ? new Response(null, { status: 200 })
322 : Response.json({
323 issuer: "https://auth.openai.com",
324 authorization_endpoint: "https://auth.openai.com/api/accounts/authorize",
325 token_endpoint: "https://auth.openai.com/api/accounts/oauth/token",
326 jwks_uri: "https://auth.openai.com/jwks",
327 revocation_endpoint: "https://auth.openai.com/revoke",
328 }),
329 );
330 }),
331 ),
332 ),
333 );
334 }).pipe(Effect.scoped);
335 // regression: a sign-in that replaces the account mid-probe must not label the old
336 // account's catalog with the new identity.
337 it.effect.each(["unchanged", "during-probe"] as const)(
338 "managed catalog keeps its account label and token together: %s",
339 checkManagedAccount,
340 );
341
342 it.effect.skipIf(windowsHost)(
343 "runs the standalone updater against the shared home, not the shadow home",
344 () =>
345 Effect.gen(function* () {
346 const fs = yield* FileSystem.FileSystem;
347 const tempDir = yield* fs
348 .makeTempDirectoryScoped({ prefix: "t3-codex-driver-" })
349 .pipe(Effect.flatMap((directory) => fs.realPath(directory)));
350 const sharedHome = NodePath.join(tempDir, "codex-home");
351 const shadowHome = NodePath.join(tempDir, "codex-shadow");
352 const binaryPath = NodePath.join(sharedHome, "packages", "standalone", "bin", "codex");
353 yield* fs.makeDirectory(NodePath.dirname(binaryPath), { recursive: true });
354 yield* fs.writeFileString(binaryPath, "#!/bin/sh\n");
355 yield* fs.chmod(binaryPath, 0o755);
356
357 const instance = yield* CodexDriver.create({
358 instanceId: ProviderInstanceId.make("codex-shadow"),
359 displayName: "Codex test",
360 enabled: false,
361 environment: [],
362 config: {
363 ...CodexDriver.defaultConfig(),
364 binaryPath,
365 homePath: sharedHome,
366 shadowHomePath: shadowHome,
367 },
368 });
369
370 const capabilities = yield* instance.snapshot.resolveMaintenance();
371 expect(capabilities.update).toMatchObject({
372 executable: binaryPath,
373 args: ["update"],
374 lockKey: "codex-native",
375 env: { CODEX_HOME: sharedHome },
376 });
377 }).pipe(
378 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn),
379 Effect.scoped,
380 ),
381 );
382
383 it.effect.skipIf(windowsHost)(
384 "runs the standalone updater against the home that holds a shared install",
385 () =>
386 Effect.gen(function* () {
387 const fs = yield* FileSystem.FileSystem;
388 const tempDir = yield* fs
389 .makeTempDirectoryScoped({ prefix: "t3-codex-driver-" })
390 .pipe(Effect.flatMap((directory) => fs.realPath(directory)));
391 // One standalone install, linked onto PATH and used by two account homes.
392 // `İ` gets longer when lowercased, so the home must not be sliced from a
393 // lowercased copy of the path.
394 const installHome = NodePath.join(tempDir, "codex-İnstall");
395 const realBinaryPath = NodePath.join(
396 installHome,
397 "packages",
398 "standalone",
399 "releases",
400 "0.162.1-x86_64-unknown-linux-musl",
401 "bin",
402 "codex",
403 );
404 const binaryPath = NodePath.join(tempDir, "bin", "codex");
405 yield* fs.makeDirectory(NodePath.dirname(realBinaryPath), { recursive: true });
406 yield* fs.makeDirectory(NodePath.dirname(binaryPath), { recursive: true });
407 yield* fs.writeFileString(realBinaryPath, "#!/bin/sh\n");
408 yield* fs.chmod(realBinaryPath, 0o755);
409 yield* fs.symlink(realBinaryPath, binaryPath);
410
411 const updates = yield* Effect.forEach(["codex-p", "codex-vm"], (account) =>
412 Effect.gen(function* () {
413 const homePath = NodePath.join(tempDir, `home-${account}`);
414 yield* fs.makeDirectory(homePath, { recursive: true });
415 const instance = yield* CodexDriver.create({
416 instanceId: ProviderInstanceId.make(account),
417 displayName: account,
418 enabled: false,
419 environment: [],
420 config: { ...CodexDriver.defaultConfig(), binaryPath, homePath },
421 });
422 return (yield* instance.snapshot.resolveMaintenance()).update;
423 }),
424 );
425
426 for (const update of updates) {
427 expect(update).toMatchObject({
428 command: `${binaryPath} update`,
429 args: ["update"],
430 lockKey: "codex-native",
431 env: { CODEX_HOME: installHome },
432 });
433 }
434 }).pipe(
435 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn),
436 Effect.scoped,
437 ),
438 );
439
440 it.effect.skipIf(windowsHost)("derives the standalone update home from either command path", () =>
441 Effect.gen(function* () {
442 const fs = yield* FileSystem.FileSystem;
443 const tempDir = yield* fs
444 .makeTempDirectoryScoped({ prefix: "t3-codex-update-home-" })
445 .pipe(Effect.flatMap((directory) => fs.realPath(directory)));
446 const linkedInstallHome = NodePath.join(tempDir, "install");
447 const fixtures = [
448 { binary: "codex", realPath: "/packages/standalone/bin/codex", home: "/" },
449 { binary: "codex", realPath: "C:\\Packages\\Standalone\\bin\\codex.exe", home: "C:\\" },
450 // The standalone tree itself is a symlink, so only the resolved path names its home.
451 {
452 binary: NodePath.join("install", "packages", "standalone", "bin", "codex"),
453 realPath: "/disk/codex/releases/0.163.0/bin/codex",
454 home: linkedInstallHome,
455 },
456 ];
457
458 for (const fixture of fixtures) {
459 const binaryPath = NodePath.join(tempDir, fixture.binary);
460 yield* fs.makeDirectory(NodePath.dirname(binaryPath), { recursive: true });
461 yield* fs.writeFileString(binaryPath, "#!/bin/sh\n");
462 yield* fs.chmod(binaryPath, 0o755);
463 const instance = yield* CodexDriver.create({
464 instanceId: ProviderInstanceId.make("codex-update-home"),
465 displayName: "Codex update home",
466 enabled: false,
467 environment: [],
468 config: { ...CodexDriver.defaultConfig(), binaryPath, homePath: tempDir },
469 }).pipe(
470 // Virtualize only the executable target: these trees do not belong to this test.
471 Effect.provideService(FileSystem.FileSystem, {
472 ...fs,
473 realPath: (path) =>
474 path === binaryPath ? Effect.succeed(fixture.realPath) : fs.realPath(path),
475 }),
476 );
477 expect((yield* instance.snapshot.resolveMaintenance()).update?.env).toEqual({
478 CODEX_HOME: fixture.home,
479 });
480 }
481 }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn), Effect.scoped),
482 );
483
484 it.effect("uses each instance's environment CODEX_HOME for continuation", () =>
485 Effect.gen(function* () {
486 const fs = yield* FileSystem.FileSystem;
487 const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-codex-driver-" });
488 for (const [index, account] of ["work", "personal", "work "].entries()) {
489 const codexHome = NodePath.join(tempDir, account);
490 const instance = yield* CodexDriver.create({
491 instanceId: ProviderInstanceId.make(`account-${index}`),
492 displayName: account,
493 enabled: false,
494 environment: [{ name: "CODEX_HOME", value: codexHome, sensitive: false }],
495 config: CodexDriver.defaultConfig(),
496 });
497 expect(instance.continuationIdentity.continuationKey).toBe(`codex:home:${codexHome}`);
498 }
499 }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn), Effect.scoped),
500 );
501
502 for (const fixture of [
503 {
504 name: "leaves mise npm-backend installations manual-only",
505 installSegments: ["mise", "installs", "npm-openai-codex", "0.110.0"],
506 npmOwned: false,
507 },
508 {
509 name: "leaves mise tool aliases backed by npm manual-only",
510 installSegments: ["mise", "installs", "codex", "0.110.0"],
511 npmOwned: false,
512 },
513 {
514 name: "keeps npm updates for globals in a mise Node installation",
515 installSegments: ["mise", "installs", "node", "24.0.0"],
516 npmOwned: true,
517 },
518 {
519 name: "keeps npm updates for ordinary global installations",
520 installSegments: ["npm-global"],
521 npmOwned: true,
522 },
523 ] as const) {
524 it.effect.skipIf(windowsHost)(fixture.name, () =>
525 Effect.gen(function* () {
526 const fs = yield* FileSystem.FileSystem;
527 const tempDir = yield* fs
528 .makeTempDirectoryScoped({ prefix: "t3-codex-installer-" })
529 .pipe(Effect.flatMap((directory) => fs.realPath(directory)));
530 const installPath = NodePath.join(tempDir, ...fixture.installSegments);
531 const realBinaryPath = NodePath.join(
532 installPath,
533 "lib",
534 "node_modules",
535 "@openai",
536 "codex",
537 "bin",
538 "codex.js",
539 );
540 const binaryPath = NodePath.join(tempDir, "bin", "codex");
541 yield* fs.makeDirectory(NodePath.dirname(realBinaryPath), { recursive: true });
542 yield* fs.makeDirectory(NodePath.dirname(binaryPath), { recursive: true });
543 yield* fs.writeFileString(realBinaryPath, "#!/bin/sh\n");
544 yield* fs.chmod(realBinaryPath, 0o755);
545 yield* fs.symlink(realBinaryPath, binaryPath);
546
547 const instance = yield* CodexDriver.create({
548 instanceId: ProviderInstanceId.make("codex-installer"),
549 displayName: "Codex installer test",
550 enabled: false,
551 environment: [],
552 config: {
553 ...CodexDriver.defaultConfig(),
554 binaryPath,
555 homePath: NodePath.join(tempDir, "codex-home"),
556 },
557 });
558
559 const update = (yield* instance.snapshot.resolveMaintenance()).update;
560 if (fixture.npmOwned) {
561 expect(update).toMatchObject({
562 executable: "npm",
563 args: [
564 "install",
565 "-g",
566 "--prefix",
567 installPath,
568 "--allow-scripts=@openai/codex",
569 "@openai/codex@latest",
570 ],
571 });
572 } else {
573 expect(update).toBeNull();
574 }
575 }).pipe(
576 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn),
577 Effect.scoped,
578 ),
579 );
580 }
581
582 it.effect.each([
583 {
584 name: "conventional shim",
585 dataRoot: "mise",
586 commandName: "codex",
587 version: "0.153.4",
588 nodeFirst: false,
589 },
590 {
591 name: "custom data directory",
592 dataRoot: "custom-tool-data",
593 commandName: "codex",
594 version: "0.153.4",
595 nodeFirst: false,
596 },
597 {
598 name: "renamed configured command",
599 dataRoot: "mise",
600 commandName: "custom-codex",
601 version: "0.153.4",
602 nodeFirst: false,
603 },
604 {
605 name: "outdated provider",
606 dataRoot: "mise",
607 commandName: "codex",
608 version: "0.153.3",
609 nodeFirst: false,
610 },
611 {
612 name: "npm before shim",
613 dataRoot: "mise",
614 commandName: "codex",
615 version: "0.153.4",
616 nodeFirst: true,
617 },
618 ])(
619 "does not mistake Homebrew mise for Codex's installer: $name",
620 (fixture) =>
621 Effect.gen(function* () {
622 const fs = yield* FileSystem.FileSystem;
623 const tempDir = yield* fs
624 .makeTempDirectoryScoped({ prefix: "t3-codex-mise-shim-" })
625 .pipe(Effect.flatMap((directory) => fs.realPath(directory)));
626 const brewPrefix = NodePath.join(tempDir, "homebrew");
627 const brewPath = NodePath.join(brewPrefix, "bin", "brew");
628 const misePath = NodePath.join(brewPrefix, "Cellar", "mise", "2026.9.1", "bin", "mise");
629 const shimDir = NodePath.join(tempDir, fixture.dataRoot, "shims");
630 const npmPrefix = NodePath.join(tempDir, "mise", "installs", "node", "24.13.0");
631 const npmBin = NodePath.join(npmPrefix, "bin");
632 const npmEntry = NodePath.join(
633 npmPrefix,
634 "lib",
635 "node_modules",
636 "@openai",
637 "codex",
638 "bin",
639 "codex.js",
640 );
641 for (const file of [brewPath, misePath, npmEntry]) {
642 yield* fs.makeDirectory(NodePath.dirname(file), { recursive: true });
643 yield* fs.writeFileString(file, "#!/bin/sh\n");
644 yield* fs.chmod(file, 0o755);
645 }
646 yield* fs.makeDirectory(shimDir, { recursive: true });
647 yield* fs.makeDirectory(npmBin, { recursive: true });
648 yield* fs.symlink(misePath, NodePath.join(shimDir, fixture.commandName));
649 yield* fs.symlink(npmEntry, NodePath.join(npmBin, fixture.commandName));
650 const lookupPath = [
651 ...(fixture.nodeFirst ? [npmBin, shimDir] : [shimDir, npmBin]),
652 NodePath.dirname(brewPath),
653 ].join(NodePath.delimiter);
654 const probes: Array<ReadonlyArray<string>> = [];
655 const metadataSpawner = ChildProcessSpawner.make((command) => {
656 if (!ChildProcess.isStandardCommand(command) || command.command !== brewPath) {
657 return Effect.die("Provider resolution must not execute a provider or updater");
658 }
659 probes.push(command.args.map(String));
660 const stdout =
661 command.args[0] === "--prefix"
662 ? brewPrefix
663 : JSON.stringify({ formulae: [{ versions: { stable: "2026.9.1" } }] });
664 return Effect.succeed(
665 ChildProcessSpawner.makeHandle({
666 pid: ChildProcessSpawner.ProcessId(1),
667 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)),
668 isRunning: Effect.succeed(false),
669 kill: () => Effect.void,
670 unref: Effect.succeed(Effect.void),
671 stdin: Sink.drain,
672 stdout: Stream.encodeText(Stream.make(stdout)),
673 stderr: Stream.empty,
674 all: Stream.empty,
675 getInputFd: () => Sink.drain,
676 getOutputFd: () => Stream.empty,
677 }),
678 );
679 });
680 const instance = yield* CodexDriver.create({
681 instanceId: ProviderInstanceId.make("codex-mise-shim"),
682 displayName: "Codex shim test",
683 enabled: false,
684 environment: [{ name: "PATH", value: lookupPath, sensitive: false }],
685 config: {
686 ...CodexDriver.defaultConfig(),
687 binaryPath: fixture.commandName,
688 homePath: NodePath.join(tempDir, "codex-home"),
689 },
690 }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, metadataSpawner));
691 const capabilities = yield* instance.snapshot
692 .resolveMaintenance()
693 .pipe(Effect.provideService(HostProcess.Environment, { PATH: "" }));
694 const latestVersion = yield* resolveLatestProviderVersion(capabilities).pipe(
695 Effect.provideServiceEffect(
696 ProviderLatestVersions.ProviderLatestVersions,
697 ProviderLatestVersions.make([["@openai/codex", "0.153.4"]]),
698 ),
699 );
700 expect(probes).toEqual([]);
701 expect(latestVersion).toBe("0.153.4");
702 expect(
703 createProviderVersionAdvisory({
704 driver: CodexDriver.driverKind,
705 currentVersion: fixture.version,
706 latestVersion,
707 maintenanceCapabilities: capabilities,
708 }),
709 ).toMatchObject({
710 status: fixture.version === "0.153.4" ? "current" : "behind_latest",
711 currentVersion: fixture.version,
712 latestVersion: "0.153.4",
713 canUpdate: fixture.nodeFirst,
714 });
715 if (fixture.nodeFirst) {
716 expect(capabilities.update).toMatchObject({
717 executable: "npm",
718 args: expect.arrayContaining([
719 "--prefix",
720 yield* fs.realPath(npmPrefix),
721 "@openai/codex@latest",
722 ]),
723 });
724 } else {
725 expect(capabilities.update).toBeNull();
726 }
727 }).pipe(Effect.scoped),
728 { skip: windowsHost },
729 );
730
731 it.effect("probes again when auth.json in the Codex home changes", () =>
732 Effect.gen(function* () {
733 const fs = yield* FileSystem.FileSystem;
734 const codexHome = yield* fs.makeTempDirectoryScoped({ prefix: "t3-codex-auth-watch-" });
735 const watchedPath = yield* Deferred.make<string>();
736 const homeEvents = yield* Queue.unbounded<FileSystem.WatchEvent>();
737 const probes = yield* Queue.unbounded<void>();
738 yield* CodexDriver.create({
739 instanceId: ProviderInstanceId.make("codex-auth-watch"),
740 displayName: "Codex auth watch",
741 enabled: true,
742 environment: [],
743 config: { ...CodexDriver.defaultConfig(), homePath: codexHome },
744 }).pipe(
745 // OS watchers can miss events written right after they start, so the test supplies them.
746 Effect.provideService(FileSystem.FileSystem, {
747 ...fs,
748 watch: (path) =>
749 Stream.unwrap(
750 Deferred.succeed(watchedPath, path).pipe(Effect.as(Stream.fromQueue(homeEvents))),
751 ),
752 }),
753 Effect.provideService(
754 ChildProcessSpawner.ChildProcessSpawner,
755 ChildProcessSpawner.make((command) =>
756 (ChildProcess.isStandardCommand(command) && command.args.includes("app-server")
757 ? Queue.offer(probes, undefined)
758 : Effect.void
759 ).pipe(
760 Effect.andThen(
761 PlatformError.badArgument({
762 module: "ChildProcessSpawner",
763 method: "spawn",
764 description: "The fixture has no Codex executable",
765 }),
766 ),
767 ),
768 ),
769 ),
770 );
771 expect(yield* Deferred.await(watchedPath)).toBe(codexHome);
772 yield* Queue.take(probes);
773
774 yield* Queue.offer(homeEvents, { _tag: "Update", path: "auth.json" });
775 yield* TestClock.adjust("250 millis");
776
777 yield* Queue.take(probes);
778 }).pipe(Effect.scoped),
779 );
780});