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