Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import * as ModelManifest from "./ModelManifest.ts";
3import { expect, it } from "@effect/vitest";
4import * as HostProcess from "@t3tools/shared/HostProcess";
5import * as Crypto from "effect/Crypto";
6import * as Deferred from "effect/Deferred";
7import * as Effect from "effect/Effect";
8import * as Hex from "effect/encoding/Hex";
9import * as FileSystem from "effect/FileSystem";
10import * as Option from "effect/Option";
11import * as PlatformError from "effect/PlatformError";
12import * as Exit from "effect/Exit";
13import * as Queue from "effect/Queue";
14import * as Scope from "effect/Scope";
15import * as Stream from "effect/Stream";
16import { HttpClient, HttpClientResponse } from "effect/http";
17import { ChildProcess, ChildProcessSpawner } from "effect/process";
18import * as CodexInstallation from "./CodexInstallation.ts";
19
20const archive = Buffer.from(
21 "H4sIAAAAAAAC/+3W0W6DIBQGYB/FcD0sKNSkD7J7aom6tmAQtzXL3n3QZM3qdWVt+n8XoCckJp78wLY3q8bu9Ge2HBbUUp7nYD4H8s9zrNdSsCxnWQLT6JULn8ye09K9h/u2/c0/jSM9xqGzo0+bf3Gdf15WQiD/Kdy61/CA+z8dlO9Wrv2387+c5Z9VZY38p7BY0+Gh8t/sVauLt9Ga9Pnnop7ln1e4/6fxRQ7qZCf/qt3YW0M2OX/JyfvljbCCy3XBSaiGH9VqH4tKuaZbC6qG4aDpTrmP3sQV2nh3Gmxvzqsud0vyjaABAAAAAAAAAAAAAAAk8gOq19rvACgAAA==",
22 "base64",
23);
24const asset = {
25 version: "0.156.1",
26 target: "aarch64-apple-darwin",
27 url: "https://github.com/openai/codex/releases/download/test/package.tar.gz",
28 archiveBytes: archive.length,
29};
30const makeHarness = Effect.fn("test.makeCodexInstallation")(function* (
31 input: {
32 options?: Partial<CodexInstallation.CodexInstallationOptions>;
33 manifestCurrent?: Effect.Effect<ModelManifest.ModelManifestData>;
34 body?: Stream.Stream<Uint8Array>;
35 baseDir?: string;
36 local?: { version: string; appServerFails?: boolean; versionFails?: boolean };
37 platform?: NodeJS.Platform;
38 spawner?: ChildProcessSpawner.ChildProcessSpawner["Service"];
39 runtimeRenameFailures?: number;
40 } = {},
41) {
42 const fs = yield* FileSystem.FileSystem;
43 const baseDir =
44 input.baseDir ?? (yield* fs.makeTempDirectoryScoped({ prefix: "t3-codex-install-test-" }));
45 const localDirectory = `${baseDir}/local`;
46 const localBinaryPath = `${localDirectory}/codex${input.platform === "win32" ? ".exe" : ""}`;
47 const probeLog = `${baseDir}/local-probes.txt`;
48 if (input.local) {
49 yield* fs.makeDirectory(localDirectory, { recursive: true });
50 yield* fs.writeFileString(
51 localBinaryPath,
52 `#!/bin/sh\nprintf '%s\\n' "$*" >> '${probeLog}'\ncase "$1" in\n--version) ${input.local.versionFails ? "exit 1" : `printf '%s\\n' 'codex-cli ${input.local.version}'`};;\napp-server) exit ${input.local.appServerFails ? "1" : "0"};;\nesac\n`,
53 { mode: 0o755 },
54 );
55 }
56 let downloads = 0;
57 const crypto = yield* Crypto.Crypto;
58 const sha256 = Hex.encode(yield* crypto.digest("SHA-256", archive).pipe(Effect.orDie));
59 let runtimeRenameFailures = input.runtimeRenameFailures ?? 0;
60 const failedRenames = yield* Queue.unbounded<void>();
61 const lockingFs: FileSystem.FileSystem = {
62 ...fs,
63 // Suspended so each retry of the same effect is a fresh attempt, like the real rename.
64 rename: (from, to) =>
65 Effect.suspend(() =>
66 /[/\\]runtime$/u.test(from) && runtimeRenameFailures-- > 0
67 ? Queue.offer(failedRenames, undefined).pipe(
68 Effect.andThen(
69 Effect.fail(
70 PlatformError.systemError({
71 _tag: "PermissionDenied",
72 module: "FileSystem",
73 method: "rename",
74 pathOrDescriptor: from,
75 }),
76 ),
77 ),
78 )
79 : fs.rename(from, to),
80 ),
81 };
82 const spawner = input.spawner ?? (yield* ChildProcessSpawner.ChildProcessSpawner);
83 const installation = yield* CodexInstallation.makeCodexInstallation({
84 baseDir,
85 releaseAsset: { ...asset, sha256 },
86 validate: () => Effect.void,
87 ...input.options,
88 }).pipe(
89 Effect.provideService(ModelManifest.ModelManifest, {
90 current: input.manifestCurrent ?? Effect.succeed(ModelManifest.BUNDLED_MODEL_MANIFEST),
91 refresh: Effect.succeed(ModelManifest.BUNDLED_MODEL_MANIFEST),
92 forceRefresh: Effect.succeed(ModelManifest.BUNDLED_MODEL_MANIFEST),
93 refreshInBackground: Effect.void,
94 }),
95 Effect.provideService(HostProcess.Platform, input.platform ?? "darwin"),
96 Effect.provideService(HostProcess.Architecture, "arm64"),
97 Effect.provideService(HostProcess.Environment, {
98 PATH: input.local ? localDirectory : "",
99 SystemRoot: "C:\\Windows",
100 }),
101 Effect.provideService(FileSystem.FileSystem, lockingFs),
102 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
103 Effect.provideService(
104 HttpClient.HttpClient,
105 HttpClient.make((request) =>
106 Effect.sync(() => {
107 downloads++;
108 return Object.defineProperty(
109 HttpClientResponse.fromWeb(request, new Response(null)),
110 "stream",
111 {
112 value: input.body ?? Stream.succeed(archive),
113 },
114 );
115 }),
116 ),
117 ),
118 );
119 return {
120 installation,
121 fs,
122 baseDir,
123 localBinaryPath,
124 probeLog,
125 failedRenames,
126 downloads: () => downloads,
127 };
128});
129const terminalState = (installation: CodexInstallation.CodexInstallation["Service"]) =>
130 installation.changes.pipe(
131 Stream.filter((state) => ["succeeded", "failed", "cancelled"].includes(state.phase)),
132 Stream.runHead,
133 Effect.map(Option.getOrThrow),
134 );
135
136it.effect.each(["0.156.0", "0.156.1", "0.156.2", "0.157.0"])(
137 "reuses installed Codex %s without downloading or taking ownership of it",
138 (version) =>
139 Effect.gen(function* () {
140 const h = yield* makeHarness({ local: { version } });
141 expect(yield* h.installation.start).toMatchObject({
142 source: "local",
143 phase: "succeeded",
144 installedVersion: version,
145 executablePath: h.localBinaryPath,
146 canRemove: false,
147 });
148 expect(yield* h.installation.resolve()).toMatchObject({
149 source: "local",
150 executablePath: h.localBinaryPath,
151 managedVersionDirectory: null,
152 version,
153 });
154 yield* h.installation.acquire().pipe(Effect.scoped);
155 expect(h.downloads()).toBe(0);
156 expect(yield* h.fs.exists(h.installation.managedDirectory)).toBe(false);
157 expect((yield* h.fs.readFileString(h.probeLog)).trim().split("\n")).toEqual([
158 "--version",
159 "app-server --help",
160 ]);
161 yield* h.installation.remove();
162 expect(yield* h.fs.exists(h.localBinaryPath)).toBe(true);
163 expect((yield* h.installation.state).source).toBe("local");
164 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
165);
166it.effect.each([
167 { version: "0.128.9" },
168 { version: "0.145.0" },
169 { version: "0.155.1" },
170 { version: "0.155.9" },
171 { version: "0.156.1-alpha.1" },
172 { version: "unknown" },
173 { version: "0.156.1", appServerFails: true },
174 { version: "0.156.1", versionFails: true },
175])("downloads the pinned release when the local CLI is unsupported or broken: %j", (local) =>
176 Effect.gen(function* () {
177 const h = yield* makeHarness({ local });
178 expect((yield* h.installation.state).installedVersion).toBeNull();
179 yield* h.installation.start;
180 const installed = yield* terminalState(h.installation);
181 expect(installed.phase).toBe("succeeded");
182 const executable = yield* h.installation.resolve();
183 expect(executable.source).toBe("managed");
184 expect(installed.executablePath).toBe(executable.executablePath);
185 expect(h.downloads()).toBe(1);
186 expect(yield* h.fs.exists(h.localBinaryPath)).toBe(true);
187 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
188);
189
190const compileNative = Effect.fn("test.compileNative")(function* (
191 executablePath: string,
192 source: string,
193) {
194 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
195 const compiler = yield* spawner.spawn(
196 ChildProcess.make("cc", ["-x", "c", "-", "-o", executablePath], {
197 stdin: Stream.make(new TextEncoder().encode(source)),
198 stdout: "inherit",
199 stderr: "inherit",
200 }),
201 );
202 expect(yield* compiler.exitCode).toBe(0);
203}, Effect.scoped);
204
205it.effect("rechecks compatibility after the local executable is replaced", () =>
206 Effect.gen(function* () {
207 const h = yield* makeHarness({ local: { version: "0.156.1" } });
208 expect((yield* h.installation.resolve()).source).toBe("local");
209 yield* h.fs.remove(h.localBinaryPath);
210 yield* h.fs.writeFileString(h.localBinaryPath, "#!/bin/sh\nprintf 'codex-cli 0.128.9\\n'\n", {
211 mode: 0o755,
212 });
213 yield* h.installation.start;
214 expect((yield* terminalState(h.installation)).phase).toBe("succeeded");
215 expect((yield* h.installation.resolve()).source).toBe("managed");
216 expect(h.downloads()).toBe(1);
217 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
218);
219
220it.effect("rechecks a cached local executable when the shared manifest policy changes", () =>
221 Effect.gen(function* () {
222 let manifest = ModelManifest.BUNDLED_MODEL_MANIFEST;
223 const h = yield* makeHarness({
224 local: { version: "0.156.0" },
225 manifestCurrent: Effect.sync(() => manifest),
226 });
227 expect((yield* h.installation.resolve()).source).toBe("local");
228 manifest = {
229 ...manifest,
230 compatibility: [
231 {
232 driver: "codex",
233 t3CodeRange: ">=0.0.42",
234 ranges: [
235 { range: ">=0.156.1", status: "supported" },
236 { range: "<0.156.1", status: "broken" },
237 ],
238 },
239 ],
240 };
241 yield* h.installation.start;
242 expect((yield* terminalState(h.installation)).phase).toBe("succeeded");
243 expect((yield* h.installation.resolve()).source).toBe("managed");
244 expect(h.downloads()).toBe(1);
245 expect((yield* h.fs.readFileString(h.probeLog)).trim().split("\n")).toEqual([
246 "--version",
247 "app-server --help",
248 ]);
249 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
250);
251
252it.effect("uses bundled Codex compatibility when the remote manifest omits its policy", () =>
253 Effect.gen(function* () {
254 const h = yield* makeHarness({
255 local: { version: "0.156.0" },
256 manifestCurrent: Effect.succeed({
257 ...ModelManifest.BUNDLED_MODEL_MANIFEST,
258 compatibility: [],
259 }),
260 });
261 expect((yield* h.installation.start).source).toBe("local");
262 expect(h.downloads()).toBe(0);
263 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
264);
265
266it.effect.each([
267 { kind: "script", name: "volta-shim" },
268 { kind: "native", name: "volta-shim" },
269 { kind: "native", name: "mise" },
270 { kind: "native", name: "aqua-proxy" },
271])("preserves the invoked name of $kind $name launcher symlinks", ({ kind, name }) =>
272 Effect.gen(function* () {
273 const h = yield* makeHarness({ local: { version: "0.156.1" } });
274 const launcher = `${h.baseDir}/${name}`;
275 if (kind === "native") {
276 const payload = `${h.baseDir}/codex.js`;
277 yield* h.fs.rename(h.localBinaryPath, payload);
278 yield* compileNative(
279 launcher,
280 `#include <string.h>
281#include <unistd.h>
282int main(int argc, char **argv) {
283 const char *name = strrchr(argv[0], '/');
284 if (strcmp(name ? name + 1 : argv[0], "codex") != 0) return 1;
285 execv(${JSON.stringify(payload)}, argv);
286 return 1;
287}
288`,
289 );
290 } else {
291 yield* h.fs.writeFileString(
292 launcher,
293 '#!/bin/sh\ncase "$0" in */codex) ;; *) exit 1;; esac\ncase "$1" in --version) printf "codex-cli 0.156.1\\n";; app-server) exit 0;; esac\n',
294 { mode: 0o755 },
295 );
296 yield* h.fs.remove(h.localBinaryPath);
297 }
298 yield* h.fs.symlink(launcher, h.localBinaryPath);
299 expect(yield* h.installation.start).toMatchObject({ source: "local", phase: "succeeded" });
300 expect((yield* h.installation.resolve()).executablePath).toBe(h.localBinaryPath);
301 expect(h.downloads()).toBe(0);
302 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
303);
304
305it.effect(
306 "installs the complete verified package in tools/codex/version and survives a restart",
307 () =>
308 Effect.gen(function* () {
309 const { installation, fs, baseDir } = yield* makeHarness();
310 yield* installation.start;
311 expect((yield* terminalState(installation)).phase).toBe("succeeded");
312 const executable = yield* installation.resolve();
313 expect(executable.executablePath).toBe(`${baseDir}/tools/codex/0.156.1/bin/codex`);
314 expect(
315 yield* fs.readFileString(`${executable.managedVersionDirectory}/bin/codex-code-mode-host`),
316 ).toBe("host");
317 expect(yield* fs.readFileString(`${executable.managedVersionDirectory}/codex-path/rg`)).toBe(
318 "rg",
319 );
320 const restarted = yield* makeHarness({ baseDir });
321 expect((yield* restarted.installation.resolve()).version).toBe("0.156.1");
322 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
323);
324
325it.effect("requires an update before running an older activated managed installation", () =>
326 Effect.gen(function* () {
327 const first = yield* makeHarness();
328 yield* first.installation.start;
329 yield* terminalState(first.installation);
330 const executable = yield* first.installation.resolve();
331 const oldDirectory = `${first.installation.managedDirectory}/0.155.1`;
332 yield* first.fs.rename(executable.managedVersionDirectory!, oldDirectory);
333 for (const name of ["codex-package.json", ".install-complete.json"]) {
334 const file = `${oldDirectory}/${name}`;
335 yield* first.fs.writeFileString(
336 file,
337 (yield* first.fs.readFileString(file)).replaceAll("0.156.1", "0.155.1"),
338 );
339 }
340 yield* first.fs.writeFileString(
341 `${first.installation.managedDirectory}/active.json`,
342 '{"version":"0.155.1"}',
343 );
344 const restarted = yield* makeHarness({ baseDir: first.baseDir });
345 expect((yield* Effect.flip(restarted.installation.resolve())).detail).toContain(
346 "outside the supported range",
347 );
348 yield* restarted.installation.start;
349 expect((yield* terminalState(restarted.installation)).phase).toBe("succeeded");
350 expect((yield* restarted.installation.resolve()).version).toBe("0.156.1");
351 expect(restarted.downloads()).toBe(1);
352 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
353);
354
355it.effect("rejects corrupted downloads without publishing a runtime", () =>
356 Effect.gen(function* () {
357 const { installation, fs } = yield* makeHarness({
358 options: { releaseAsset: { ...asset, sha256: "0".repeat(64) } },
359 });
360 yield* installation.start;
361 const state = yield* terminalState(installation);
362 expect(state.phase).toBe("failed");
363 expect(state.message).toContain("SHA-256");
364 expect(yield* fs.exists(`${installation.managedDirectory}/active.json`)).toBe(false);
365 expect(yield* fs.exists(`${installation.managedDirectory}/0.156.1`)).toBe(false);
366 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
367);
368
369it.effect("cancels an in-flight download and cleans the staging directory", () =>
370 Effect.gen(function* () {
371 const downloading = yield* Deferred.make<void>();
372 const body = Stream.fromEffect(
373 Deferred.succeed(downloading, undefined).pipe(Effect.andThen(Effect.never)),
374 );
375 const { installation, fs } = yield* makeHarness({ body });
376 const started = yield* installation.start;
377 yield* Deferred.await(downloading);
378 expect((yield* installation.cancel(started.operationId!)).phase).toBe("cancelled");
379 expect(
380 (yield* fs.readDirectory(installation.managedDirectory)).filter((name) =>
381 name.startsWith(".install-"),
382 ),
383 ).toEqual([]);
384 expect(yield* fs.exists(`${installation.managedDirectory}/active.json`)).toBe(false);
385 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
386);
387
388it.effect("protects active process leases and removes the runtime after release", () =>
389 Effect.gen(function* () {
390 const { installation, fs } = yield* makeHarness();
391 yield* installation.start;
392 yield* terminalState(installation);
393 const leaseScope = yield* Scope.make();
394 yield* installation.acquire().pipe(Effect.provideService(Scope.Scope, leaseScope));
395 expect((yield* Effect.flip(installation.remove())).detail).toContain("Stop Codex sessions");
396 yield* Scope.close(leaseScope, Exit.void);
397 yield* installation.remove();
398 expect(yield* fs.exists(installation.managedDirectory)).toBe(false);
399 expect((yield* installation.state).installedVersion).toBeNull();
400 expect((yield* installation.state).executablePath).toBeNull();
401 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
402);
403
404it.effect("keeps an activated runtime when a later update fails verification", () =>
405 Effect.gen(function* () {
406 const first = yield* makeHarness();
407 yield* first.installation.start;
408 yield* terminalState(first.installation);
409 const update = yield* makeHarness({
410 baseDir: first.baseDir,
411 options: { releaseAsset: { ...asset, version: "0.156.2", sha256: "0".repeat(64) } },
412 });
413 expect((yield* update.installation.state).executablePath).toBe(
414 (yield* first.installation.resolve()).executablePath,
415 );
416 yield* update.installation.start;
417 expect((yield* terminalState(update.installation)).phase).toBe("failed");
418 expect((yield* update.installation.resolve()).version).toBe("0.156.1");
419 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
420);
421
422// Stands in for Windows' bsdtar: CRLF listings, and extraction writes the Windows layout.