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

CodexInstallation.test.ts

362 lines15.4 KB

1import * as NodeServices from "@effect/platform-node/NodeServices";
2import * as ModelManifest from "./ModelManifest.ts";
3import { expect, it } from "@effect/vitest";
4import {
5 HostProcessArchitecture,
6 HostProcessEnvironment,
7 HostProcessPlatform,
8} from "@t3tools/shared/hostProcess";
9import * as Deferred from "effect/Deferred";
10import * as Effect from "effect/Effect";
11import * as FileSystem from "effect/FileSystem";
12import * as Option from "effect/Option";
13import * as Exit from "effect/Exit";
14import * as Scope from "effect/Scope";
15import * as Stream from "effect/Stream";
16import { HttpClient, HttpClientResponse } from "effect/http";
17import * as NodeCrypto from "node:crypto";
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 sha256: NodeCrypto.createHash("sha256").update(archive).digest("hex"),
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>;
36 baseDir?: string;
37 local?: { version: string; appServerFails?: boolean; versionFails?: boolean };
38 } = {},
39) {
40 const fs = yield* FileSystem.FileSystem;
41 const baseDir =
42 input.baseDir ?? (yield* fs.makeTempDirectoryScoped({ prefix: "t3-codex-install-test-" }));
43 const localDirectory = `${baseDir}/local`;
44 const localBinaryPath = `${localDirectory}/codex`;
45 const probeLog = `${baseDir}/local-probes.txt`;
46 if (input.local) {
47 yield* fs.makeDirectory(localDirectory, { recursive: true });
48 yield* fs.writeFileString(
49 localBinaryPath,
50 `#!/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`,
51 { mode: 0o755 },
52 );
53 }
54 let downloads = 0;
55 const installation = yield* CodexInstallation.makeCodexInstallation({
56 baseDir,
57 releaseAsset: asset,
58 validate: () => Effect.void,
59 ...input.options,
60 }).pipe(
61 Effect.provideService(ModelManifest.ModelManifest, {
62 current: input.manifestCurrent ?? Effect.succeed(ModelManifest.BUNDLED_MODEL_MANIFEST),
63 refresh: Effect.succeed(ModelManifest.BUNDLED_MODEL_MANIFEST),
64 forceRefresh: Effect.succeed(ModelManifest.BUNDLED_MODEL_MANIFEST),
65 refreshInBackground: Effect.void,
66 }),
67 Effect.provideService(HostProcessPlatform, "darwin"),
68 Effect.provideService(HostProcessArchitecture, "arm64"),
69 Effect.provideService(HostProcessEnvironment, { PATH: input.local ? localDirectory : "" }),
70 Effect.provideService(
71 HttpClient.HttpClient,
72 HttpClient.make((request) =>
73 Effect.sync(() => {
74 downloads++;
75 return Object.defineProperty(
76 HttpClientResponse.fromWeb(request, new Response(null)),
77 "stream",
78 {
79 value: input.body ?? Stream.succeed(archive),
80 },
81 );
82 }),
83 ),
84 ),
85 );
86 return { installation, fs, baseDir, localBinaryPath, probeLog, downloads: () => downloads };
87});
88const terminalState = (installation: CodexInstallation.CodexInstallation["Service"]) =>
89 installation.changes.pipe(
90 Stream.filter((state) => ["succeeded", "failed", "cancelled"].includes(state.phase)),
91 Stream.runHead,
92 Effect.map(Option.getOrThrow),
93 );
94​
95it.effect.each(["0.156.0", "0.156.1", "0.156.2", "0.157.0"])(
96 "reuses installed Codex %s without downloading or taking ownership of it",
97 (version) =>
98 Effect.gen(function* () {
99 const h = yield* makeHarness({ local: { version } });
100 expect(yield* h.installation.start).toMatchObject({
101 source: "local",
102 phase: "succeeded",
103 installedVersion: version,
104 executablePath: h.localBinaryPath,
105 canRemove: false,
106 });
107 expect(yield* h.installation.resolve()).toMatchObject({
108 source: "local",
109 executablePath: h.localBinaryPath,
110 managedVersionDirectory: null,
111 version,
112 });
113 yield* h.installation.acquire().pipe(Effect.scoped);
114 expect(h.downloads()).toBe(0);
115 expect(yield* h.fs.exists(h.installation.managedDirectory)).toBe(false);
116 expect((yield* h.fs.readFileString(h.probeLog)).trim().split("\n")).toEqual([
117 "--version",
118 "app-server --help",
119 ]);
120 yield* h.installation.remove();
121 expect(yield* h.fs.exists(h.localBinaryPath)).toBe(true);
122 expect((yield* h.installation.state).source).toBe("local");
123 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
124);
125it.effect.each([
126 { version: "0.128.9" },
127 { version: "0.145.0" },
128 { version: "0.155.1" },
129 { version: "0.155.9" },
130 { version: "0.156.1-alpha.1" },
131 { version: "unknown" },
132 { version: "0.156.1", appServerFails: true },
133 { version: "0.156.1", versionFails: true },
134])("downloads the pinned release when the local CLI is unsupported or broken: %j", (local) =>
135 Effect.gen(function* () {
136 const h = yield* makeHarness({ local });
137 expect((yield* h.installation.state).installedVersion).toBeNull();
138 yield* h.installation.start;
139 const installed = yield* terminalState(h.installation);
140 expect(installed.phase).toBe("succeeded");
141 const executable = yield* h.installation.resolve();
142 expect(executable.source).toBe("managed");
143 expect(installed.executablePath).toBe(executable.executablePath);
144 expect(h.downloads()).toBe(1);
145 expect(yield* h.fs.exists(h.localBinaryPath)).toBe(true);
146 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
147);
148it.effect("falls back to a managed download when the reused local executable disappears", () =>
149 Effect.gen(function* () {
150 const h = yield* makeHarness({ local: { version: "0.156.1" } });
151 expect((yield* h.installation.resolve()).source).toBe("local");
152 yield* h.fs.remove(h.localBinaryPath);
153 yield* h.installation.start;
154 expect((yield* terminalState(h.installation)).phase).toBe("succeeded");
155 expect((yield* h.installation.resolve()).source).toBe("managed");
156 expect(h.downloads()).toBe(1);
157 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
158);
159​
160it.effect("rechecks compatibility after the local executable is replaced", () =>
161 Effect.gen(function* () {
162 const h = yield* makeHarness({ local: { version: "0.156.1" } });
163 expect((yield* h.installation.resolve()).source).toBe("local");
164 yield* h.fs.remove(h.localBinaryPath);
165 yield* h.fs.writeFileString(h.localBinaryPath, "#!/bin/sh\nprintf 'codex-cli 0.128.9\\n'\n", {
166 mode: 0o755,
167 });
168 yield* h.installation.start;
169 expect((yield* terminalState(h.installation)).phase).toBe("succeeded");
170 expect((yield* h.installation.resolve()).source).toBe("managed");
171 expect(h.downloads()).toBe(1);
172 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
173);
174​
175it.effect("rechecks a cached local executable when the shared manifest policy changes", () =>
176 Effect.gen(function* () {
177 let manifest = ModelManifest.BUNDLED_MODEL_MANIFEST;
178 const h = yield* makeHarness({
179 local: { version: "0.156.0" },
180 manifestCurrent: Effect.sync(() => manifest),
181 });
182 expect((yield* h.installation.resolve()).source).toBe("local");
183 manifest = {
184 ...manifest,
185 compatibility: [
186 {
187 driver: "codex",
188 t3CodeRange: ">=0.0.42",
189 ranges: [
190 { range: ">=0.156.1", status: "supported" },
191 { range: "<0.156.1", status: "broken" },
192 ],
193 },
194 ],
195 };
196 yield* h.installation.start;
197 expect((yield* terminalState(h.installation)).phase).toBe("succeeded");
198 expect((yield* h.installation.resolve()).source).toBe("managed");
199 expect(h.downloads()).toBe(1);
200 expect((yield* h.fs.readFileString(h.probeLog)).trim().split("\n")).toEqual([
201 "--version",
202 "app-server --help",
203 ]);
204 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
205);
206​
207it.effect("uses bundled Codex compatibility when the remote manifest omits its policy", () =>
208 Effect.gen(function* () {
209 const h = yield* makeHarness({
210 local: { version: "0.156.0" },
211 manifestCurrent: Effect.succeed({
212 ...ModelManifest.BUNDLED_MODEL_MANIFEST,
213 compatibility: [],
214 }),
215 });
216 expect((yield* h.installation.start).source).toBe("local");
217 expect(h.downloads()).toBe(0);
218 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
219);
220​
221it.effect("preserves the invoked name of version-manager launcher symlinks", () =>
222 Effect.gen(function* () {
223 const h = yield* makeHarness({ local: { version: "0.156.1" } });
224 const launcher = `${h.baseDir}/launcher`;
225 yield* h.fs.writeFileString(
226 launcher,
227 '#!/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',
228 { mode: 0o755 },
229 );
230 yield* h.fs.remove(h.localBinaryPath);
231 yield* h.fs.symlink(launcher, h.localBinaryPath);
232 expect(yield* h.installation.start).toMatchObject({ source: "local", phase: "succeeded" });
233 expect((yield* h.installation.resolve()).executablePath).toBe(h.localBinaryPath);
234 expect(h.downloads()).toBe(0);
235 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
236);
237​
238it.effect(
239 "installs the complete verified package in tools/codex/version and survives a restart",
240 () =>
241 Effect.gen(function* () {
242 const { installation, fs, baseDir } = yield* makeHarness();
243 yield* installation.start;
244 expect((yield* terminalState(installation)).phase).toBe("succeeded");
245 const executable = yield* installation.resolve();
246 expect(executable.executablePath).toBe(`${baseDir}/tools/codex/0.156.1/bin/codex`);
247 expect(
248 yield* fs.readFileString(`${executable.managedVersionDirectory}/bin/codex-code-mode-host`),
249 ).toBe("host");
250 expect(yield* fs.readFileString(`${executable.managedVersionDirectory}/codex-path/rg`)).toBe(
251 "rg",
252 );
253 const restarted = yield* makeHarness({ baseDir });
254 expect((yield* restarted.installation.resolve()).version).toBe("0.156.1");
255 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
256);
257​
258it.effect("requires an update before running an older activated managed installation", () =>
259 Effect.gen(function* () {
260 const first = yield* makeHarness();
261 yield* first.installation.start;
262 yield* terminalState(first.installation);
263 const executable = yield* first.installation.resolve();
264 const oldDirectory = `${first.installation.managedDirectory}/0.155.1`;
265 yield* first.fs.rename(executable.managedVersionDirectory!, oldDirectory);
266 for (const name of ["codex-package.json", ".install-complete.json"]) {
267 const file = `${oldDirectory}/${name}`;
268 yield* first.fs.writeFileString(
269 file,
270 (yield* first.fs.readFileString(file)).replaceAll("0.156.1", "0.155.1"),
271 );
272 }
273 yield* first.fs.writeFileString(
274 `${first.installation.managedDirectory}/active.json`,
275 '{"version":"0.155.1"}',
276 );
277 const restarted = yield* makeHarness({ baseDir: first.baseDir });
278 expect((yield* Effect.flip(restarted.installation.resolve())).detail).toContain(
279 "outside the supported range",
280 );
281 yield* restarted.installation.start;
282 expect((yield* terminalState(restarted.installation)).phase).toBe("succeeded");
283 expect((yield* restarted.installation.resolve()).version).toBe("0.156.1");
284 expect(restarted.downloads()).toBe(1);
285 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
286);
287​
288it.effect("rejects corrupted downloads without publishing a runtime", () =>
289 Effect.gen(function* () {
290 const { installation, fs } = yield* makeHarness({
291 options: { releaseAsset: { ...asset, sha256: "0".repeat(64) } },
292 });
293 yield* installation.start;
294 const state = yield* terminalState(installation);
295 expect(state.phase).toBe("failed");
296 expect(state.message).toContain("SHA-256");
297 expect(yield* fs.exists(`${installation.managedDirectory}/active.json`)).toBe(false);
298 expect(yield* fs.exists(`${installation.managedDirectory}/0.156.1`)).toBe(false);
299 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
300);
301​
302it.effect("cancels an in-flight download and cleans the staging directory", () =>
303 Effect.gen(function* () {
304 const downloading = yield* Deferred.make<void>();
305 const body = Stream.fromEffect(
306 Deferred.succeed(downloading, undefined).pipe(Effect.andThen(Effect.never)),
307 );
308 const { installation, fs } = yield* makeHarness({ body });
309 const started = yield* installation.start;
310 yield* Deferred.await(downloading);
311 expect((yield* installation.cancel(started.operationId!)).phase).toBe("cancelled");
312 expect(
313 (yield* fs.readDirectory(installation.managedDirectory)).filter((name) =>
314 name.startsWith(".install-"),
315 ),
316 ).toEqual([]);
317 expect(yield* fs.exists(`${installation.managedDirectory}/active.json`)).toBe(false);
318 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
319);
320​
321it.effect("protects active process leases and removes the runtime after release", () =>
322 Effect.gen(function* () {
323 const { installation, fs } = yield* makeHarness();
324 yield* installation.start;
325 yield* terminalState(installation);
326 const leaseScope = yield* Scope.make();
327 yield* installation.acquire().pipe(Effect.provideService(Scope.Scope, leaseScope));
328 expect((yield* Effect.flip(installation.remove())).detail).toContain("Stop Codex sessions");
329 yield* Scope.close(leaseScope, Exit.void);
330 yield* installation.remove();
331 expect(yield* fs.exists(installation.managedDirectory)).toBe(false);
332 expect((yield* installation.state).installedVersion).toBeNull();
333 expect((yield* installation.state).executablePath).toBeNull();
334 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
335);
336​
337it.effect("keeps an activated runtime when a later update fails verification", () =>
338 Effect.gen(function* () {
339 const first = yield* makeHarness();
340 yield* first.installation.start;
341 yield* terminalState(first.installation);
342 const update = yield* makeHarness({
343 baseDir: first.baseDir,
344 options: { releaseAsset: { ...asset, version: "0.156.2", sha256: "0".repeat(64) } },
345 });
346 expect((yield* update.installation.state).executablePath).toBe(
347 (yield* first.installation.resolve()).executablePath,
348 );
349 yield* update.installation.start;
350 expect((yield* terminalState(update.installation)).phase).toBe("failed");
351 expect((yield* update.installation.resolve()).version).toBe("0.156.1");
352 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
353);
354​
355it("publishes complete packages for all supported platforms", () => {
356 for (const platform of ["darwin", "linux", "win32"] as const)
357 for (const arch of ["x64", "arm64"])
358 expect(CodexInstallation.resolveCodexReleaseAsset(platform, arch)?.url).toContain(
359 "codex-package-",
360 );
361 expect(CodexInstallation.resolveCodexReleaseAsset("linux", "riscv64")).toBeNull();
362});