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

CodexDriver.test.ts

372 lines13.8 KB

1// @effect-diagnostics nodeBuiltinImport:off
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import * as NodeOS from "node:os";
4import * as NodePath from "node:path";
5import { expect, it } from "@effect/vitest";
6import { ProviderInstanceId } from "@t3tools/contracts";
7import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
8import * as Effect from "effect/Effect";
9import * as FileSystem from "effect/FileSystem";
10import * as Layer from "effect/Layer";
11import * as Sink from "effect/Sink";
12import * as Stream from "effect/Stream";
13import { HttpClient } from "effect/unstable/http";
14import * as ChildProcess from "effect/unstable/process/ChildProcess";
15import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
16​
17import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
18import { ServerConfig } from "../../config.ts";
19import { ServerSettingsService } from "../../serverSettings.ts";
20import { layerTest as codexResetCreditLayerTest } from "../Layers/codexResetCredit.ts";
21import { NoOpProviderEventLoggers, ProviderEventLoggers } from "../Layers/ProviderEventLoggers.ts";
22import * as ModelManifest from "../ModelManifest.ts";
23import {
24 createProviderVersionAdvisory,
25 ProviderVersionCache,
26 resolveLatestProviderVersion,
27} from "../providerMaintenance.ts";
28import { CodexDriver } from "./CodexDriver.ts";
29​
30const testLayer = ServerConfig.layerTest(process.cwd(), {
31 prefix: "t3-codex-driver-maintenance-",
32}).pipe(
33 Layer.provideMerge(NodeServices.layer),
34 Layer.provideMerge(ServerSettingsService.layerTest()),
35 Layer.provideMerge(ModelManifest.layerTest),
36 Layer.provideMerge(codexResetCreditLayerTest),
37 Layer.provideMerge(
38 Layer.mock(BackgroundPolicy.BackgroundPolicy)({
39 shouldRunScopeWork: () => Effect.succeed(false),
40 }),
41 ),
42 Layer.provideMerge(Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers)),
43 Layer.provideMerge(
44 Layer.succeed(
45 HttpClient.HttpClient,
46 HttpClient.make(() => Effect.die("Disabled Codex must not make an HTTP request")),
47 ),
48 ),
49);
50​
51// The `#!/bin/sh` stub below cannot be resolved as an executable on Windows.
52const windowsHost = HostProcessPlatform.defaultValue() === "win32";
53​
54const noSpawn = ChildProcessSpawner.make(() =>
55 Effect.die("Disabled Codex must not spawn a process"),
56);
57​
58it.layer(testLayer)("CodexDriver", (it) => {
59 it.effect.skipIf(windowsHost)(
60 "runs the standalone updater against the shared home, not the shadow home",
61 () =>
62 Effect.gen(function* () {
63 const fs = yield* FileSystem.FileSystem;
64 const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-codex-driver-" });
65 const sharedHome = NodePath.join(tempDir, "codex-home");
66 const shadowHome = NodePath.join(tempDir, "codex-shadow");
67 const binaryPath = NodePath.join(sharedHome, "packages", "standalone", "bin", "codex");
68 yield* fs.makeDirectory(NodePath.dirname(binaryPath), { recursive: true });
69 yield* fs.writeFileString(binaryPath, "#!/bin/sh\n");
70 yield* fs.chmod(binaryPath, 0o755);
71​
72 const instance = yield* CodexDriver.create({
73 instanceId: ProviderInstanceId.make("codex-shadow"),
74 displayName: "Codex test",
75 enabled: false,
76 environment: [],
77 config: {
78 ...CodexDriver.defaultConfig(),
79 binaryPath,
80 homePath: sharedHome,
81 shadowHomePath: shadowHome,
82 },
83 });
84​
85 const capabilities = yield* instance.snapshot.resolveMaintenance();
86 expect(capabilities.update).toMatchObject({
87 executable: binaryPath,
88 args: ["update"],
89 lockKey: "codex-native",
90 env: { CODEX_HOME: sharedHome },
91 });
92 }).pipe(
93 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn),
94 Effect.scoped,
95 ),
96 );
97​
98 it.effect("stays manual-only when the configured executable does not exist", () =>
99 Effect.gen(function* () {
100 const instance = yield* CodexDriver.create({
101 instanceId: ProviderInstanceId.make("codex-missing"),
102 displayName: "Codex test",
103 enabled: false,
104 environment: [],
105 config: {
106 ...CodexDriver.defaultConfig(),
107 binaryPath: NodePath.join(NodeOS.tmpdir(), "t3-codex-missing", "codex"),
108 },
109 });
110 expect((yield* instance.snapshot.resolveMaintenance()).update).toBeNull();
111 }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn), Effect.scoped),
112 );
113​
114 for (const fixture of [
115 {
116 name: "leaves mise npm-backend installations manual-only",
117 installSegments: ["mise", "installs", "npm-openai-codex", "0.110.0"],
118 npmOwned: false,
119 },
120 {
121 name: "leaves mise tool aliases backed by npm manual-only",
122 installSegments: ["mise", "installs", "codex", "0.110.0"],
123 npmOwned: false,
124 },
125 {
126 name: "keeps npm updates for globals in a mise Node installation",
127 installSegments: ["mise", "installs", "node", "24.0.0"],
128 npmOwned: true,
129 },
130 {
131 name: "keeps npm updates for ordinary global installations",
132 installSegments: ["npm-global"],
133 npmOwned: true,
134 },
135 ] as const) {
136 it.effect.skipIf(windowsHost)(fixture.name, () =>
137 Effect.gen(function* () {
138 const fs = yield* FileSystem.FileSystem;
139 const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-codex-installer-" });
140 const installPath = NodePath.join(tempDir, ...fixture.installSegments);
141 const realBinaryPath = NodePath.join(
142 installPath,
143 "lib",
144 "node_modules",
145 "@openai",
146 "codex",
147 "bin",
148 "codex.js",
149 );
150 const binaryPath = NodePath.join(tempDir, "bin", "codex");
151 yield* fs.makeDirectory(NodePath.dirname(realBinaryPath), { recursive: true });
152 yield* fs.makeDirectory(NodePath.dirname(binaryPath), { recursive: true });
153 yield* fs.writeFileString(realBinaryPath, "#!/bin/sh\n");
154 yield* fs.chmod(realBinaryPath, 0o755);
155 yield* fs.symlink(realBinaryPath, binaryPath);
156​
157 const instance = yield* CodexDriver.create({
158 instanceId: ProviderInstanceId.make("codex-installer"),
159 displayName: "Codex installer test",
160 enabled: false,
161 environment: [],
162 config: {
163 ...CodexDriver.defaultConfig(),
164 binaryPath,
165 homePath: NodePath.join(tempDir, "codex-home"),
166 },
167 });
168​
169 const update = (yield* instance.snapshot.resolveMaintenance()).update;
170 if (fixture.npmOwned) {
171 expect(update).toMatchObject({
172 executable: "npm",
173 args: [
174 "install",
175 "-g",
176 "--prefix",
177 installPath,
178 "--allow-scripts=@openai/codex",
179 "@openai/codex@latest",
180 ],
181 });
182 } else {
183 expect(update).toBeNull();
184 }
185 }).pipe(
186 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn),
187 Effect.scoped,
188 ),
189 );
190 }
191​
192 for (const layout of ["direct", "wrapper"] as const) {
193 it.effect.skipIf(windowsHost)(`leaves a mise ${layout} installation manual-only`, () =>
194 Effect.gen(function* () {
195 const fs = yield* FileSystem.FileSystem;
196 const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: `t3-codex-mise-${layout}-` });
197 const binaryPath =
198 layout === "direct"
199 ? NodePath.join(tempDir, "mise", "installs", "codex", "0.110.0", "codex")
200 : NodePath.join(tempDir, "omarchy", "bin", "codex");
201 yield* fs.makeDirectory(NodePath.dirname(binaryPath), { recursive: true });
202 yield* fs.writeFileString(
203 binaryPath,
204 layout === "direct"
205 ? "#!/bin/sh\n"
206 : '#!/bin/sh\nmise use -g --quiet "codex" || exit 1\nexec mise x "codex" -- "codex" "$@"\n',
207 );
208 yield* fs.chmod(binaryPath, 0o755);
209​
210 const instance = yield* CodexDriver.create({
211 instanceId: ProviderInstanceId.make(`codex-mise-${layout}`),
212 displayName: "Codex mise test",
213 enabled: false,
214 environment: [],
215 config: {
216 ...CodexDriver.defaultConfig(),
217 binaryPath,
218 homePath: NodePath.join(tempDir, "codex-home"),
219 },
220 });
221​
222 expect((yield* instance.snapshot.resolveMaintenance()).update).toBeNull();
223 }).pipe(
224 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, noSpawn),
225 Effect.scoped,
226 ),
227 );
228 }
229​
230 it.effect.each([
231 {
232 name: "conventional shim",
233 dataRoot: "mise",
234 commandName: "codex",
235 version: "0.153.4",
236 nodeFirst: false,
237 },
238 {
239 name: "custom data directory",
240 dataRoot: "custom-tool-data",
241 commandName: "codex",
242 version: "0.153.4",
243 nodeFirst: false,
244 },
245 {
246 name: "renamed configured command",
247 dataRoot: "mise",
248 commandName: "custom-codex",
249 version: "0.153.4",
250 nodeFirst: false,
251 },
252 {
253 name: "outdated provider",
254 dataRoot: "mise",
255 commandName: "codex",
256 version: "0.153.3",
257 nodeFirst: false,
258 },
259 {
260 name: "npm before shim",
261 dataRoot: "mise",
262 commandName: "codex",
263 version: "0.153.4",
264 nodeFirst: true,
265 },
266 ])(
267 "does not mistake Homebrew mise for Codex's installer: $name",
268 (fixture) =>
269 Effect.gen(function* () {
270 const fs = yield* FileSystem.FileSystem;
271 const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-codex-mise-shim-" });
272 const brewPrefix = NodePath.join(tempDir, "homebrew");
273 const brewPath = NodePath.join(brewPrefix, "bin", "brew");
274 const misePath = NodePath.join(brewPrefix, "Cellar", "mise", "2026.9.1", "bin", "mise");
275 const shimDir = NodePath.join(tempDir, fixture.dataRoot, "shims");
276 const npmPrefix = NodePath.join(tempDir, "mise", "installs", "node", "24.13.0");
277 const npmBin = NodePath.join(npmPrefix, "bin");
278 const npmEntry = NodePath.join(
279 npmPrefix,
280 "lib",
281 "node_modules",
282 "@openai",
283 "codex",
284 "bin",
285 "codex.js",
286 );
287 for (const file of [brewPath, misePath, npmEntry]) {
288 yield* fs.makeDirectory(NodePath.dirname(file), { recursive: true });
289 yield* fs.writeFileString(file, "#!/bin/sh\n");
290 yield* fs.chmod(file, 0o755);
291 }
292 yield* fs.makeDirectory(shimDir, { recursive: true });
293 yield* fs.makeDirectory(npmBin, { recursive: true });
294 yield* fs.symlink(misePath, NodePath.join(shimDir, fixture.commandName));
295 yield* fs.symlink(npmEntry, NodePath.join(npmBin, fixture.commandName));
296 const lookupPath = [
297 ...(fixture.nodeFirst ? [npmBin, shimDir] : [shimDir, npmBin]),
298 NodePath.dirname(brewPath),
299 ].join(NodePath.delimiter);
300 const probes: Array<ReadonlyArray<string>> = [];
301 const metadataSpawner = ChildProcessSpawner.make((command) => {
302 if (!ChildProcess.isStandardCommand(command) || command.command !== brewPath) {
303 return Effect.die("Provider resolution must not execute a provider or updater");
304 }
305 probes.push(command.args);
306 const stdout =
307 command.args[0] === "--prefix"
308 ? brewPrefix
309 : JSON.stringify({ formulae: [{ versions: { stable: "2026.9.1" } }] });
310 return Effect.succeed(
311 ChildProcessSpawner.makeHandle({
312 pid: ChildProcessSpawner.ProcessId(1),
313 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)),
314 isRunning: Effect.succeed(false),
315 kill: () => Effect.void,
316 unref: Effect.succeed(Effect.void),
317 stdin: Sink.drain,
318 stdout: Stream.encodeText(Stream.make(stdout)),
319 stderr: Stream.empty,
320 all: Stream.empty,
321 getInputFd: () => Sink.drain,
322 getOutputFd: () => Stream.empty,
323 }),
324 );
325 });
326 const instance = yield* CodexDriver.create({
327 instanceId: ProviderInstanceId.make("codex-mise-shim"),
328 displayName: "Codex shim test",
329 enabled: false,
330 environment: [{ name: "PATH", value: lookupPath, sensitive: false }],
331 config: {
332 ...CodexDriver.defaultConfig(),
333 binaryPath: fixture.commandName,
334 homePath: NodePath.join(tempDir, "codex-home"),
335 },
336 }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, metadataSpawner));
337 const capabilities = yield* instance.snapshot.resolveMaintenance();
338 const latestVersion = yield* resolveLatestProviderVersion(capabilities).pipe(
339 Effect.provideService(
340 ProviderVersionCache,
341 new Map([
342 ["@openai/codex", { expiresAt: Number.MAX_SAFE_INTEGER, version: "0.153.4" }],
343 ]),
344 ),
345 );
346 expect(probes).toEqual([]);
347 expect(latestVersion).toBe("0.153.4");
348 expect(
349 createProviderVersionAdvisory({
350 driver: CodexDriver.driverKind,
351 currentVersion: fixture.version,
352 latestVersion,
353 maintenanceCapabilities: capabilities,
354 }),
355 ).toMatchObject({
356 status: fixture.version === "0.153.4" ? "current" : "behind_latest",
357 currentVersion: fixture.version,
358 latestVersion: "0.153.4",
359 canUpdate: fixture.nodeFirst,
360 });
361 if (fixture.nodeFirst) {
362 expect(capabilities.update).toMatchObject({
363 executable: "npm",
364 args: expect.arrayContaining(["--prefix", npmPrefix, "@openai/codex@latest"]),
365 });
366 } else {
367 expect(capabilities.update).toBeNull();
368 }
369 }).pipe(Effect.scoped),
370 { skip: windowsHost },
371 );
372});