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

CodexDriver.test.ts

889 lines37.3 KB

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