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