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(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn)),
378 );
379
380 it.effect.skipIf(windowsHost)(
381 "runs the standalone updater against the home that holds a shared install",
382 () =>
383 Effect.gen(function* () {
384 const fs = yield* FileSystem.FileSystem;
385 const tempDir = yield* fs
386 .makeTempDirectoryScoped({ prefix: "t3-codex-driver-" })
387 .pipe(Effect.flatMap((directory) => fs.realPath(directory)));
388 // One standalone install, linked onto PATH and used by two account homes.
389 // `İ` gets longer when lowercased, so the home must not be sliced from a
390 // lowercased copy of the path.
391 const installHome = NodePath.join(tempDir, "codex-İnstall");
392 const realBinaryPath = NodePath.join(
393 installHome,
394 "packages",
395 "standalone",
396 "releases",
397 "0.162.1-x86_64-unknown-linux-musl",
398 "bin",
399 "codex",
400 );
401 const binaryPath = NodePath.join(tempDir, "bin", "codex");
402 yield* fs.makeDirectory(NodePath.dirname(realBinaryPath), { recursive: true });
403 yield* fs.makeDirectory(NodePath.dirname(binaryPath), { recursive: true });
404 yield* fs.writeFileString(realBinaryPath, "#!/bin/sh\n");
405 yield* fs.chmod(realBinaryPath, 0o755);
406 yield* fs.symlink(realBinaryPath, binaryPath);
407
408 const updates = yield* Effect.forEach(["codex-p", "codex-vm"], (account) =>
409 Effect.gen(function* () {
410 const homePath = NodePath.join(tempDir, `home-${account}`);
411 yield* fs.makeDirectory(homePath, { recursive: true });
412 const instance = yield* CodexDriver.create({
413 instanceId: ProviderInstanceId.make(account),
414 displayName: account,
415 enabled: false,
416 environment: [],
417 config: { ...CodexDriver.defaultConfig(), binaryPath, homePath },
418 });
419 return (yield* instance.snapshot.resolveMaintenance()).update;
420 }),
421 );
422
423 for (const update of updates) {
424 expect(update).toMatchObject({
425 command: `${binaryPath} update`,
426 args: ["update"],
427 lockKey: "codex-native",
428 env: { CODEX_HOME: installHome },
429 });
430 }
431 }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn)),
432 );
433
434 it.effect.skipIf(windowsHost)("derives the standalone update home from either command path", () =>
435 Effect.gen(function* () {
436 const fs = yield* FileSystem.FileSystem;
437 const tempDir = yield* fs
438 .makeTempDirectoryScoped({ prefix: "t3-codex-update-home-" })
439 .pipe(Effect.flatMap((directory) => fs.realPath(directory)));
440 const linkedInstallHome = NodePath.join(tempDir, "install");
441 const fixtures = [
442 { binary: "codex", realPath: "/packages/standalone/bin/codex", home: "/" },
443 { binary: "codex", realPath: "C:\\Packages\\Standalone\\bin\\codex.exe", home: "C:\\" },
444 // The standalone tree itself is a symlink, so only the resolved path names its home.
445 {
446 binary: NodePath.join("install", "packages", "standalone", "bin", "codex"),
447 realPath: "/disk/codex/releases/0.163.0/bin/codex",
448 home: linkedInstallHome,
449 },
450 ];
451
452 for (const fixture of fixtures) {
453 const binaryPath = NodePath.join(tempDir, fixture.binary);
454 yield* fs.makeDirectory(NodePath.dirname(binaryPath), { recursive: true });
455 yield* fs.writeFileString(binaryPath, "#!/bin/sh\n");
456 yield* fs.chmod(binaryPath, 0o755);
457 const instance = yield* CodexDriver.create({
458 instanceId: ProviderInstanceId.make("codex-update-home"),
459 displayName: "Codex update home",
460 enabled: false,
461 environment: [],
462 config: { ...CodexDriver.defaultConfig(), binaryPath, homePath: tempDir },
463 }).pipe(
464 // Virtualize only the executable target: these trees do not belong to this test.
465 Effect.provideService(FileSystem.FileSystem, {
466 ...fs,
467 realPath: (path) =>
468 path === binaryPath ? Effect.succeed(fixture.realPath) : fs.realPath(path),
469 }),
470 );
471 expect((yield* instance.snapshot.resolveMaintenance()).update?.env).toEqual({
472 CODEX_HOME: fixture.home,
473 });
474 }
475 }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn)),
476 );
477
478 // regression: #23937 `codex update` installs the native channel's release, which can lag npm.
479 it.effect.skipIf(windowsHost)(
480 "does not advertise npm's latest Codex to a standalone install",
481 () =>
482 Effect.gen(function* () {
483 const fs = yield* FileSystem.FileSystem;
484 const tempDir = yield* fs
485 .makeTempDirectoryScoped({ prefix: "t3-codex-driver-" })
486 .pipe(Effect.flatMap((directory) => fs.realPath(directory)));
487 const home = NodePath.join(tempDir, "codex-home");
488 const binaryPath = NodePath.join(home, "packages", "standalone", "current", "bin", "codex");
489 yield* fs.makeDirectory(NodePath.dirname(binaryPath), { recursive: true });
490 yield* fs.writeFileString(binaryPath, "#!/bin/sh\n");
491 yield* fs.chmod(binaryPath, 0o755);
492 // npm's latest tag is ahead of the native channel, as during a staggered release.
493 const npmView = ChildProcessSpawner.make((command) => {
494 if (!ChildProcess.isStandardCommand(command) || command.args[0] !== "view") {
495 return Effect.die("Version lookup must not run a provider or updater");
496 }
497 return Effect.succeed(
498 ChildProcessSpawner.makeHandle({
499 pid: ChildProcessSpawner.ProcessId(1),
500 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)),
501 isRunning: Effect.succeed(false),
502 kill: () => Effect.void,
503 unref: Effect.succeed(Effect.void),
504 stdin: Sink.drain,
505 stdout: Stream.encodeText(Stream.make('"0.164.0"')),
506 stderr: Stream.empty,
507 all: Stream.empty,
508 getInputFd: () => Sink.drain,
509 getOutputFd: () => Stream.empty,
510 }),
511 );
512 });
513 const instance = yield* CodexDriver.create({
514 instanceId: ProviderInstanceId.make("codex-standalone-latest"),
515 displayName: "Codex standalone",
516 enabled: false,
517 environment: [],
518 config: { ...CodexDriver.defaultConfig(), binaryPath, homePath: home },
519 }).pipe(
520 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, npmView),
521 Effect.provideService(
522 HttpClient.HttpClient,
523 HttpClient.make((request) =>
524 Effect.succeed(
525 HttpClientResponse.fromWeb(
526 request,
527 request.url === "https://releases.openai.com/codex/channels/latest"
528 ? Response.json({ tag_name: "rust-v0.163.0", assets: [] })
529 : new Response(null, { status: 404 }),
530 ),
531 ),
532 ),
533 ),
534 );
535 const capabilities = yield* instance.snapshot.resolveMaintenance();
536 expect(capabilities.update?.lockKey).toBe("codex-native");
537
538 const latestVersion = yield* resolveLatestProviderVersion(capabilities).pipe(
539 Effect.provideServiceEffect(
540 ProviderLatestVersions.ProviderLatestVersions,
541 ProviderLatestVersions.make(),
542 ),
543 );
544 expect(latestVersion).toBe("0.163.0");
545 expect(
546 createProviderVersionAdvisory({
547 driver: CodexDriver.driverKind,
548 currentVersion: "0.163.0",
549 latestVersion,
550 maintenanceCapabilities: capabilities,
551 }).status,
552 ).not.toBe("behind_latest");
553 }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn)),
554 );
555
556 it.effect("uses each instance's environment CODEX_HOME for continuation", () =>
557 Effect.gen(function* () {
558 const fs = yield* FileSystem.FileSystem;
559 const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-codex-driver-" });
560 for (const [index, account] of ["work", "personal", "work "].entries()) {
561 const codexHome = NodePath.join(tempDir, account);
562 const instance = yield* CodexDriver.create({
563 instanceId: ProviderInstanceId.make(`account-${index}`),
564 displayName: account,
565 enabled: false,
566 environment: [{ name: "CODEX_HOME", value: codexHome, sensitive: false }],
567 config: CodexDriver.defaultConfig(),
568 });
569 expect(instance.continuationIdentity.continuationKey).toBe(`codex:home:${codexHome}`);
570 }
571 }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn)),
572 );
573
574 it.effect.skipIf(windowsHost)(
575 "shares state from the environment CODEX_HOME in a shadow home",
576 () =>
577 Effect.gen(function* () {
578 const fs = yield* FileSystem.FileSystem;
579 const tempDir = yield* fs
580 .makeTempDirectoryScoped({ prefix: "t3-codex-driver-" })
581 .pipe(Effect.flatMap((directory) => fs.realPath(directory)));
582 const codexHome = NodePath.join(tempDir, "custom-codex");
583 const shadowHome = NodePath.join(tempDir, "shadow");
584 yield* fs.makeDirectory(codexHome, { recursive: true });
585 yield* fs.writeFileString(NodePath.join(codexHome, "config.toml"), 'model = "custom"\n');
586 const instance = yield* CodexDriver.create({
587 instanceId: ProviderInstanceId.make("env-shadow"),
588 displayName: "env-shadow",
589 enabled: false,
590 environment: [{ name: "CODEX_HOME", value: codexHome, sensitive: false }],
591 config: { ...CodexDriver.defaultConfig(), shadowHomePath: shadowHome },
592 }).pipe(Effect.provideService(HostProcess.HomeDirectory, NodePath.join(tempDir, "user")));
593 expect(instance.continuationIdentity.continuationKey).toBe(`codex:home:${codexHome}`);
594 expect(yield* fs.readLink(NodePath.join(shadowHome, "config.toml"))).toBe(
595 NodePath.join(codexHome, "config.toml"),
596 );
597 expect(yield* fs.readLink(NodePath.join(shadowHome, "sessions"))).toBe(
598 NodePath.join(codexHome, "sessions"),
599 );
600 }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn)),
601 );
602
603 for (const fixture of [
604 {
605 name: "leaves mise npm-backend installations manual-only",
606 installSegments: ["mise", "installs", "npm-openai-codex", "0.110.0"],
607 npmOwned: false,
608 },
609 {
610 name: "leaves mise tool aliases backed by npm manual-only",
611 installSegments: ["mise", "installs", "codex", "0.110.0"],
612 npmOwned: false,
613 },
614 {
615 name: "keeps npm updates for globals in a mise Node installation",
616 installSegments: ["mise", "installs", "node", "24.0.0"],
617 npmOwned: true,
618 },
619 {
620 name: "keeps npm updates for ordinary global installations",
621 installSegments: ["npm-global"],
622 npmOwned: true,
623 },
624 ] as const) {
625 it.effect.skipIf(windowsHost)(fixture.name, () =>
626 Effect.gen(function* () {
627 const fs = yield* FileSystem.FileSystem;
628 const tempDir = yield* fs
629 .makeTempDirectoryScoped({ prefix: "t3-codex-installer-" })
630 .pipe(Effect.flatMap((directory) => fs.realPath(directory)));
631 const installPath = NodePath.join(tempDir, ...fixture.installSegments);
632 const realBinaryPath = NodePath.join(
633 installPath,
634 "lib",
635 "node_modules",
636 "@openai",
637 "codex",
638 "bin",
639 "codex.js",
640 );
641 const binaryPath = NodePath.join(tempDir, "bin", "codex");
642 yield* fs.makeDirectory(NodePath.dirname(realBinaryPath), { recursive: true });
643 yield* fs.makeDirectory(NodePath.dirname(binaryPath), { recursive: true });
644 yield* fs.writeFileString(realBinaryPath, "#!/bin/sh\n");
645 yield* fs.chmod(realBinaryPath, 0o755);
646 yield* fs.symlink(realBinaryPath, binaryPath);
647
648 const instance = yield* CodexDriver.create({
649 instanceId: ProviderInstanceId.make("codex-installer"),
650 displayName: "Codex installer test",
651 enabled: false,
652 environment: [],
653 config: {
654 ...CodexDriver.defaultConfig(),
655 binaryPath,
656 homePath: NodePath.join(tempDir, "codex-home"),
657 },
658 });
659
660 const update = (yield* instance.snapshot.resolveMaintenance()).update;
661 if (fixture.npmOwned) {
662 expect(update).toMatchObject({
663 executable: "npm",
664 args: [
665 "install",
666 "-g",
667 "--prefix",
668 installPath,
669 "--allow-scripts=@openai/codex",
670 "@openai/codex@latest",
671 ],
672 });
673 } else {
674 expect(update).toBeNull();
675 }
676 }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn)),
677 );
678 }
679
680 it.effect.each([
681 {
682 name: "conventional shim",
683 dataRoot: "mise",
684 commandName: "codex",
685 version: "0.153.4",
686 nodeFirst: false,
687 },
688 {
689 name: "custom data directory",
690 dataRoot: "custom-tool-data",
691 commandName: "codex",
692 version: "0.153.4",
693 nodeFirst: false,
694 },
695 {
696 name: "renamed configured command",
697 dataRoot: "mise",
698 commandName: "custom-codex",
699 version: "0.153.4",
700 nodeFirst: false,
701 },
702 {
703 name: "outdated provider",
704 dataRoot: "mise",
705 commandName: "codex",
706 version: "0.153.3",
707 nodeFirst: false,
708 },
709 {
710 name: "npm before shim",
711 dataRoot: "mise",
712 commandName: "codex",
713 version: "0.153.4",
714 nodeFirst: true,
715 },
716 ])(
717 "does not mistake Homebrew mise for Codex's installer: $name",
718 (fixture) =>
719 Effect.gen(function* () {
720 const fs = yield* FileSystem.FileSystem;
721 const tempDir = yield* fs
722 .makeTempDirectoryScoped({ prefix: "t3-codex-mise-shim-" })
723 .pipe(Effect.flatMap((directory) => fs.realPath(directory)));
724 const brewPrefix = NodePath.join(tempDir, "homebrew");
725 const brewPath = NodePath.join(brewPrefix, "bin", "brew");
726 const misePath = NodePath.join(brewPrefix, "Cellar", "mise", "2026.9.1", "bin", "mise");
727 const shimDir = NodePath.join(tempDir, fixture.dataRoot, "shims");
728 const npmPrefix = NodePath.join(tempDir, "mise", "installs", "node", "24.13.0");
729 const npmBin = NodePath.join(npmPrefix, "bin");
730 const npmEntry = NodePath.join(
731 npmPrefix,
732 "lib",
733 "node_modules",
734 "@openai",
735 "codex",
736 "bin",
737 "codex.js",
738 );
739 for (const file of [brewPath, misePath, npmEntry]) {
740 yield* fs.makeDirectory(NodePath.dirname(file), { recursive: true });
741 yield* fs.writeFileString(file, "#!/bin/sh\n");
742 yield* fs.chmod(file, 0o755);
743 }
744 yield* fs.makeDirectory(shimDir, { recursive: true });
745 yield* fs.makeDirectory(npmBin, { recursive: true });
746 yield* fs.symlink(misePath, NodePath.join(shimDir, fixture.commandName));
747 yield* fs.symlink(npmEntry, NodePath.join(npmBin, fixture.commandName));
748 const lookupPath = [
749 ...(fixture.nodeFirst ? [npmBin, shimDir] : [shimDir, npmBin]),
750 NodePath.dirname(brewPath),
751 ].join(NodePath.delimiter);
752 const probes: Array<ReadonlyArray<string>> = [];
753 const metadataSpawner = ChildProcessSpawner.make((command) => {
754 if (!ChildProcess.isStandardCommand(command) || command.command !== brewPath) {
755 return Effect.die("Provider resolution must not execute a provider or updater");
756 }
757 probes.push(command.args.map(String));
758 const stdout =
759 command.args[0] === "--prefix"
760 ? brewPrefix
761 : JSON.stringify({ formulae: [{ versions: { stable: "2026.9.1" } }] });
762 return Effect.succeed(
763 ChildProcessSpawner.makeHandle({
764 pid: ChildProcessSpawner.ProcessId(1),
765 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)),
766 isRunning: Effect.succeed(false),
767 kill: () => Effect.void,
768 unref: Effect.succeed(Effect.void),
769 stdin: Sink.drain,
770 stdout: Stream.encodeText(Stream.make(stdout)),
771 stderr: Stream.empty,
772 all: Stream.empty,
773 getInputFd: () => Sink.drain,
774 getOutputFd: () => Stream.empty,
775 }),
776 );
777 });
778 const instance = yield* CodexDriver.create({
779 instanceId: ProviderInstanceId.make("codex-mise-shim"),
780 displayName: "Codex shim test",
781 enabled: false,
782 environment: [{ name: "PATH", value: lookupPath, sensitive: false }],
783 config: {
784 ...CodexDriver.defaultConfig(),
785 binaryPath: fixture.commandName,
786 homePath: NodePath.join(tempDir, "codex-home"),
787 },
788 }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, metadataSpawner));
789 const capabilities = yield* instance.snapshot
790 .resolveMaintenance()
791 .pipe(Effect.provideService(HostProcess.Environment, { PATH: "" }));
792 const latestVersion = yield* resolveLatestProviderVersion(capabilities).pipe(
793 Effect.provideServiceEffect(
794 ProviderLatestVersions.ProviderLatestVersions,
795 ProviderLatestVersions.make([["@openai/codex", "0.153.4"]]),
796 ),
797 );
798 expect(probes).toEqual([]);
799 expect(latestVersion).toBe("0.153.4");
800 expect(
801 createProviderVersionAdvisory({
802 driver: CodexDriver.driverKind,
803 currentVersion: fixture.version,
804 latestVersion,
805 maintenanceCapabilities: capabilities,
806 }),
807 ).toMatchObject({
808 status: fixture.version === "0.153.4" ? "current" : "behind_latest",
809 currentVersion: fixture.version,
810 latestVersion: "0.153.4",
811 canUpdate: fixture.nodeFirst,
812 });
813 if (fixture.nodeFirst) {
814 expect(capabilities.update).toMatchObject({
815 executable: "npm",
816 args: expect.arrayContaining([
817 "--prefix",
818 yield* fs.realPath(npmPrefix),
819 "@openai/codex@latest",
820 ]),
821 });
822 } else {
823 expect(capabilities.update).toBeNull();
824 }
825 }),
826 { skip: windowsHost },
827 );
828
829 it.effect("probes again when auth.json in the Codex home changes", () =>
830 Effect.gen(function* () {
831 const fs = yield* FileSystem.FileSystem;
832 const codexHome = yield* fs.makeTempDirectoryScoped({ prefix: "t3-codex-auth-watch-" });
833 const watchedPath = yield* Deferred.make<string>();
834 const homeEvents = yield* Queue.unbounded<FileSystem.WatchEvent>();
835 const probes = yield* Queue.unbounded<void>();
836 yield* CodexDriver.create({
837 instanceId: ProviderInstanceId.make("codex-auth-watch"),
838 displayName: "Codex auth watch",
839 enabled: true,
840 environment: [],
841 config: { ...CodexDriver.defaultConfig(), homePath: codexHome },
842 }).pipe(
843 // OS watchers can miss events written right after they start, so the test supplies them.
844 Effect.provideService(FileSystem.FileSystem, {
845 ...fs,
846 watch: (path) =>
847 Stream.unwrap(
848 Deferred.succeed(watchedPath, path).pipe(Effect.as(Stream.fromQueue(homeEvents))),
849 ),
850 }),
851 Effect.provideService(
852 ChildProcessSpawner.ChildProcessSpawner,
853 ChildProcessSpawner.make((command) =>
854 (ChildProcess.isStandardCommand(command) && command.args.includes("app-server")
855 ? Queue.offer(probes, undefined)
856 : Effect.void
857 ).pipe(
858 Effect.andThen(
859 PlatformError.badArgument({
860 module: "ChildProcessSpawner",
861 method: "spawn",
862 description: "The fixture has no Codex executable",
863 }),
864 ),
865 ),
866 ),
867 ),
868 );
869 expect(yield* Deferred.await(watchedPath)).toBe(codexHome);
870 yield* Queue.take(probes);
871
872 yield* Queue.offer(homeEvents, { _tag: "Update", path: "auth.json" });
873 yield* TestClock.adjust("250 millis");
874
875 yield* Queue.take(probes);
876 }),
877 );
878});