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