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

CodexInstallation.test.ts

502 lines20.5 KB

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