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

CodexDriver.test.ts

567 lines22.7 KB

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