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 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 * 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
95for (const version of ["0.156.0", "0.156.1", "0.156.2", "0.157.0"]) {
96 it.effect(`reuses installed Codex ${version} without downloading or taking ownership of it`, () =>
97 Effect.gen(function* () {
98 const h = yield* makeHarness({ local: { version } });
99 expect(yield* h.installation.start).toMatchObject({
100 source: "local",
101 phase: "succeeded",
102 installedVersion: version,
103 executablePath: h.localBinaryPath,
104 canRemove: false,
105 });
106 expect(yield* h.installation.resolve()).toMatchObject({
107 source: "local",
108 executablePath: h.localBinaryPath,
109 managedVersionDirectory: null,
110 version,
111 });
112 yield* h.installation.acquire().pipe(Effect.scoped);
113 expect(h.downloads()).toBe(0);
114 expect(yield* h.fs.exists(h.installation.managedDirectory)).toBe(false);
115 expect((yield* h.fs.readFileString(h.probeLog)).trim().split("\n")).toEqual([
116 "--version",
117 "app-server --help",
118 ]);
119 yield* h.installation.remove();
120 expect(yield* h.fs.exists(h.localBinaryPath)).toBe(true);
121 expect((yield* h.installation.state).source).toBe("local");
122 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
123 );
124}
125for (const local of [
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]) {
135 it.effect(
136 `downloads the pinned release when the local CLI is unsupported or broken: ${JSON.stringify(local)}`,
137 () =>
138 Effect.gen(function* () {
139 const h = yield* makeHarness({ local });
140 expect((yield* h.installation.state).installedVersion).toBeNull();
141 yield* h.installation.start;
142 const installed = yield* terminalState(h.installation);
143 expect(installed.phase).toBe("succeeded");
144 const executable = yield* h.installation.resolve();
145 expect(executable.source).toBe("managed");
146 expect(installed.executablePath).toBe(executable.executablePath);
147 expect(h.downloads()).toBe(1);
148 expect(yield* h.fs.exists(h.localBinaryPath)).toBe(true);
149 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
150 );
151}
152it.effect("falls back to a managed download when the reused local executable disappears", () =>
153 Effect.gen(function* () {
154 const h = yield* makeHarness({ local: { version: "0.156.1" } });
155 expect((yield* h.installation.resolve()).source).toBe("local");
156 yield* h.fs.remove(h.localBinaryPath);
157 yield* h.installation.start;
158 expect((yield* terminalState(h.installation)).phase).toBe("succeeded");
159 expect((yield* h.installation.resolve()).source).toBe("managed");
160 expect(h.downloads()).toBe(1);
161 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
162);
163
164it.effect("rechecks compatibility after the local executable is replaced", () =>
165 Effect.gen(function* () {
166 const h = yield* makeHarness({ local: { version: "0.156.1" } });
167 expect((yield* h.installation.resolve()).source).toBe("local");
168 yield* h.fs.remove(h.localBinaryPath);
169 yield* h.fs.writeFileString(h.localBinaryPath, "#!/bin/sh\nprintf 'codex-cli 0.128.9\\n'\n", {
170 mode: 0o755,
171 });
172 yield* h.installation.start;
173 expect((yield* terminalState(h.installation)).phase).toBe("succeeded");
174 expect((yield* h.installation.resolve()).source).toBe("managed");
175 expect(h.downloads()).toBe(1);
176 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
177);
178
179it.effect("rechecks a cached local executable when the shared manifest policy changes", () =>
180 Effect.gen(function* () {
181 let manifest = ModelManifest.BUNDLED_MODEL_MANIFEST;
182 const h = yield* makeHarness({
183 local: { version: "0.156.0" },
184 manifestCurrent: Effect.sync(() => manifest),
185 });
186 expect((yield* h.installation.resolve()).source).toBe("local");
187 manifest = {
188 ...manifest,
189 compatibility: [
190 {
191 driver: "codex",
192 t3CodeRange: ">=0.0.42",
193 ranges: [
194 { range: ">=0.156.1", status: "supported" },
195 { range: "<0.156.1", status: "broken" },
196 ],
197 },
198 ],
199 };
200 yield* h.installation.start;
201 expect((yield* terminalState(h.installation)).phase).toBe("succeeded");
202 expect((yield* h.installation.resolve()).source).toBe("managed");
203 expect(h.downloads()).toBe(1);
204 expect((yield* h.fs.readFileString(h.probeLog)).trim().split("\n")).toEqual([
205 "--version",
206 "app-server --help",
207 ]);
208 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
209);
210
211it.effect("uses bundled Codex compatibility when the remote manifest omits its policy", () =>
212 Effect.gen(function* () {
213 const h = yield* makeHarness({
214 local: { version: "0.156.0" },
215 manifestCurrent: Effect.succeed({
216 ...ModelManifest.BUNDLED_MODEL_MANIFEST,
217 compatibility: [],
218 }),
219 });
220 expect((yield* h.installation.start).source).toBe("local");
221 expect(h.downloads()).toBe(0);
222 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
223);
224
225it.effect("preserves the invoked name of version-manager launcher symlinks", () =>
226 Effect.gen(function* () {
227 const h = yield* makeHarness({ local: { version: "0.156.1" } });
228 const launcher = `${h.baseDir}/launcher`;
229 yield* h.fs.writeFileString(
230 launcher,
231 '#!/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',
232 { mode: 0o755 },
233 );
234 yield* h.fs.remove(h.localBinaryPath);
235 yield* h.fs.symlink(launcher, h.localBinaryPath);
236 expect(yield* h.installation.start).toMatchObject({ source: "local", phase: "succeeded" });
237 expect((yield* h.installation.resolve()).executablePath).toBe(h.localBinaryPath);
238 expect(h.downloads()).toBe(0);
239 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
240);
241
242it.effect(
243 "installs the complete verified package in tools/codex/version and survives a restart",
244 () =>
245 Effect.gen(function* () {
246 const { installation, fs, baseDir } = yield* makeHarness();
247 yield* installation.start;
248 expect((yield* terminalState(installation)).phase).toBe("succeeded");
249 const executable = yield* installation.resolve();
250 expect(executable.executablePath).toBe(`${baseDir}/tools/codex/0.156.1/bin/codex`);
251 expect(
252 yield* fs.readFileString(`${executable.managedVersionDirectory}/bin/codex-code-mode-host`),
253 ).toBe("host");
254 expect(yield* fs.readFileString(`${executable.managedVersionDirectory}/codex-path/rg`)).toBe(
255 "rg",
256 );
257 const restarted = yield* makeHarness({ baseDir });
258 expect((yield* restarted.installation.resolve()).version).toBe("0.156.1");
259 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
260);
261
262it.effect("requires an update before running an older activated managed installation", () =>
263 Effect.gen(function* () {
264 const first = yield* makeHarness();
265 yield* first.installation.start;
266 yield* terminalState(first.installation);
267 const executable = yield* first.installation.resolve();
268 const oldDirectory = `${first.installation.managedDirectory}/0.155.1`;
269 yield* first.fs.rename(executable.managedVersionDirectory!, oldDirectory);
270 for (const name of ["codex-package.json", ".install-complete.json"]) {
271 const file = `${oldDirectory}/${name}`;
272 yield* first.fs.writeFileString(
273 file,
274 (yield* first.fs.readFileString(file)).replaceAll("0.156.1", "0.155.1"),
275 );
276 }
277 yield* first.fs.writeFileString(
278 `${first.installation.managedDirectory}/active.json`,
279 '{"version":"0.155.1"}',
280 );
281 const restarted = yield* makeHarness({ baseDir: first.baseDir });
282 expect((yield* Effect.flip(restarted.installation.resolve())).detail).toContain(
283 "outside the supported range",
284 );
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(CodexInstallation.resolveCodexReleaseAsset(platform, arch)?.url).toContain(
363 "codex-package-",
364 );
365 expect(CodexInstallation.resolveCodexReleaseAsset("linux", "riscv64")).toBeNull();
366});