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

CodexDriver.test.ts

530 lines20.5 KB

1import { CodexInstallation } from "../CodexInstallation.ts";
2import { ServerSecretStore } from "../../auth/ServerSecretStore.ts";
3import { ServerEnvironmentIdentity } from "../../environment/ServerEnvironment.ts";
4// @effect-diagnostics nodeBuiltinImport:off
5import * as NodeServices from "@effect/platform-node/NodeServices";
6import * as NodeOS from "node:os";
7import * as NodePath from "node:path";
8import { expect, it } from "@effect/vitest";
9import { EnvironmentId, ProviderInstanceId } from "@t3tools/contracts";
10import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
11import * as Effect from "effect/Effect";
12import * as Deferred from "effect/Deferred";
13import * as Fiber from "effect/Fiber";
14import * as FileSystem from "effect/FileSystem";
15import * as Layer from "effect/Layer";
16import * as Option from "effect/Option";
17import * as PlatformError from "effect/PlatformError";
18import * as Schema from "effect/Schema";
19import * as Sink from "effect/Sink";
20import * as Stream from "effect/Stream";
21import { HttpClient, HttpClientResponse } from "effect/unstable/http";
22import * as ChildProcess from "effect/unstable/process/ChildProcess";
23import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
24​
25import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
26import { ServerConfig } from "../../config.ts";
27import { ServerSettingsService } from "../../serverSettings.ts";
28import * as ResetCreditCoordinator from "../Layers/resetCreditCoordinator.ts";
29import { NoOpProviderEventLoggers, ProviderEventLoggers } from "../Layers/ProviderEventLoggers.ts";
30import * as ModelManifest from "../ModelManifest.ts";
31import {
32 createProviderVersionAdvisory,
33 ProviderVersionCache,
34 resolveLatestProviderVersion,
35} from "../providerMaintenance.ts";
36import { CodexDriver } from "./CodexDriver.ts";
37import * as ProviderCredentialStore from "../ProviderCredentialStore.ts";
38​
39const testLayer = ServerConfig.layerTest(process.cwd(), {
40 prefix: "t3-codex-driver-maintenance-",
41}).pipe(
42 Layer.provideMerge(NodeServices.layer),
43 Layer.provideMerge(
44 Layer.mock(CodexInstallation)({ managedDirectory: "unused-managed-installation" }),
45 ),
46 Layer.provideMerge(Layer.mock(ServerSecretStore)({})),
47 Layer.provideMerge(
48 Layer.succeed(ServerEnvironmentIdentity, {
49 getEnvironmentId: Effect.succeed(EnvironmentId.make("00000000-0000-4000-8000-000000000001")),
50 }),
51 ),
52 Layer.provideMerge(ServerSettingsService.layerTest()),
53 Layer.provideMerge(ModelManifest.layerTest),
54 Layer.provideMerge(ResetCreditCoordinator.layerTest),
55 Layer.provideMerge(
56 Layer.mock(BackgroundPolicy.BackgroundPolicy)({
57 shouldRunScopeWork: () => Effect.succeed(false),
58 }),
59 ),
60 Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
61 Layer.provideMerge(
62 Layer.succeed(
63 HttpClient.HttpClient,
64 HttpClient.make(() => Effect.die("Disabled Codex must not make an HTTP request")),
65 ),
66 ),
67);
68​
69// The `#!/bin/sh` stub below cannot be resolved as an executable on Windows.
70const windowsHost = HostProcessPlatform.defaultValue() === "win32";
71​
72const noSpawn = ChildProcessSpawner.make(() =>
73 Effect.die("Disabled Codex must not spawn a process"),
74);
75const encodeCredentials = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));
76​
77it.layer(testLayer)("CodexDriver", (it) => {
78 it.effect("disconnect refreshes a restored managed account while its auth flow is idle", () =>
79 Effect.gen(function* () {
80 const instanceId = ProviderInstanceId.make("restored-managed-account");
81 const credentials = new Map<string, Uint8Array>();
82 const secrets = ServerSecretStore.of({
83 get: (key) => Effect.sync(() => Option.fromUndefinedOr(credentials.get(key))),
84 set: (key, value) =>
85 Effect.sync(() => {
86 credentials.set(key, value);
87 }),
88 remove: (key) =>
89 Effect.sync(() => {
90 credentials.delete(key);
91 }),
92 create: () => Effect.die("unused"),
93 getOrCreateRandom: () => Effect.die("unused"),
94 });
95 yield* Effect.gen(function* () {
96 const store = yield* ProviderCredentialStore.make("codex-chatgpt", instanceId);
97 const json = yield* encodeCredentials({
98 clientId: "oaiapp_test",
99 accessToken: "dummy-owned-access",
100 refreshToken: "dummy-refresh",
101 expiresAt: Number.MAX_SAFE_INTEGER,
102 earliestRefreshAt: null,
103 scopes: ["chatgpt.tokens.use.direct"],
104 subject: "test-user",
105 email: "account@example.test",
106 });
107 yield* store.set(new TextEncoder().encode(json));
108 const executable = {
109 executablePath: "/user/bin/codex",
110 managedVersionDirectory: null,
111 source: "local" as const,
112 version: "0.156.1",
113 };
114 const installation = yield* CodexInstallation;
115 const serverConfig = yield* ServerConfig;
116 const sharedHome = NodePath.join(serverConfig.stateDir, "shared-codex-home");
117 const instance = yield* CodexDriver.create({
118 instanceId,
119 displayName: "Restored account",
120 enabled: true,
121 environment: [],
122 config: { ...CodexDriver.defaultConfig(), setupMode: "managed", homePath: sharedHome },
123 }).pipe(
124 Effect.provideService(
125 CodexInstallation,
126 CodexInstallation.of({
127 ...installation,
128 managedDirectory: "unused-managed-installation",
129 resolve: () => Effect.succeed(executable),
130 acquire: () => Effect.succeed(executable),
131 }),
132 ),
133 Effect.provideService(
134 ChildProcessSpawner.ChildProcessSpawner,
135 ChildProcessSpawner.make(() =>
136 Effect.fail(
137 PlatformError.badArgument({
138 module: "ChildProcessSpawner",
139 method: "spawn",
140 description: "The fixture app-server is unavailable",
141 }),
142 ),
143 ),
144 ),
145 );
146 const observedAccount = yield* Deferred.make<void>();
147 const disconnected = yield* instance.snapshot.streamChanges.pipe(
148 Stream.tap((provider) =>
149 provider.auth.status === "authenticated"
150 ? Deferred.succeed(observedAccount, undefined).pipe(Effect.asVoid)
151 : Effect.void,
152 ),
153 Stream.filter((provider) => provider.auth.status === "unauthenticated"),
154 Stream.runHead,
155 Effect.forkScoped,
156 );
157 const restored = yield* instance.snapshot.refresh;
158 expect(restored.auth.email).toBe("account@example.test");
159 expect(restored.runtimePaths?.homePath).toBe(sharedHome);
160 expect(restored.runtimePaths?.shadowHomePath).toContain(
161 `providers/codex/${instanceId}/shadow`,
162 );
163 yield* Deferred.await(observedAccount);
164 const before = yield* instance.auth!.subscribe("test-owner").pipe(Stream.runHead);
165 expect(Option.getOrThrow(before).phase).toBe("idle");
166 yield* instance.auth!.logout(Effect.void);
167 const after = Option.getOrThrow(yield* Fiber.join(disconnected));
168 expect(after.auth.status).toBe("unauthenticated");
169 expect(after.auth.email).toBeUndefined();
170 expect(after.installed).toBe(true);
171 expect(after.models).toEqual([]);
172 expect(Option.isNone(yield* store.get)).toBe(true);
173 }).pipe(
174 Effect.provideService(ServerSecretStore, secrets),
175 Effect.provideService(
176 HttpClient.HttpClient,
177 HttpClient.make((request) =>
178 Effect.sync(() => {
179 expect([
180 "https://auth.openai.com/.well-known/openid-configuration",
181 "https://auth.openai.com/revoke",
182 "https://api.openai.com/v1/models",
183 ]).toContain(request.url);
184 if (request.url.endsWith("/models"))
185 return HttpClientResponse.fromWeb(request, Response.json({ models: [] }));
186 return HttpClientResponse.fromWeb(
187 request,
188 request.url.endsWith("/revoke")
189 ? new Response(null, { status: 200 })
190 : Response.json({
191 issuer: "https://auth.openai.com",
192 authorization_endpoint: "https://auth.openai.com/api/accounts/authorize",
193 token_endpoint: "https://auth.openai.com/api/accounts/oauth/token",
194 jwks_uri: "https://auth.openai.com/jwks",
195 revocation_endpoint: "https://auth.openai.com/revoke",
196 }),
197 );
198 }),
199 ),
200 ),
201 );
202 }).pipe(Effect.scoped),
203 );
204​
205 it.effect.skipIf(windowsHost)(
206 "runs the standalone updater against the shared home, not the shadow home",
207 () =>
208 Effect.gen(function* () {
209 const fs = yield* FileSystem.FileSystem;
210 const tempDir = yield* fs
211 .makeTempDirectoryScoped({ prefix: "t3-codex-driver-" })
212 .pipe(Effect.flatMap((directory) => fs.realPath(directory)));
213 const sharedHome = NodePath.join(tempDir, "codex-home");
214 const shadowHome = NodePath.join(tempDir, "codex-shadow");
215 const binaryPath = NodePath.join(sharedHome, "packages", "standalone", "bin", "codex");
216 yield* fs.makeDirectory(NodePath.dirname(binaryPath), { recursive: true });
217 yield* fs.writeFileString(binaryPath, "#!/bin/sh\n");
218 yield* fs.chmod(binaryPath, 0o755);
219​
220 const instance = yield* CodexDriver.create({
221 instanceId: ProviderInstanceId.make("codex-shadow"),
222 displayName: "Codex test",
223 enabled: false,
224 environment: [],
225 config: {
226 ...CodexDriver.defaultConfig(),
227 binaryPath,
228 homePath: sharedHome,
229 shadowHomePath: shadowHome,
230 },
231 });
232​
233 const capabilities = yield* instance.snapshot.resolveMaintenance();
234 expect(capabilities.update).toMatchObject({
235 executable: binaryPath,
236 args: ["update"],
237 lockKey: "codex-native",
238 env: { CODEX_HOME: sharedHome },
239 });
240 }).pipe(
241 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn),
242 Effect.scoped,
243 ),
244 );
245​
246 it.effect("stays manual-only when the configured executable does not exist", () =>
247 Effect.gen(function* () {
248 const instance = yield* CodexDriver.create({
249 instanceId: ProviderInstanceId.make("codex-missing"),
250 displayName: "Codex test",
251 enabled: false,
252 environment: [],
253 config: {
254 ...CodexDriver.defaultConfig(),
255 binaryPath: NodePath.join(NodeOS.tmpdir(), "t3-codex-missing", "codex"),
256 },
257 });
258 expect((yield* instance.snapshot.resolveMaintenance()).update).toBeNull();
259 }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn), Effect.scoped),
260 );
261​
262 for (const fixture of [
263 {
264 name: "leaves mise npm-backend installations manual-only",
265 installSegments: ["mise", "installs", "npm-openai-codex", "0.110.0"],
266 npmOwned: false,
267 },
268 {
269 name: "leaves mise tool aliases backed by npm manual-only",
270 installSegments: ["mise", "installs", "codex", "0.110.0"],
271 npmOwned: false,
272 },
273 {
274 name: "keeps npm updates for globals in a mise Node installation",
275 installSegments: ["mise", "installs", "node", "24.0.0"],
276 npmOwned: true,
277 },
278 {
279 name: "keeps npm updates for ordinary global installations",
280 installSegments: ["npm-global"],
281 npmOwned: true,
282 },
283 ] as const) {
284 it.effect.skipIf(windowsHost)(fixture.name, () =>
285 Effect.gen(function* () {
286 const fs = yield* FileSystem.FileSystem;
287 const tempDir = yield* fs
288 .makeTempDirectoryScoped({ prefix: "t3-codex-installer-" })
289 .pipe(Effect.flatMap((directory) => fs.realPath(directory)));
290 const installPath = NodePath.join(tempDir, ...fixture.installSegments);
291 const realBinaryPath = NodePath.join(
292 installPath,
293 "lib",
294 "node_modules",
295 "@openai",
296 "codex",
297 "bin",
298 "codex.js",
299 );
300 const binaryPath = NodePath.join(tempDir, "bin", "codex");
301 yield* fs.makeDirectory(NodePath.dirname(realBinaryPath), { recursive: true });
302 yield* fs.makeDirectory(NodePath.dirname(binaryPath), { recursive: true });
303 yield* fs.writeFileString(realBinaryPath, "#!/bin/sh\n");
304 yield* fs.chmod(realBinaryPath, 0o755);
305 yield* fs.symlink(realBinaryPath, binaryPath);
306​
307 const instance = yield* CodexDriver.create({
308 instanceId: ProviderInstanceId.make("codex-installer"),
309 displayName: "Codex installer test",
310 enabled: false,
311 environment: [],
312 config: {
313 ...CodexDriver.defaultConfig(),
314 binaryPath,
315 homePath: NodePath.join(tempDir, "codex-home"),
316 },
317 });
318​
319 const update = (yield* instance.snapshot.resolveMaintenance()).update;
320 if (fixture.npmOwned) {
321 expect(update).toMatchObject({
322 executable: "npm",
323 args: [
324 "install",
325 "-g",
326 "--prefix",
327 installPath,
328 "--allow-scripts=@openai/codex",
329 "@openai/codex@latest",
330 ],
331 });
332 } else {
333 expect(update).toBeNull();
334 }
335 }).pipe(
336 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn),
337 Effect.scoped,
338 ),
339 );
340 }
341​
342 for (const layout of ["direct", "wrapper"] as const) {
343 it.effect.skipIf(windowsHost)(`leaves a mise ${layout} installation manual-only`, () =>
344 Effect.gen(function* () {
345 const fs = yield* FileSystem.FileSystem;
346 const tempDir = yield* fs
347 .makeTempDirectoryScoped({ prefix: `t3-codex-mise-${layout}-` })
348 .pipe(Effect.flatMap((directory) => fs.realPath(directory)));
349 const binaryPath =
350 layout === "direct"
351 ? NodePath.join(tempDir, "mise", "installs", "codex", "0.110.0", "codex")
352 : NodePath.join(tempDir, "omarchy", "bin", "codex");
353 yield* fs.makeDirectory(NodePath.dirname(binaryPath), { recursive: true });
354 yield* fs.writeFileString(
355 binaryPath,
356 layout === "direct"
357 ? "#!/bin/sh\n"
358 : '#!/bin/sh\nmise use -g --quiet "codex" || exit 1\nexec mise x "codex" -- "codex" "$@"\n',
359 );
360 yield* fs.chmod(binaryPath, 0o755);
361​
362 const instance = yield* CodexDriver.create({
363 instanceId: ProviderInstanceId.make(`codex-mise-${layout}`),
364 displayName: "Codex mise test",
365 enabled: false,
366 environment: [],
367 config: {
368 ...CodexDriver.defaultConfig(),
369 binaryPath,
370 homePath: NodePath.join(tempDir, "codex-home"),
371 },
372 });
373​
374 expect((yield* instance.snapshot.resolveMaintenance()).update).toBeNull();
375 }).pipe(
376 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn),
377 Effect.scoped,
378 ),
379 );
380 }
381​
382 it.effect.each([
383 {
384 name: "conventional shim",
385 dataRoot: "mise",
386 commandName: "codex",
387 version: "0.153.4",
388 nodeFirst: false,
389 },
390 {
391 name: "custom data directory",
392 dataRoot: "custom-tool-data",
393 commandName: "codex",
394 version: "0.153.4",
395 nodeFirst: false,
396 },
397 {
398 name: "renamed configured command",
399 dataRoot: "mise",
400 commandName: "custom-codex",
401 version: "0.153.4",
402 nodeFirst: false,
403 },
404 {
405 name: "outdated provider",
406 dataRoot: "mise",
407 commandName: "codex",
408 version: "0.153.3",
409 nodeFirst: false,
410 },
411 {
412 name: "npm before shim",
413 dataRoot: "mise",
414 commandName: "codex",
415 version: "0.153.4",
416 nodeFirst: true,
417 },
418 ])(
419 "does not mistake Homebrew mise for Codex's installer: $name",
420 (fixture) =>
421 Effect.gen(function* () {
422 const fs = yield* FileSystem.FileSystem;
423 const tempDir = yield* fs
424 .makeTempDirectoryScoped({ prefix: "t3-codex-mise-shim-" })
425 .pipe(Effect.flatMap((directory) => fs.realPath(directory)));
426 const brewPrefix = NodePath.join(tempDir, "homebrew");
427 const brewPath = NodePath.join(brewPrefix, "bin", "brew");
428 const misePath = NodePath.join(brewPrefix, "Cellar", "mise", "2026.9.1", "bin", "mise");
429 const shimDir = NodePath.join(tempDir, fixture.dataRoot, "shims");
430 const npmPrefix = NodePath.join(tempDir, "mise", "installs", "node", "24.13.0");
431 const npmBin = NodePath.join(npmPrefix, "bin");
432 const npmEntry = NodePath.join(
433 npmPrefix,
434 "lib",
435 "node_modules",
436 "@openai",
437 "codex",
438 "bin",
439 "codex.js",
440 );
441 for (const file of [brewPath, misePath, npmEntry]) {
442 yield* fs.makeDirectory(NodePath.dirname(file), { recursive: true });
443 yield* fs.writeFileString(file, "#!/bin/sh\n");
444 yield* fs.chmod(file, 0o755);
445 }
446 yield* fs.makeDirectory(shimDir, { recursive: true });
447 yield* fs.makeDirectory(npmBin, { recursive: true });
448 yield* fs.symlink(misePath, NodePath.join(shimDir, fixture.commandName));
449 yield* fs.symlink(npmEntry, NodePath.join(npmBin, fixture.commandName));
450 const lookupPath = [
451 ...(fixture.nodeFirst ? [npmBin, shimDir] : [shimDir, npmBin]),
452 NodePath.dirname(brewPath),
453 ].join(NodePath.delimiter);
454 const probes: Array<ReadonlyArray<string>> = [];
455 const metadataSpawner = ChildProcessSpawner.make((command) => {
456 if (!ChildProcess.isStandardCommand(command) || command.command !== brewPath) {
457 return Effect.die("Provider resolution must not execute a provider or updater");
458 }
459 probes.push(command.args);
460 const stdout =
461 command.args[0] === "--prefix"
462 ? brewPrefix
463 : JSON.stringify({ formulae: [{ versions: { stable: "2026.9.1" } }] });
464 return Effect.succeed(
465 ChildProcessSpawner.makeHandle({
466 pid: ChildProcessSpawner.ProcessId(1),
467 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)),
468 isRunning: Effect.succeed(false),
469 kill: () => Effect.void,
470 unref: Effect.succeed(Effect.void),
471 stdin: Sink.drain,
472 stdout: Stream.encodeText(Stream.make(stdout)),
473 stderr: Stream.empty,
474 all: Stream.empty,
475 getInputFd: () => Sink.drain,
476 getOutputFd: () => Stream.empty,
477 }),
478 );
479 });
480 const instance = yield* CodexDriver.create({
481 instanceId: ProviderInstanceId.make("codex-mise-shim"),
482 displayName: "Codex shim test",
483 enabled: false,
484 environment: [{ name: "PATH", value: lookupPath, sensitive: false }],
485 config: {
486 ...CodexDriver.defaultConfig(),
487 binaryPath: fixture.commandName,
488 homePath: NodePath.join(tempDir, "codex-home"),
489 },
490 }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, metadataSpawner));
491 const capabilities = yield* instance.snapshot.resolveMaintenance();
492 const latestVersion = yield* resolveLatestProviderVersion(capabilities).pipe(
493 Effect.provideService(
494 ProviderVersionCache,
495 new Map([
496 ["@openai/codex", { expiresAt: Number.MAX_SAFE_INTEGER, version: "0.153.4" }],
497 ]),
498 ),
499 );
500 expect(probes).toEqual([]);
501 expect(latestVersion).toBe("0.153.4");
502 expect(
503 createProviderVersionAdvisory({
504 driver: CodexDriver.driverKind,
505 currentVersion: fixture.version,
506 latestVersion,
507 maintenanceCapabilities: capabilities,
508 }),
509 ).toMatchObject({
510 status: fixture.version === "0.153.4" ? "current" : "behind_latest",
511 currentVersion: fixture.version,
512 latestVersion: "0.153.4",
513 canUpdate: fixture.nodeFirst,
514 });
515 if (fixture.nodeFirst) {
516 expect(capabilities.update).toMatchObject({
517 executable: "npm",
518 args: expect.arrayContaining([
519 "--prefix",
520 yield* fs.realPath(npmPrefix),
521 "@openai/codex@latest",
522 ]),
523 });
524 } else {
525 expect(capabilities.update).toBeNull();
526 }
527 }).pipe(Effect.scoped),
528 { skip: windowsHost },
529 );
530});