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