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

CodexInstallation.test.ts

515 lines21.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 Clock from "effect/Clock";
6import * as Crypto from "effect/Crypto";
7import * as Deferred from "effect/Deferred";
8import * as Effect from "effect/Effect";
9import * as Hex from "effect/encoding/Hex";
10import * as FileSystem from "effect/FileSystem";
11import * as Option from "effect/Option";
12import * as Path from "effect/Path";
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 Sink from "effect/Sink";
18import * as Stream from "effect/Stream";
19import { HttpClient, HttpClientResponse } from "effect/http";
20import * as TestClock from "effect/testing/TestClock";
21import { ChildProcessSpawner } from "effect/process";
22import * as CodexInstallation from "./CodexInstallation.ts";
23​
24const archive = Buffer.from(
25 "H4sIAAAAAAAC/+3W0W6DIBQGYB/FcD0sKNSkD7J7aom6tmAQtzXL3n3QZM3qdWVt+n8XoCckJp78wLY3q8bu9Ge2HBbUUp7nYD4H8s9zrNdSsCxnWQLT6JULn8ye09K9h/u2/c0/jSM9xqGzo0+bf3Gdf15WQiD/Kdy61/CA+z8dlO9Wrv2387+c5Z9VZY38p7BY0+Gh8t/sVauLt9Ga9Pnnop7ln1e4/6fxRQ7qZCf/qt3YW0M2OX/JyfvljbCCy3XBSaiGH9VqH4tKuaZbC6qG4aDpTrmP3sQV2nh3Gmxvzqsud0vyjaABAAAAAAAAAAAAAAAk8gOq19rvACgAAA==",
26 "base64",
27);
28const asset = {
29 version: "0.156.1",
30 target: "aarch64-apple-darwin",
31 url: "https://github.com/openai/codex/releases/download/test/package.tar.gz",
32 archiveBytes: archive.length,
33};
34const makeHarness = Effect.fn("test.makeCodexInstallation")(function* (
35 input: {
36 options?: Partial<CodexInstallation.CodexInstallationOptions>;
37 manifestCurrent?: Effect.Effect<ModelManifest.ModelManifestData>;
38 body?: Stream.Stream<Uint8Array>;
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`;
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 crypto = yield* Crypto.Crypto;
62 const sha256 = Hex.encode(yield* crypto.digest("SHA-256", 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(request, new Response(null)),
114 "stream",
115 {
116 value: input.body ?? Stream.succeed(archive),
117 },
118 );
119 }),
120 ),
121 ),
122 );
123 return {
124 installation,
125 fs,
126 baseDir,
127 localBinaryPath,
128 probeLog,
129 failedRenames,
130 downloads: () => downloads,
131 };
132});
133const terminalState = (installation: CodexInstallation.CodexInstallation["Service"]) =>
134 installation.changes.pipe(
135 Stream.filter((state) => ["succeeded", "failed", "cancelled"].includes(state.phase)),
136 Stream.runHead,
137 Effect.map(Option.getOrThrow),
138 );
139​
140it.effect.each(["0.156.0", "0.156.1", "0.156.2", "0.157.0"])(
141 "reuses installed Codex %s without downloading or taking ownership of it",
142 (version) =>
143 Effect.gen(function* () {
144 const h = yield* makeHarness({ local: { version } });
145 expect(yield* h.installation.start).toMatchObject({
146 source: "local",
147 phase: "succeeded",
148 installedVersion: version,
149 executablePath: h.localBinaryPath,
150 canRemove: false,
151 });
152 expect(yield* h.installation.resolve()).toMatchObject({
153 source: "local",
154 executablePath: h.localBinaryPath,
155 managedVersionDirectory: null,
156 version,
157 });
158 yield* h.installation.acquire().pipe(Effect.scoped);
159 expect(h.downloads()).toBe(0);
160 expect(yield* h.fs.exists(h.installation.managedDirectory)).toBe(false);
161 expect((yield* h.fs.readFileString(h.probeLog)).trim().split("\n")).toEqual([
162 "--version",
163 "app-server --help",
164 ]);
165 yield* h.installation.remove();
166 expect(yield* h.fs.exists(h.localBinaryPath)).toBe(true);
167 expect((yield* h.installation.state).source).toBe("local");
168 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
169);
170it.effect.each([
171 { version: "0.128.9" },
172 { version: "0.145.0" },
173 { version: "0.155.1" },
174 { version: "0.155.9" },
175 { version: "0.156.1-alpha.1" },
176 { version: "unknown" },
177 { version: "0.156.1", appServerFails: true },
178 { version: "0.156.1", versionFails: true },
179])("downloads the pinned release when the local CLI is unsupported or broken: %j", (local) =>
180 Effect.gen(function* () {
181 const h = yield* makeHarness({ local });
182 expect((yield* h.installation.state).installedVersion).toBeNull();
183 yield* h.installation.start;
184 const installed = yield* terminalState(h.installation);
185 expect(installed.phase).toBe("succeeded");
186 const executable = yield* h.installation.resolve();
187 expect(executable.source).toBe("managed");
188 expect(installed.executablePath).toBe(executable.executablePath);
189 expect(h.downloads()).toBe(1);
190 expect(yield* h.fs.exists(h.localBinaryPath)).toBe(true);
191 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
192);
193it.effect("falls back to a managed download when the reused local executable disappears", () =>
194 Effect.gen(function* () {
195 const h = yield* makeHarness({ local: { version: "0.156.1" } });
196 expect((yield* h.installation.resolve()).source).toBe("local");
197 yield* h.fs.remove(h.localBinaryPath);
198 yield* h.installation.start;
199 expect((yield* terminalState(h.installation)).phase).toBe("succeeded");
200 expect((yield* h.installation.resolve()).source).toBe("managed");
201 expect(h.downloads()).toBe(1);
202 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
203);
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("preserves the invoked name of version-manager launcher symlinks", () =>
267 Effect.gen(function* () {
268 const h = yield* makeHarness({ local: { version: "0.156.1" } });
269 const launcher = `${h.baseDir}/launcher`;
270 yield* h.fs.writeFileString(
271 launcher,
272 '#!/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',
273 { mode: 0o755 },
274 );
275 yield* h.fs.remove(h.localBinaryPath);
276 yield* h.fs.symlink(launcher, h.localBinaryPath);
277 expect(yield* h.installation.start).toMatchObject({ source: "local", phase: "succeeded" });
278 expect((yield* h.installation.resolve()).executablePath).toBe(h.localBinaryPath);
279 expect(h.downloads()).toBe(0);
280 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
281);
282​
283it.effect(
284 "installs the complete verified package in tools/codex/version and survives a restart",
285 () =>
286 Effect.gen(function* () {
287 const { installation, fs, baseDir } = yield* makeHarness();
288 yield* installation.start;
289 expect((yield* terminalState(installation)).phase).toBe("succeeded");
290 const executable = yield* installation.resolve();
291 expect(executable.executablePath).toBe(`${baseDir}/tools/codex/0.156.1/bin/codex`);
292 expect(
293 yield* fs.readFileString(`${executable.managedVersionDirectory}/bin/codex-code-mode-host`),
294 ).toBe("host");
295 expect(yield* fs.readFileString(`${executable.managedVersionDirectory}/codex-path/rg`)).toBe(
296 "rg",
297 );
298 const restarted = yield* makeHarness({ baseDir });
299 expect((yield* restarted.installation.resolve()).version).toBe("0.156.1");
300 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
301);
302​
303it.effect("requires an update before running an older activated managed installation", () =>
304 Effect.gen(function* () {
305 const first = yield* makeHarness();
306 yield* first.installation.start;
307 yield* terminalState(first.installation);
308 const executable = yield* first.installation.resolve();
309 const oldDirectory = `${first.installation.managedDirectory}/0.155.1`;
310 yield* first.fs.rename(executable.managedVersionDirectory!, oldDirectory);
311 for (const name of ["codex-package.json", ".install-complete.json"]) {
312 const file = `${oldDirectory}/${name}`;
313 yield* first.fs.writeFileString(
314 file,
315 (yield* first.fs.readFileString(file)).replaceAll("0.156.1", "0.155.1"),
316 );
317 }
318 yield* first.fs.writeFileString(
319 `${first.installation.managedDirectory}/active.json`,
320 '{"version":"0.155.1"}',
321 );
322 const restarted = yield* makeHarness({ baseDir: first.baseDir });
323 expect((yield* Effect.flip(restarted.installation.resolve())).detail).toContain(
324 "outside the supported range",
325 );
326 yield* restarted.installation.start;
327 expect((yield* terminalState(restarted.installation)).phase).toBe("succeeded");
328 expect((yield* restarted.installation.resolve()).version).toBe("0.156.1");
329 expect(restarted.downloads()).toBe(1);
330 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
331);
332​
333it.effect("rejects corrupted downloads without publishing a runtime", () =>
334 Effect.gen(function* () {
335 const { installation, fs } = yield* makeHarness({
336 options: { releaseAsset: { ...asset, sha256: "0".repeat(64) } },
337 });
338 yield* installation.start;
339 const state = yield* terminalState(installation);
340 expect(state.phase).toBe("failed");
341 expect(state.message).toContain("SHA-256");
342 expect(yield* fs.exists(`${installation.managedDirectory}/active.json`)).toBe(false);
343 expect(yield* fs.exists(`${installation.managedDirectory}/0.156.1`)).toBe(false);
344 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
345);
346​
347it.effect("cancels an in-flight download and cleans the staging directory", () =>
348 Effect.gen(function* () {
349 const downloading = yield* Deferred.make<void>();
350 const body = Stream.fromEffect(
351 Deferred.succeed(downloading, undefined).pipe(Effect.andThen(Effect.never)),
352 );
353 const { installation, fs } = yield* makeHarness({ body });
354 const started = yield* installation.start;
355 yield* Deferred.await(downloading);
356 expect((yield* installation.cancel(started.operationId!)).phase).toBe("cancelled");
357 expect(
358 (yield* fs.readDirectory(installation.managedDirectory)).filter((name) =>
359 name.startsWith(".install-"),
360 ),
361 ).toEqual([]);
362 expect(yield* fs.exists(`${installation.managedDirectory}/active.json`)).toBe(false);
363 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
364);
365​
366it.effect("protects active process leases and removes the runtime after release", () =>
367 Effect.gen(function* () {
368 const { installation, fs } = yield* makeHarness();
369 yield* installation.start;
370 yield* terminalState(installation);
371 const leaseScope = yield* Scope.make();
372 yield* installation.acquire().pipe(Effect.provideService(Scope.Scope, leaseScope));
373 expect((yield* Effect.flip(installation.remove())).detail).toContain("Stop Codex sessions");
374 yield* Scope.close(leaseScope, Exit.void);
375 yield* installation.remove();
376 expect(yield* fs.exists(installation.managedDirectory)).toBe(false);
377 expect((yield* installation.state).installedVersion).toBeNull();
378 expect((yield* installation.state).executablePath).toBeNull();
379 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
380);
381​
382it.effect("keeps an activated runtime when a later update fails verification", () =>
383 Effect.gen(function* () {
384 const first = yield* makeHarness();
385 yield* first.installation.start;
386 yield* terminalState(first.installation);
387 const update = yield* makeHarness({
388 baseDir: first.baseDir,
389 options: { releaseAsset: { ...asset, version: "0.156.2", sha256: "0".repeat(64) } },
390 });
391 expect((yield* update.installation.state).executablePath).toBe(
392 (yield* first.installation.resolve()).executablePath,
393 );
394 yield* update.installation.start;
395 expect((yield* terminalState(update.installation)).phase).toBe("failed");
396 expect((yield* update.installation.resolve()).version).toBe("0.156.1");
397 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
398);
399​
400it("publishes complete packages for all supported platforms", () => {
401 for (const platform of ["darwin", "linux", "win32"] as const)
402 for (const arch of ["x64", "arm64"])
403 expect(CodexInstallation.resolveCodexReleaseAsset(platform, arch)?.url).toContain(
404 "codex-package-",
405 );
406 expect(CodexInstallation.resolveCodexReleaseAsset("linux", "riscv64")).toBeNull();
407});
408// Live clock: staleness compares real filesystem mtimes.
409it.live("startup removes only stale staging directories", () =>
410 Effect.gen(function* () {
411 const fs = yield* FileSystem.FileSystem;
412 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-codex-install-test-" });
413 const managed = `${baseDir}/tools/codex`;
414 const stale = ((yield* Clock.currentTimeMillis) - 25 * 60 * 60_000) / 1000;
415 for (const name of [".install-stale", ".active-stale", ".install-live"]) {
416 yield* fs.makeDirectory(`${managed}/${name}`, { recursive: true });
417 }
418 yield* fs.utimes(`${managed}/.install-stale`, stale, stale);
419 yield* fs.utimes(`${managed}/.active-stale`, stale, stale);
420 const h = yield* makeHarness({ baseDir });
421 expect(yield* fs.readDirectory(managed)).toEqual([".install-live"]);
422 expect((yield* h.installation.state).canRemove).toBe(true);
423​
424 yield* fs.remove(`${managed}/.install-live`, { recursive: true });
425 yield* fs.makeDirectory(`${managed}/.install-stale`);
426 yield* fs.utimes(`${managed}/.install-stale`, stale, stale);
427 const fresh = yield* makeHarness({ baseDir });
428 expect(yield* fs.readDirectory(managed)).toEqual([]);
429 expect((yield* fresh.installation.state).canRemove).toBe(false);
430 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
431);
432​
433const processHandle = (stdout: string) =>
434 ChildProcessSpawner.makeHandle({
435 pid: ChildProcessSpawner.ProcessId(1),
436 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)),
437 isRunning: Effect.succeed(false),
438 kill: () => Effect.void,
439 unref: Effect.succeed(Effect.void),
440 stdin: Sink.drain,
441 stdout: Stream.make(new TextEncoder().encode(stdout)),
442 stderr: Stream.empty,
443 all: Stream.empty,
444 getInputFd: () => Sink.drain,
445 getOutputFd: () => Stream.empty,
446 });
447const windowsPackage: Record<string, string> = {
448 "bin/codex.exe": "codex",
449 "bin/codex-code-mode-host.exe": "host",
450 "codex-path/rg.exe": "rg",
451 "codex-package.json": JSON.stringify({
452 layoutVersion: 1,
453 version: asset.version,
454 target: asset.target,
455 entrypoint: "bin/codex.exe",
456 }),
457};
458// Stands in for Windows' bsdtar: CRLF listings, and extraction writes the Windows layout.
459const makeWindowsTar = (fs: FileSystem.FileSystem, commands: Array<string>) =>
460 ChildProcessSpawner.make((command) =>
461 Effect.gen(function* () {
462 const { command: executable, args } = command as unknown as {
463 readonly command: string;
464 readonly args: ReadonlyArray<string>;
465 };
466 commands.push(executable);
467 const names = Object.keys(windowsPackage);
468 if (args[0] === "-tzf") return processHandle(`${names.join("\r\n")}\r\n`);
469 if (args[0] === "-tvzf")
470 return processHandle(`${names.map((name) => `-rwxr-xr-x 0 0 ${name}`).join("\r\n")}\r\n`);
471 const runtime = args[3] ?? "";
472 for (const [name, contents] of Object.entries(windowsPackage)) {
473 yield* fs.makeDirectory(`${runtime}/${name.split("/").slice(0, -1).join("/")}`, {
474 recursive: true,
475 });
476 yield* fs.writeFileString(`${runtime}/${name}`, contents);
477 }
478 return processHandle("");
479 }).pipe(Effect.orDie),
480 );
481​
482it.effect("installs on Windows via System32 tar with CRLF output and a locked runtime", () =>
483 Effect.gen(function* () {
484 const fs = yield* FileSystem.FileSystem;
485 const commands: Array<string> = [];
486 const h = yield* makeHarness({
487 platform: "win32",
488 spawner: makeWindowsTar(fs, commands),
489 runtimeRenameFailures: 3,
490 });
491 yield* h.installation.start;
492 // Each failed attempt has scheduled its retry before the test fiber resumes.
493 for (let attempt = 0; attempt < 3; attempt++) {
494 yield* Queue.take(h.failedRenames);
495 yield* TestClock.adjust("100 millis");
496 }
497 expect(yield* terminalState(h.installation)).toMatchObject({ phase: "succeeded" });
498 expect(commands).toEqual([
499 "C:\\Windows\\System32\\tar.exe",
500 "C:\\Windows\\System32\\tar.exe",
501 "C:\\Windows\\System32\\tar.exe",
502 ]);
503 const path = yield* Path.Path;
504 expect((yield* h.installation.resolve()).executablePath).toBe(
505 path.join(h.baseDir, "tools", "codex", "0.156.1", "bin", "codex.exe"),
506 );
507 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
508);
509it.effect("does not retry a failed runtime rename outside Windows", () =>
510 Effect.gen(function* () {
511 const h = yield* makeHarness({ runtimeRenameFailures: 1 });
512 yield* h.installation.start;
513 expect((yield* terminalState(h.installation)).phase).toBe("failed");
514 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
515);