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

CodexInstallation.test.ts

865 lines36.7 KB

1import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import * as Layer from "effect/Layer";
4import * as ModelManifest from "./ModelManifest.ts";
5import { expect, it } from "@effect/vitest";
6import * as HostProcess from "@t3tools/shared/HostProcess";
7import * as Digest from "effect/crypto/Digest";
8import * as Deferred from "effect/Deferred";
9import * as Effect from "effect/Effect";
10import * as Hex from "effect/encoding/Hex";
11import * as FileSystem from "effect/FileSystem";
12import * as Option from "effect/Option";
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 Stream from "effect/Stream";
18import { HttpClient, HttpClientError, HttpClientRequest, HttpClientResponse } from "effect/http";
19import * as TestClock from "effect/testing/TestClock";
20import { ChildProcess, ChildProcessSpawner } from "effect/process";
21import * as CodexInstallation from "./CodexInstallation.ts";
22​
23const archive = Buffer.from(
24 "H4sIAAAAAAAC/+3W0W6DIBQGYB/FcD0sKNSkD7J7aom6tmAQtzXL3n3QZM3qdWVt+n8XoCckJp78wLY3q8bu9Ge2HBbUUp7nYD4H8s9zrNdSsCxnWQLT6JULn8ye09K9h/u2/c0/jSM9xqGzo0+bf3Gdf15WQiD/Kdy61/CA+z8dlO9Wrv2387+c5Z9VZY38p7BY0+Gh8t/sVauLt9Ga9Pnnop7ln1e4/6fxRQ7qZCf/qt3YW0M2OX/JyfvljbCCy3XBSaiGH9VqH4tKuaZbC6qG4aDpTrmP3sQV2nh3Gmxvzqsud0vyjaABAAAAAAAAAAAAAAAk8gOq19rvACgAAA==",
25 "base64",
26);
27const asset = {
28 version: "0.156.1",
29 target: "aarch64-apple-darwin",
30 url: "https://github.com/openai/codex/releases/download/test/package.tar.gz",
31 archiveBytes: archive.length,
32};
33const makeHarness = Effect.fn("test.makeCodexInstallation")(function* (
34 input: {
35 options?: Partial<CodexInstallation.CodexInstallationOptions>;
36 manifestCurrent?: Effect.Effect<ModelManifest.ModelManifestData>;
37 body?: Stream.Stream<Uint8Array, HttpClientError.HttpClientError>;
38 downloadStatus?: number;
39 baseDir?: string;
40 local?: { version: string; appServerFails?: boolean; versionFails?: boolean };
41 platform?: NodeJS.Platform;
42 spawner?: ChildProcessSpawner.ChildProcessSpawner["Service"];
43 runtimeRenameFailures?: number;
44 /** Served by URL instead of the pinned package. */
45 responses?: Readonly<Record<string, () => Response>>;
46 } = {},
47) {
48 const fs = yield* FileSystem.FileSystem;
49 const baseDir =
50 input.baseDir ?? (yield* fs.makeTempDirectoryScoped({ prefix: "t3-codex-install-test-" }));
51 const localDirectory = `${baseDir}/local`;
52 const localBinaryPath = `${localDirectory}/codex${input.platform === "win32" ? ".exe" : ""}`;
53 const probeLog = `${baseDir}/local-probes.txt`;
54 // A restarted harness on the same baseDir keeps the existing binary, and with it its fingerprint.
55 if (input.local && !(yield* fs.exists(localBinaryPath))) {
56 yield* fs.makeDirectory(localDirectory, { recursive: true });
57 yield* fs.writeFileString(
58 localBinaryPath,
59 `#!/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`,
60 { mode: 0o755 },
61 );
62 }
63 let downloads = 0;
64 const digest = yield* Digest.Digest;
65 const sha256 = Hex.encode(yield* digest.digest(Digest.sha256, archive).pipe(Effect.orDie));
66 let runtimeRenameFailures = input.runtimeRenameFailures ?? 0;
67 const failedRenames = yield* Queue.unbounded<void>();
68 const lockingFs: FileSystem.FileSystem = {
69 ...fs,
70 // Suspended so each retry of the same effect is a fresh attempt, like the real rename.
71 rename: (from, to) =>
72 Effect.suspend(() =>
73 /[/\\]runtime$/u.test(from) && runtimeRenameFailures-- > 0
74 ? Queue.offer(failedRenames, undefined).pipe(
75 Effect.andThen(
76 Effect.fail(
77 PlatformError.systemError({
78 _tag: "PermissionDenied",
79 module: "FileSystem",
80 method: "rename",
81 pathOrDescriptor: from,
82 }),
83 ),
84 ),
85 )
86 : fs.rename(from, to),
87 ),
88 };
89 const spawner = input.spawner ?? (yield* ChildProcessSpawner.ChildProcessSpawner);
90 const installation = yield* CodexInstallation.makeCodexInstallation({
91 baseDir,
92 releaseAsset: { ...asset, sha256 },
93 validate: () => Effect.void,
94 ...input.options,
95 }).pipe(
96 Effect.provideService(ModelManifest.ModelManifest, {
97 current: input.manifestCurrent ?? Effect.succeed(ModelManifest.BUNDLED_MODEL_MANIFEST),
98 refresh: Effect.succeed(ModelManifest.BUNDLED_MODEL_MANIFEST),
99 forceRefresh: Effect.succeed(ModelManifest.BUNDLED_MODEL_MANIFEST),
100 refreshOnDemand: Effect.succeed(ModelManifest.BUNDLED_MODEL_MANIFEST),
101 refreshInBackground: Effect.void,
102 }),
103 Effect.provideService(HostProcess.Platform, input.platform ?? "darwin"),
104 Effect.provideService(HostProcess.Architecture, "arm64"),
105 Effect.provideService(HostProcess.Environment, {
106 PATH: input.local ? localDirectory : "",
107 SystemRoot: "C:\\Windows",
108 }),
109 Effect.provideService(FileSystem.FileSystem, lockingFs),
110 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
111 Effect.provideService(
112 HttpClient.HttpClient,
113 HttpClient.make((request) =>
114 Effect.sync(() => {
115 downloads++;
116 const respond = input.responses?.[request.url];
117 if (respond) return HttpClientResponse.fromWeb(request, respond());
118 return Object.defineProperty(
119 HttpClientResponse.fromWeb(
120 request,
121 new Response(null, { status: input.downloadStatus ?? 200 }),
122 ),
123 "stream",
124 {
125 value: input.body ?? Stream.succeed(archive),
126 },
127 );
128 }),
129 ),
130 ),
131 );
132 return {
133 installation,
134 fs,
135 baseDir,
136 localBinaryPath,
137 probeLog,
138 failedRenames,
139 downloads: () => downloads,
140 };
141});
142const terminalState = (installation: CodexInstallation.CodexInstallation["Service"]) =>
143 installation.changes.pipe(
144 Stream.filter((state) => ["succeeded", "failed", "cancelled"].includes(state.phase)),
145 Stream.runHead,
146 Effect.map(Option.getOrThrow),
147 );
148​
149it.effect.each(["0.156.0", "0.156.1", "0.156.2", "0.157.0"])(
150 "reuses installed Codex %s without downloading or taking ownership of it",
151 (version) =>
152 Effect.gen(function* () {
153 const h = yield* makeHarness({ local: { version } });
154 expect(yield* h.installation.start).toMatchObject({
155 source: "local",
156 phase: "succeeded",
157 installedVersion: version,
158 executablePath: h.localBinaryPath,
159 canRemove: false,
160 });
161 expect(yield* h.installation.resolve()).toMatchObject({
162 source: "local",
163 executablePath: h.localBinaryPath,
164 managedVersionDirectory: null,
165 version,
166 });
167 yield* h.installation.acquire().pipe(Effect.scoped);
168 expect(h.downloads()).toBe(0);
169 expect(yield* h.fs.exists(h.installation.managedDirectory)).toBe(false);
170 expect((yield* h.fs.readFileString(h.probeLog)).trim().split("\n")).toEqual([
171 "--version",
172 "app-server --help",
173 ]);
174 yield* h.installation.remove();
175 expect(yield* h.fs.exists(h.localBinaryPath)).toBe(true);
176 expect((yield* h.installation.state).source).toBe("local");
177 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
178);
179it.effect.each([
180 { version: "0.128.9" },
181 { version: "0.145.0" },
182 { version: "0.155.1" },
183 { version: "0.155.9" },
184 { version: "0.156.1-alpha.1" },
185 { version: "unknown" },
186 { version: "0.156.1", appServerFails: true },
187 { version: "0.156.1", versionFails: true },
188])("downloads the pinned release when the local CLI is unsupported or broken: %j", (local) =>
189 Effect.gen(function* () {
190 const h = yield* makeHarness({ local });
191 expect((yield* h.installation.state).installedVersion).toBeNull();
192 yield* h.installation.start;
193 const installed = yield* terminalState(h.installation);
194 expect(installed.phase).toBe("succeeded");
195 const executable = yield* h.installation.resolve();
196 expect(executable.source).toBe("managed");
197 expect(installed.executablePath).toBe(executable.executablePath);
198 expect(h.downloads()).toBe(1);
199 expect(yield* h.fs.exists(h.localBinaryPath)).toBe(true);
200 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
201);
202​
203const compileNative = Effect.fn("test.compileNative")(function* (
204 executablePath: string,
205 source: string,
206) {
207 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
208 const compiler = yield* spawner.spawn(
209 ChildProcess.make("cc", ["-x", "c", "-", "-o", executablePath], {
210 stdin: Stream.make(new TextEncoder().encode(source)),
211 stdout: "inherit",
212 stderr: "inherit",
213 }),
214 );
215 expect(yield* compiler.exitCode).toBe(0);
216}, Effect.scoped);
217​
218it.effect.each([
219 { layout: "npm bin symlink", persists: true },
220 { layout: "npm shim", persists: true },
221 { layout: "wrapper script", persists: false },
222])(
223 "re-probes a $layout Codex after a restart only when its payload can change",
224 ({ layout, persists }) =>
225 Effect.gen(function* () {
226 const fs = yield* FileSystem.FileSystem;
227 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-codex-install-test-" });
228 const packageDirectory =
229 layout === "npm shim"
230 ? `${baseDir}/local/node_modules/@openai/codex`
231 : `${baseDir}/npm/lib/node_modules/@openai/codex`;
232 const payload =
233 layout === "wrapper script" ? `${baseDir}/payload` : `${packageDirectory}/bin/codex.js`;
234 const install = Effect.fn("test.installPayload")(function* (version: string) {
235 yield* fs.makeDirectory(`${packageDirectory}/bin`, { recursive: true });
236 if (layout !== "wrapper script")
237 yield* fs.writeFileString(
238 `${packageDirectory}/package.json`,
239 JSON.stringify({ name: "@openai/codex", version }),
240 );
241 yield* fs.writeFileString(
242 payload,
243 `#!/bin/sh\nprintf '%s\\n' "$*" >> '${baseDir}/local-probes.txt'\ncase "$1" in --version) printf 'codex-cli ${version}\\n';; esac\n`,
244 { mode: 0o755 },
245 );
246 });
247 yield* install("0.156.1");
248 yield* fs.makeDirectory(`${baseDir}/local`, { recursive: true });
249 if (layout === "npm bin symlink") yield* fs.symlink(payload, `${baseDir}/local/codex`);
250 else
251 yield* fs.writeFileString(`${baseDir}/local/codex`, `#!/bin/sh\nexec '${payload}' "$@"\n`, {
252 mode: 0o755,
253 });
254 const first = yield* makeHarness({ baseDir, local: { version: "0.156.1" } });
255 expect((yield* first.installation.resolve()).source).toBe("local");
256 const restarted = yield* makeHarness({ baseDir, local: { version: "0.156.1" } });
257 expect((yield* restarted.installation.resolve()).source).toBe("local");
258 expect((yield* fs.readFileString(first.probeLog)).trim().split("\n")).toHaveLength(
259 persists ? 2 : 4,
260 );
261 yield* install("0.128.9");
262 const upgraded = yield* makeHarness({ baseDir, local: { version: "0.156.1" } });
263 expect((yield* upgraded.installation.state).installedVersion).toBeNull();
264 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
265);
266​
267it.effect("rechecks compatibility after the local executable is replaced", () =>
268 Effect.gen(function* () {
269 const h = yield* makeHarness({ local: { version: "0.156.1" } });
270 expect((yield* h.installation.resolve()).source).toBe("local");
271 yield* h.fs.remove(h.localBinaryPath);
272 yield* h.fs.writeFileString(h.localBinaryPath, "#!/bin/sh\nprintf 'codex-cli 0.128.9\\n'\n", {
273 mode: 0o755,
274 });
275 yield* h.installation.start;
276 expect((yield* terminalState(h.installation)).phase).toBe("succeeded");
277 expect((yield* h.installation.resolve()).source).toBe("managed");
278 expect(h.downloads()).toBe(1);
279 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
280);
281​
282it.effect("rechecks a cached local executable when the shared manifest policy changes", () =>
283 Effect.gen(function* () {
284 let manifest = ModelManifest.BUNDLED_MODEL_MANIFEST;
285 const h = yield* makeHarness({
286 local: { version: "0.156.0" },
287 manifestCurrent: Effect.sync(() => manifest),
288 });
289 expect((yield* h.installation.resolve()).source).toBe("local");
290 manifest = {
291 ...manifest,
292 compatibility: [
293 {
294 driver: "codex",
295 t3CodeRange: ">=0.0.42",
296 ranges: [
297 { range: ">=0.156.1", status: "supported" },
298 { range: "<0.156.1", status: "broken" },
299 ],
300 },
301 ],
302 };
303 yield* h.installation.start;
304 expect((yield* terminalState(h.installation)).phase).toBe("succeeded");
305 expect((yield* h.installation.resolve()).source).toBe("managed");
306 expect(h.downloads()).toBe(1);
307 expect((yield* h.fs.readFileString(h.probeLog)).trim().split("\n")).toEqual([
308 "--version",
309 "app-server --help",
310 ]);
311 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
312);
313​
314it.effect("uses bundled Codex compatibility when the remote manifest omits its policy", () =>
315 Effect.gen(function* () {
316 const h = yield* makeHarness({
317 local: { version: "0.156.0" },
318 manifestCurrent: Effect.succeed({
319 ...ModelManifest.BUNDLED_MODEL_MANIFEST,
320 compatibility: [],
321 }),
322 });
323 expect((yield* h.installation.start).source).toBe("local");
324 expect(h.downloads()).toBe(0);
325 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
326);
327​
328it.effect.each([
329 { kind: "script", name: "volta-shim" },
330 { kind: "native", name: "volta-shim" },
331 { kind: "native", name: "mise" },
332 { kind: "native", name: "aqua-proxy" },
333])("preserves the invoked name of $kind $name launcher symlinks", ({ kind, name }) =>
334 Effect.gen(function* () {
335 const h = yield* makeHarness({ local: { version: "0.156.1" } });
336 const launcher = `${h.baseDir}/${name}`;
337 if (kind === "native") {
338 const payload = `${h.baseDir}/codex.js`;
339 yield* h.fs.rename(h.localBinaryPath, payload);
340 yield* compileNative(
341 launcher,
342 `#include <string.h>
343#include <unistd.h>
344int main(int argc, char **argv) {
345 const char *name = strrchr(argv[0], '/');
346 if (strcmp(name ? name + 1 : argv[0], "codex") != 0) return 1;
347 execv(${JSON.stringify(payload)}, argv);
348 return 1;
350`,
351 );
352 } else {
353 yield* h.fs.writeFileString(
354 launcher,
355 '#!/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',
356 { mode: 0o755 },
357 );
358 yield* h.fs.remove(h.localBinaryPath);
359 }
360 yield* h.fs.symlink(launcher, h.localBinaryPath);
361 expect(yield* h.installation.start).toMatchObject({ source: "local", phase: "succeeded" });
362 expect((yield* h.installation.resolve()).executablePath).toBe(h.localBinaryPath);
363 expect(h.downloads()).toBe(0);
364 expect(yield* h.fs.exists(`${h.baseDir}/caches/codex-local-probe.json`)).toBe(false);
365 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
366);
367​
368it.effect(
369 "installs the complete verified package in tools/codex/version and survives a restart",
370 () =>
371 Effect.gen(function* () {
372 const { installation, fs, baseDir } = yield* makeHarness();
373 yield* installation.start;
374 expect((yield* terminalState(installation)).phase).toBe("succeeded");
375 const executable = yield* installation.resolve();
376 expect(executable.executablePath).toBe(`${baseDir}/tools/codex/0.156.1/bin/codex`);
377 expect(
378 yield* fs.readFileString(`${executable.managedVersionDirectory}/bin/codex-code-mode-host`),
379 ).toBe("host");
380 expect(yield* fs.readFileString(`${executable.managedVersionDirectory}/codex-path/rg`)).toBe(
381 "rg",
382 );
383 const restarted = yield* makeHarness({ baseDir });
384 expect((yield* restarted.installation.resolve()).version).toBe("0.156.1");
385 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
386);
387​
388it.effect("requires an update before running an older activated managed installation", () =>
389 Effect.gen(function* () {
390 const first = yield* makeHarness();
391 yield* first.installation.start;
392 yield* terminalState(first.installation);
393 const executable = yield* first.installation.resolve();
394 const oldDirectory = `${first.installation.managedDirectory}/0.155.1`;
395 yield* first.fs.rename(executable.managedVersionDirectory!, oldDirectory);
396 for (const name of ["codex-package.json", ".install-complete.json"]) {
397 const file = `${oldDirectory}/${name}`;
398 yield* first.fs.writeFileString(
399 file,
400 (yield* first.fs.readFileString(file)).replaceAll("0.156.1", "0.155.1"),
401 );
402 }
403 yield* first.fs.writeFileString(
404 `${first.installation.managedDirectory}/active.json`,
405 '{"version":"0.155.1"}',
406 );
407 const restarted = yield* makeHarness({ baseDir: first.baseDir });
408 expect((yield* Effect.flip(restarted.installation.resolve())).detail).toContain(
409 "outside the supported range",
410 );
411 yield* restarted.installation.start;
412 expect((yield* terminalState(restarted.installation)).phase).toBe("succeeded");
413 expect((yield* restarted.installation.resolve()).version).toBe("0.156.1");
414 expect(restarted.downloads()).toBe(1);
415 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
416);
417​
418it.effect("updates an older supported managed installation to the pinned release on startup", () =>
419 Effect.gen(function* () {
420 const first = yield* makeHarness();
421 yield* first.installation.start;
422 yield* terminalState(first.installation);
423 const executable = yield* first.installation.resolve();
424 const oldDirectory = `${first.installation.managedDirectory}/0.156.0`;
425 yield* first.fs.rename(executable.managedVersionDirectory!, oldDirectory);
426 for (const name of ["codex-package.json", ".install-complete.json"]) {
427 const file = `${oldDirectory}/${name}`;
428 yield* first.fs.writeFileString(
429 file,
430 (yield* first.fs.readFileString(file)).replaceAll("0.156.1", "0.156.0"),
431 );
432 }
433 yield* first.fs.writeFileString(
434 `${first.installation.managedDirectory}/active.json`,
435 '{"version":"0.156.0"}',
436 );
437 const restarted = yield* makeHarness({ baseDir: first.baseDir });
438 expect((yield* restarted.installation.state).operationId).not.toBeNull();
439 expect((yield* terminalState(restarted.installation)).phase).toBe("succeeded");
440 expect((yield* restarted.installation.resolve()).version).toBe("0.156.1");
441 expect(restarted.downloads()).toBe(1);
442 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
443);
444​
445it.effect("rejects corrupted downloads without publishing a runtime", () =>
446 Effect.gen(function* () {
447 const { installation, fs } = yield* makeHarness({
448 options: { releaseAsset: { ...asset, sha256: "0".repeat(64) } },
449 });
450 yield* installation.start;
451 const state = yield* terminalState(installation);
452 expect(state.phase).toBe("failed");
453 expect(state.message).toContain("SHA-256");
454 expect(yield* fs.exists(`${installation.managedDirectory}/active.json`)).toBe(false);
455 expect(yield* fs.exists(`${installation.managedDirectory}/0.156.1`)).toBe(false);
456 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
457);
458​
459it.effect.each(["interrupted body", "HTTP 404"] as const)(
460 "reports a download failure for %s without blaming disk access",
461 (failure) =>
462 Effect.gen(function* () {
463 const request = HttpClientRequest.get(asset.url);
464 const response = HttpClientResponse.fromWeb(request, new Response(null));
465 const h = yield* makeHarness(
466 failure === "HTTP 404"
467 ? { downloadStatus: 404 }
468 : {
469 body: Stream.concat(
470 Stream.succeed(archive.subarray(0, 10)),
471 Stream.fail(
472 new HttpClientError.HttpClientError({
473 reason: new HttpClientError.DecodeError({
474 request,
475 response,
476 cause: new TypeError("terminated"),
477 }),
478 }),
479 ),
480 ),
481 },
482 );
483 yield* h.installation.start;
484 expect(yield* terminalState(h.installation)).toMatchObject({
485 phase: "failed",
486 message:
487 failure === "HTTP 404"
488 ? "The Codex download server returned HTTP 404. Try again later."
489 : "The Codex download was interrupted. Check your internet connection, then retry installation.",
490 });
491 expect(h.downloads()).toBe(1);
492 expect(yield* h.fs.readDirectory(h.installation.managedDirectory)).toEqual([]);
493 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
494);
495​
496it.effect(
497 "preserves the filesystem failure message when installation cannot create its directory",
498 () =>
499 Effect.gen(function* () {
500 const fs = yield* FileSystem.FileSystem;
501 const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-codex-install-test-" });
502 const baseDir = `${directory}/not-a-directory`;
503 yield* fs.writeFileString(baseDir, "existing file");
504 const h = yield* makeHarness({ baseDir });
505 yield* h.installation.start;
506 expect(yield* terminalState(h.installation)).toMatchObject({
507 phase: "failed",
508 message: "Could not install Codex. Check disk space and directory access, then try again.",
509 });
510 expect(h.downloads()).toBe(0);
511 expect(yield* fs.readFileString(baseDir)).toBe("existing file");
512 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
513);
514​
515it.effect.each(["cached update", "reverify"] as const)(
516 "reports a verification timeout during %s and preserves the managed runtime",
517 (operation) =>
518 Effect.gen(function* () {
519 const fs = yield* FileSystem.FileSystem;
520 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-codex-verify-test-" });
521 const managed = `${baseDir}/tools/codex`;
522 const installedVersion = operation === "cached update" ? "0.156.0" : asset.version;
523 const target = "aarch64-pc-windows-msvc";
524 const checksum = "a".repeat(64);
525 for (const version of new Set([installedVersion, asset.version])) {
526 const directory = `${managed}/${version}`;
527 yield* fs.makeDirectory(`${directory}/bin`, { recursive: true });
528 yield* fs.makeDirectory(`${directory}/codex-path`, { recursive: true });
529 for (const name of ["bin/codex.exe", "bin/codex-code-mode-host.exe", "codex-path/rg.exe"]) {
530 yield* fs.writeFileString(`${directory}/${name}`, "fixture executable");
531 }
532 yield* fs.writeFileString(
533 `${directory}/codex-package.json`,
534 JSON.stringify({ layoutVersion: 1, version, target, entrypoint: "bin/codex.exe" }),
535 );
536 yield* fs.writeFileString(
537 `${directory}/.install-complete.json`,
538 JSON.stringify({ version, target, sha256: checksum }),
539 );
540 }
541 const pointer = JSON.stringify({ version: installedVersion });
542 yield* fs.writeFileString(`${managed}/active.json`, pointer);
543 const entered = yield* Deferred.make<void>();
544 const h = yield* makeHarness({
545 baseDir,
546 platform: "win32",
547 manifestCurrent: Effect.succeed({
548 ...ModelManifest.BUNDLED_MODEL_MANIFEST,
549 compatibility: [
550 {
551 driver: "codex",
552 t3CodeRange: ">=0.0.0",
553 ranges: [{ range: ">=0.156.0", status: "supported" }],
554 },
555 ],
556 }),
557 options: {
558 releaseAsset: operation === "reverify" ? null : { ...asset, target, sha256: checksum },
559 validate: () => Deferred.succeed(entered, undefined).pipe(Effect.andThen(Effect.never)),
560 },
561 });
562 yield* h.installation.start;
563 yield* Deferred.await(entered);
564 yield* TestClock.adjust("90 seconds");
565 expect(yield* terminalState(h.installation)).toMatchObject({
566 phase: "failed",
567 installedVersion,
568 message:
569 "Codex runtime verification timed out after 90 seconds. Check this environment's server logs for startup errors, then retry installation.",
570 });
571 expect(yield* fs.readFileString(`${managed}/active.json`)).toBe(pointer);
572 expect((yield* h.installation.resolve()).version).toBe(installedVersion);
573 expect(h.downloads()).toBe(0);
574 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
575);
576​
577it.effect("reports a download timeout and cleans the staging directory", () =>
578 Effect.gen(function* () {
579 const started = yield* Deferred.make<void>();
580 const stall = Deferred.succeed(started, undefined).pipe(Effect.andThen(Effect.never));
581 const h = yield* makeHarness({
582 body: Stream.concat(Stream.succeed(archive.subarray(0, 10)), Stream.fromEffect(stall)),
583 });
584 yield* h.installation.start;
585 yield* Deferred.await(started);
586 yield* TestClock.adjust("45 minutes");
587 expect(yield* terminalState(h.installation)).toMatchObject({
588 phase: "failed",
589 message: "The Codex download timed out. Retry installation.",
590 });
591 expect(h.downloads()).toBe(1);
592 expect(yield* h.fs.readDirectory(h.installation.managedDirectory)).toEqual([]);
593 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
594);
595​
596it.effect("cancels an in-flight download and cleans the staging directory", () =>
597 Effect.gen(function* () {
598 const downloading = yield* Deferred.make<void>();
599 const body = Stream.fromEffect(
600 Deferred.succeed(downloading, undefined).pipe(Effect.andThen(Effect.never)),
601 );
602 const { installation, fs } = yield* makeHarness({ body });
603 const started = yield* installation.start;
604 yield* Deferred.await(downloading);
605 expect((yield* installation.cancel(started.operationId!)).phase).toBe("cancelled");
606 expect(
607 (yield* fs.readDirectory(installation.managedDirectory)).filter((name) =>
608 name.startsWith(".install-"),
609 ),
610 ).toEqual([]);
611 expect(yield* fs.exists(`${installation.managedDirectory}/active.json`)).toBe(false);
612 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
613);
614​
615it.effect("protects active process leases and removes the runtime after release", () =>
616 Effect.gen(function* () {
617 const { installation, fs } = yield* makeHarness();
618 yield* installation.start;
619 yield* terminalState(installation);
620 const leaseScope = yield* Scope.make();
621 yield* installation.acquire().pipe(Effect.provideService(Scope.Scope, leaseScope));
622 expect((yield* Effect.flip(installation.remove())).detail).toContain("Stop Codex sessions");
623 yield* Scope.close(leaseScope, Exit.void);
624 yield* installation.remove();
625 expect(yield* fs.exists(installation.managedDirectory)).toBe(false);
626 expect((yield* installation.state).installedVersion).toBeNull();
627 expect((yield* installation.state).executablePath).toBeNull();
628 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
629);
630​
631it.effect("keeps an activated runtime when a later update fails verification", () =>
632 Effect.gen(function* () {
633 const first = yield* makeHarness();
634 yield* first.installation.start;
635 yield* terminalState(first.installation);
636 const update = yield* makeHarness({
637 baseDir: first.baseDir,
638 options: { releaseAsset: { ...asset, version: "0.156.2", sha256: "0".repeat(64) } },
639 });
640 expect((yield* update.installation.state).executablePath).toBe(
641 (yield* first.installation.resolve()).executablePath,
642 );
643 yield* update.installation.start;
644 expect((yield* terminalState(update.installation)).phase).toBe("failed");
645 expect((yield* update.installation.resolve()).version).toBe("0.156.1");
646 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
647);
648​
649const upstreamVersion = "0.163.0";
650const upstreamArchive = Buffer.from(
651 "H4sIAAAAAAACA+3WzY7CIBQF4D5Kw1oqtNQmPoh7rKStP9BQdMaYefcBE43T9RQ1nm8B7Q1Jk94cYN3peW026juZDvOqsrzO3nj2yofnUK9KwZKUJREcByet/2TymabuPby29S3/NIz0EIbWDC5u/sXf/PO8EAL5j+G/ew1vuP/TXrp2bpunnf/5KP+syCvkP4bJmg5vlf96JxuVbQej4+efi2qUf17g/h/Hhezl2RzdStmhM5osUz5Lyen+RljGF0XGiK/6H9UoF4pS2rpdCCr7fq/oRtqvTocVSjt77k2nr6vud0vyg6ABAAAAAAAAAAAAAABE8gvVbjvaACgAAA==",
652 "base64",
653);
654const upstreamReleaseUrl = `https://github.com/openai/codex/releases/download/rust-v${upstreamVersion}`;
655const upstreamResponses = (checksum: string) => ({
656 "https://registry.npmjs.org/@openai/codex/latest": () =>
657 Response.json({ version: upstreamVersion }),
658 [`${upstreamReleaseUrl}/codex-package_SHA256SUMS`]: () =>
659 new Response(
660 `${"0".repeat(64)} codex-package-x86_64-apple-darwin.tar.gz\n${checksum} codex-package-aarch64-apple-darwin.tar.gz\n`,
661 ),
662 [`${upstreamReleaseUrl}/codex-package-aarch64-apple-darwin.tar.gz`]: () =>
663 new Response(upstreamArchive),
664});
665​
666it.effect("updates a managed install to OpenAI's newest release and never downgrades it", () =>
667 Effect.gen(function* () {
668 const digest = yield* Digest.Digest;
669 const checksum = Hex.encode(
670 yield* digest.digest(Digest.sha256, upstreamArchive).pipe(Effect.orDie),
671 );
672 const h = yield* makeHarness({ responses: upstreamResponses(checksum) });
673 yield* h.installation.checkForUpdate;
674 // A fresh install still gets the pinned release.
675 expect((yield* h.installation.state).version).toBe("0.156.1");
676 yield* h.installation.start;
677 expect(yield* terminalState(h.installation)).toMatchObject({
678 phase: "succeeded",
679 installedVersion: "0.156.1",
680 version: upstreamVersion,
681 });
682​
683 const sessionScope = yield* Scope.make();
684 const previous = yield* h.installation.acquire().pipe(Scope.provide(sessionScope));
685 yield* h.installation.start;
686 expect(yield* terminalState(h.installation)).toMatchObject({
687 phase: "succeeded",
688 installedVersion: upstreamVersion,
689 version: upstreamVersion,
690 });
691 expect((yield* h.installation.resolve()).version).toBe(upstreamVersion);
692 // The running session keeps its release until the next start prunes it.
693 expect(yield* h.fs.exists(previous.managedVersionDirectory!)).toBe(true);
694 yield* Scope.close(sessionScope, Exit.void);
695​
696 // Without upstream information the older pin is not offered as a reinstall.
697 const restarted = yield* makeHarness({ baseDir: h.baseDir });
698 expect(yield* h.fs.exists(previous.managedVersionDirectory!)).toBe(false);
699 expect(yield* restarted.installation.state).toMatchObject({
700 installedVersion: upstreamVersion,
701 version: upstreamVersion,
702 });
703 yield* restarted.installation.start;
704 expect(yield* terminalState(restarted.installation)).toMatchObject({
705 phase: "succeeded",
706 installedVersion: upstreamVersion,
707 });
708 expect(restarted.downloads()).toBe(0);
709 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
710);
711​
712it.effect("keeps the managed install when an update fails its published checksum", () =>
713 Effect.gen(function* () {
714 const h = yield* makeHarness({ responses: upstreamResponses("f".repeat(64)) });
715 yield* h.installation.start;
716 yield* terminalState(h.installation);
717 yield* h.installation.checkForUpdate;
718 yield* h.installation.start;
719 expect(yield* terminalState(h.installation)).toMatchObject({
720 phase: "failed",
721 installedVersion: "0.156.1",
722 message: expect.stringContaining("SHA-256"),
723 });
724 expect((yield* h.installation.resolve()).version).toBe("0.156.1");
725 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
726);
727​
728it.effect("does not install a cached update the manifest has since withdrawn", () =>
729 Effect.gen(function* () {
730 const digest = yield* Digest.Digest;
731 const checksum = Hex.encode(
732 yield* digest.digest(Digest.sha256, upstreamArchive).pipe(Effect.orDie),
733 );
734 let manifest = ModelManifest.BUNDLED_MODEL_MANIFEST;
735 const h = yield* makeHarness({
736 responses: upstreamResponses(checksum),
737 manifestCurrent: Effect.sync(() => manifest),
738 });
739 yield* h.installation.start;
740 yield* terminalState(h.installation);
741 yield* h.installation.checkForUpdate;
742 expect((yield* h.installation.state).version).toBe(upstreamVersion);
743 manifest = {
744 ...manifest,
745 compatibility: [
746 {
747 driver: "codex",
748 t3CodeRange: ">=0.0.42",
749 ranges: [
750 { range: ">=0.160.0", status: "unsupported" },
751 { range: ">=0.156.0 <0.160.0", status: "supported" },
752 ],
753 },
754 ],
755 };
756 const downloads = h.downloads();
757 yield* h.installation.start;
758 expect(yield* terminalState(h.installation)).toMatchObject({
759 phase: "succeeded",
760 installedVersion: "0.156.1",
761 version: "0.156.1",
762 });
763 expect(h.downloads()).toBe(downloads);
764 expect((yield* h.installation.resolve()).version).toBe("0.156.1");
765 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
766);
767​
768it.effect("returns a managed install the manifest withdraws to the pinned release", () =>
769 Effect.gen(function* () {
770 const digest = yield* Digest.Digest;
771 const checksum = Hex.encode(
772 yield* digest.digest(Digest.sha256, upstreamArchive).pipe(Effect.orDie),
773 );
774 let manifest = ModelManifest.BUNDLED_MODEL_MANIFEST;
775 const h = yield* makeHarness({
776 responses: upstreamResponses(checksum),
777 manifestCurrent: Effect.sync(() => manifest),
778 });
779 yield* h.installation.checkForUpdate;
780 yield* h.installation.start;
781 yield* terminalState(h.installation);
782 yield* h.installation.start;
783 expect(yield* terminalState(h.installation)).toMatchObject({
784 installedVersion: upstreamVersion,
785 });
786​
787 manifest = {
788 ...manifest,
789 compatibility: [
790 {
791 driver: "codex",
792 t3CodeRange: ">=0.0.42",
793 ranges: [
794 { range: ">=0.160.0", status: "unsupported" },
795 { range: ">=0.156.0 <0.160.0", status: "supported" },
796 ],
797 },
798 ],
799 };
800 yield* h.installation.checkForUpdate;
801 expect(yield* h.installation.state).toMatchObject({
802 installedVersion: upstreamVersion,
803 version: "0.156.1",
804 });
805 yield* h.installation.start;
806 expect(yield* terminalState(h.installation)).toMatchObject({
807 phase: "succeeded",
808 installedVersion: "0.156.1",
809 version: "0.156.1",
810 });
811 expect((yield* h.installation.resolve()).version).toBe("0.156.1");
812 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
813);
814​
815it.effect.each(["update", "reinstall"] as const)(
816 "rejects withdrawal during $0 validation",
817 (operation) =>
818 Effect.gen(function* () {
819 const digest = yield* Digest.Digest;
820 const checksum = Hex.encode(
821 yield* digest.digest(Digest.sha256, upstreamArchive).pipe(Effect.orDie),
822 );
823 let manifest = ModelManifest.BUNDLED_MODEL_MANIFEST;
824 let withdraw = operation === "update";
825 const h = yield* makeHarness({
826 responses: upstreamResponses(checksum),
827 manifestCurrent: Effect.sync(() => manifest),
828 options: {
829 validate: (_executable, version) =>
830 Effect.sync(() => {
831 if (withdraw && version === upstreamVersion)
832 manifest = {
833 ...ModelManifest.BUNDLED_MODEL_MANIFEST,
834 compatibility: [
835 {
836 driver: "codex",
837 t3CodeRange: ">=0.0.42",
838 ranges: [
839 { range: ">=0.160.0", status: "unsupported" },
840 { range: ">=0.156.0 <0.160.0", status: "supported" },
841 ],
842 },
843 ],
844 };
845 }),
846 },
847 });
848 yield* h.installation.start;
849 yield* terminalState(h.installation);
850 yield* h.installation.checkForUpdate;
851 if (operation === "reinstall") {
852 yield* h.installation.start;
853 expect((yield* terminalState(h.installation)).phase).toBe("succeeded");
854 withdraw = true;
855 }
856 yield* h.installation.start;
857 expect((yield* terminalState(h.installation)).phase).toBe("failed");
858 if (operation === "update") {
859 expect((yield* h.installation.resolve()).version).toBe("0.156.1");
860 } else {
861 expect((yield* h.installation.state).version).toBe("0.156.1");
862 yield* Effect.flip(h.installation.resolve());
863 }
864 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
865);