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