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