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

CodexInstallation.test.ts

604 lines24.5 KB

1import * as NodeServices from "@effect/platform-node/NodeServices";
2import * as ModelManifest from "./ModelManifest.ts";
3import { expect, it } from "@effect/vitest";
4import * as HostProcess from "@t3tools/shared/HostProcess";
5import * as Clock from "effect/Clock";
6import * as Crypto from "effect/Crypto";
7import * as Deferred from "effect/Deferred";
8import * as Effect from "effect/Effect";
9import * as Hex from "effect/encoding/Hex";
10import * as FileSystem from "effect/FileSystem";
11import * as Option from "effect/Option";
12import * as Path from "effect/Path";
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 Sink from "effect/Sink";
18import * as Stream from "effect/Stream";
19import { HttpClient, HttpClientResponse } from "effect/http";
20import * as TestClock from "effect/testing/TestClock";
21import { ChildProcess, ChildProcessSpawner } from "effect/process";
22import * as CodexInstallation from "./CodexInstallation.ts";
23​
24const archive = Buffer.from(
25 "H4sIAAAAAAAC/+3W0W6DIBQGYB/FcD0sKNSkD7J7aom6tmAQtzXL3n3QZM3qdWVt+n8XoCckJp78wLY3q8bu9Ge2HBbUUp7nYD4H8s9zrNdSsCxnWQLT6JULn8ye09K9h/u2/c0/jSM9xqGzo0+bf3Gdf15WQiD/Kdy61/CA+z8dlO9Wrv2387+c5Z9VZY38p7BY0+Gh8t/sVauLt9Ga9Pnnop7ln1e4/6fxRQ7qZCf/qt3YW0M2OX/JyfvljbCCy3XBSaiGH9VqH4tKuaZbC6qG4aDpTrmP3sQV2nh3Gmxvzqsud0vyjaABAAAAAAAAAAAAAAAk8gOq19rvACgAAA==",
26 "base64",
27);
28const asset = {
29 version: "0.156.1",
30 target: "aarch64-apple-darwin",
31 url: "https://github.com/openai/codex/releases/download/test/package.tar.gz",
32 archiveBytes: archive.length,
33};
34const makeHarness = Effect.fn("test.makeCodexInstallation")(function* (
35 input: {
36 options?: Partial<CodexInstallation.CodexInstallationOptions>;
37 manifestCurrent?: Effect.Effect<ModelManifest.ModelManifestData>;
38 body?: Stream.Stream<Uint8Array>;
39 baseDir?: string;
40 local?: { version: string; appServerFails?: boolean; versionFails?: boolean };
41 platform?: NodeJS.Platform;
42 spawner?: ChildProcessSpawner.ChildProcessSpawner["Service"];
43 runtimeRenameFailures?: number;
44 } = {},
45) {
46 const fs = yield* FileSystem.FileSystem;
47 const baseDir =
48 input.baseDir ?? (yield* fs.makeTempDirectoryScoped({ prefix: "t3-codex-install-test-" }));
49 const localDirectory = `${baseDir}/local`;
50 const localBinaryPath = `${localDirectory}/codex${input.platform === "win32" ? ".exe" : ""}`;
51 const probeLog = `${baseDir}/local-probes.txt`;
52 if (input.local) {
53 yield* fs.makeDirectory(localDirectory, { recursive: true });
54 yield* fs.writeFileString(
55 localBinaryPath,
56 `#!/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`,
57 { mode: 0o755 },
58 );
59 }
60 let downloads = 0;
61 const crypto = yield* Crypto.Crypto;
62 const sha256 = Hex.encode(yield* crypto.digest("SHA-256", archive).pipe(Effect.orDie));
63 let runtimeRenameFailures = input.runtimeRenameFailures ?? 0;
64 const failedRenames = yield* Queue.unbounded<void>();
65 const lockingFs: FileSystem.FileSystem = {
66 ...fs,
67 // Suspended so each retry of the same effect is a fresh attempt, like the real rename.
68 rename: (from, to) =>
69 Effect.suspend(() =>
70 /[/\\]runtime$/u.test(from) && runtimeRenameFailures-- > 0
71 ? Queue.offer(failedRenames, undefined).pipe(
72 Effect.andThen(
73 Effect.fail(
74 PlatformError.systemError({
75 _tag: "PermissionDenied",
76 module: "FileSystem",
77 method: "rename",
78 pathOrDescriptor: from,
79 }),
80 ),
81 ),
82 )
83 : fs.rename(from, to),
84 ),
85 };
86 const spawner = input.spawner ?? (yield* ChildProcessSpawner.ChildProcessSpawner);
87 const installation = yield* CodexInstallation.makeCodexInstallation({
88 baseDir,
89 releaseAsset: { ...asset, sha256 },
90 validate: () => Effect.void,
91 ...input.options,
92 }).pipe(
93 Effect.provideService(ModelManifest.ModelManifest, {
94 current: input.manifestCurrent ?? Effect.succeed(ModelManifest.BUNDLED_MODEL_MANIFEST),
95 refresh: Effect.succeed(ModelManifest.BUNDLED_MODEL_MANIFEST),
96 forceRefresh: Effect.succeed(ModelManifest.BUNDLED_MODEL_MANIFEST),
97 refreshInBackground: Effect.void,
98 }),
99 Effect.provideService(HostProcess.Platform, input.platform ?? "darwin"),
100 Effect.provideService(HostProcess.Architecture, "arm64"),
101 Effect.provideService(HostProcess.Environment, {
102 PATH: input.local ? localDirectory : "",
103 SystemRoot: "C:\\Windows",
104 }),
105 Effect.provideService(FileSystem.FileSystem, lockingFs),
106 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
107 Effect.provideService(
108 HttpClient.HttpClient,
109 HttpClient.make((request) =>
110 Effect.sync(() => {
111 downloads++;
112 return Object.defineProperty(
113 HttpClientResponse.fromWeb(request, new Response(null)),
114 "stream",
115 {
116 value: input.body ?? Stream.succeed(archive),
117 },
118 );
119 }),
120 ),
121 ),
122 );
123 return {
124 installation,
125 fs,
126 baseDir,
127 localBinaryPath,
128 probeLog,
129 failedRenames,
130 downloads: () => downloads,
131 };
132});
133const terminalState = (installation: CodexInstallation.CodexInstallation["Service"]) =>
134 installation.changes.pipe(
135 Stream.filter((state) => ["succeeded", "failed", "cancelled"].includes(state.phase)),
136 Stream.runHead,
137 Effect.map(Option.getOrThrow),
138 );
139​
140it.effect.each(["0.156.0", "0.156.1", "0.156.2", "0.157.0"])(
141 "reuses installed Codex %s without downloading or taking ownership of it",
142 (version) =>
143 Effect.gen(function* () {
144 const h = yield* makeHarness({ local: { version } });
145 expect(yield* h.installation.start).toMatchObject({
146 source: "local",
147 phase: "succeeded",
148 installedVersion: version,
149 executablePath: h.localBinaryPath,
150 canRemove: false,
151 });
152 expect(yield* h.installation.resolve()).toMatchObject({
153 source: "local",
154 executablePath: h.localBinaryPath,
155 managedVersionDirectory: null,
156 version,
157 });
158 yield* h.installation.acquire().pipe(Effect.scoped);
159 expect(h.downloads()).toBe(0);
160 expect(yield* h.fs.exists(h.installation.managedDirectory)).toBe(false);
161 expect((yield* h.fs.readFileString(h.probeLog)).trim().split("\n")).toEqual([
162 "--version",
163 "app-server --help",
164 ]);
165 yield* h.installation.remove();
166 expect(yield* h.fs.exists(h.localBinaryPath)).toBe(true);
167 expect((yield* h.installation.state).source).toBe("local");
168 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
169);
170it.effect.each([
171 { version: "0.128.9" },
172 { version: "0.145.0" },
173 { version: "0.155.1" },
174 { version: "0.155.9" },
175 { version: "0.156.1-alpha.1" },
176 { version: "unknown" },
177 { version: "0.156.1", appServerFails: true },
178 { version: "0.156.1", versionFails: true },
179])("downloads the pinned release when the local CLI is unsupported or broken: %j", (local) =>
180 Effect.gen(function* () {
181 const h = yield* makeHarness({ local });
182 expect((yield* h.installation.state).installedVersion).toBeNull();
183 yield* h.installation.start;
184 const installed = yield* terminalState(h.installation);
185 expect(installed.phase).toBe("succeeded");
186 const executable = yield* h.installation.resolve();
187 expect(executable.source).toBe("managed");
188 expect(installed.executablePath).toBe(executable.executablePath);
189 expect(h.downloads()).toBe(1);
190 expect(yield* h.fs.exists(h.localBinaryPath)).toBe(true);
191 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
192);
193it.effect("falls back to a managed download when the reused local executable disappears", () =>
194 Effect.gen(function* () {
195 const h = yield* makeHarness({ local: { version: "0.156.1" } });
196 expect((yield* h.installation.resolve()).source).toBe("local");
197 yield* h.fs.remove(h.localBinaryPath);
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 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
203);
204​
205const compileNative = Effect.fn("test.compileNative")(function* (
206 executablePath: string,
207 source: string,
208) {
209 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
210 const compiler = yield* spawner.spawn(
211 ChildProcess.make("cc", ["-x", "c", "-", "-o", executablePath], {
212 stdin: Stream.make(new TextEncoder().encode(source)),
213 stdout: "inherit",
214 stderr: "inherit",
215 }),
216 );
217 expect(yield* compiler.exitCode).toBe(0);
218}, Effect.scoped);
219​
220it.effect.each([
221 { withHost: false, marker: null },
222 { withHost: true, marker: null },
223 { withHost: false, marker: ".bunx" },
224 { withHost: false, marker: ".shim" },
225])("requires the native host or a known package-manager launcher: %j", ({ withHost, marker }) =>
226 Effect.gen(function* () {
227 const h = yield* makeHarness({
228 local: { version: "0.156.1" },
229 platform: marker ? "win32" : "darwin",
230 });
231 yield* compileNative(
232 h.localBinaryPath,
233 `#include <stdio.h>
234#include <string.h>
235int main(int argc, char **argv) {
236 if (argc == 2 && strcmp(argv[1], "--version") == 0) {
237 puts("codex-cli 0.156.1");
238 return 0;
239 }
240 return !(argc == 3 && strcmp(argv[1], "app-server") == 0 && strcmp(argv[2], "--help") == 0);
242`,
243 );
244 if (withHost) {
245 const packageDirectory = `${h.baseDir}/package`;
246 yield* h.fs.makeDirectory(packageDirectory);
247 yield* h.fs.rename(h.localBinaryPath, `${packageDirectory}/codex`);
248 yield* h.fs.copyFile(`${packageDirectory}/codex`, `${packageDirectory}/codex-code-mode-host`);
249 yield* h.fs.symlink(`${packageDirectory}/codex`, h.localBinaryPath);
250 }
251 if (marker) {
252 yield* h.fs.writeFileString(
253 h.localBinaryPath.replace(/\.exe$/u, marker),
254 "launcher metadata",
255 );
256 }
257 const reusesLocal = withHost || marker !== null;
258 const started = yield* h.installation.start;
259 if (reusesLocal) {
260 expect(started).toMatchObject({
261 source: "local",
262 phase: "succeeded",
263 executablePath: h.localBinaryPath,
264 });
265 }
266 expect((yield* terminalState(h.installation)).phase).toBe("succeeded");
267 expect((yield* h.installation.resolve()).source).toBe(reusesLocal ? "local" : "managed");
268 expect(h.downloads()).toBe(reusesLocal ? 0 : 1);
269 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
270);
271​
272it.effect("rechecks compatibility after the local executable is replaced", () =>
273 Effect.gen(function* () {
274 const h = yield* makeHarness({ local: { version: "0.156.1" } });
275 expect((yield* h.installation.resolve()).source).toBe("local");
276 yield* h.fs.remove(h.localBinaryPath);
277 yield* h.fs.writeFileString(h.localBinaryPath, "#!/bin/sh\nprintf 'codex-cli 0.128.9\\n'\n", {
278 mode: 0o755,
279 });
280 yield* h.installation.start;
281 expect((yield* terminalState(h.installation)).phase).toBe("succeeded");
282 expect((yield* h.installation.resolve()).source).toBe("managed");
283 expect(h.downloads()).toBe(1);
284 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
285);
286​
287it.effect("rechecks a cached local executable when the shared manifest policy changes", () =>
288 Effect.gen(function* () {
289 let manifest = ModelManifest.BUNDLED_MODEL_MANIFEST;
290 const h = yield* makeHarness({
291 local: { version: "0.156.0" },
292 manifestCurrent: Effect.sync(() => manifest),
293 });
294 expect((yield* h.installation.resolve()).source).toBe("local");
295 manifest = {
296 ...manifest,
297 compatibility: [
298 {
299 driver: "codex",
300 t3CodeRange: ">=0.0.42",
301 ranges: [
302 { range: ">=0.156.1", status: "supported" },
303 { range: "<0.156.1", status: "broken" },
304 ],
305 },
306 ],
307 };
308 yield* h.installation.start;
309 expect((yield* terminalState(h.installation)).phase).toBe("succeeded");
310 expect((yield* h.installation.resolve()).source).toBe("managed");
311 expect(h.downloads()).toBe(1);
312 expect((yield* h.fs.readFileString(h.probeLog)).trim().split("\n")).toEqual([
313 "--version",
314 "app-server --help",
315 ]);
316 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
317);
318​
319it.effect("uses bundled Codex compatibility when the remote manifest omits its policy", () =>
320 Effect.gen(function* () {
321 const h = yield* makeHarness({
322 local: { version: "0.156.0" },
323 manifestCurrent: Effect.succeed({
324 ...ModelManifest.BUNDLED_MODEL_MANIFEST,
325 compatibility: [],
326 }),
327 });
328 expect((yield* h.installation.start).source).toBe("local");
329 expect(h.downloads()).toBe(0);
330 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
331);
332​
333it.effect.each([
334 { kind: "script", name: "volta-shim" },
335 { kind: "native", name: "volta-shim" },
336 { kind: "native", name: "mise" },
337 { kind: "native", name: "aqua-proxy" },
338])("preserves the invoked name of $kind $name launcher symlinks", ({ kind, name }) =>
339 Effect.gen(function* () {
340 const h = yield* makeHarness({ local: { version: "0.156.1" } });
341 const launcher = `${h.baseDir}/${name}`;
342 if (kind === "native") {
343 const payload = `${h.baseDir}/codex.js`;
344 yield* h.fs.rename(h.localBinaryPath, payload);
345 yield* compileNative(
346 launcher,
347 `#include <string.h>
348#include <unistd.h>
349int main(int argc, char **argv) {
350 const char *name = strrchr(argv[0], '/');
351 if (strcmp(name ? name + 1 : argv[0], "codex") != 0) return 1;
352 execv(${JSON.stringify(payload)}, argv);
353 return 1;
355`,
356 );
357 } else {
358 yield* h.fs.writeFileString(
359 launcher,
360 '#!/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',
361 { mode: 0o755 },
362 );
363 yield* h.fs.remove(h.localBinaryPath);
364 }
365 yield* h.fs.symlink(launcher, h.localBinaryPath);
366 expect(yield* h.installation.start).toMatchObject({ source: "local", phase: "succeeded" });
367 expect((yield* h.installation.resolve()).executablePath).toBe(h.localBinaryPath);
368 expect(h.downloads()).toBe(0);
369 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
370);
371​
372it.effect(
373 "installs the complete verified package in tools/codex/version and survives a restart",
374 () =>
375 Effect.gen(function* () {
376 const { installation, fs, baseDir } = yield* makeHarness();
377 yield* installation.start;
378 expect((yield* terminalState(installation)).phase).toBe("succeeded");
379 const executable = yield* installation.resolve();
380 expect(executable.executablePath).toBe(`${baseDir}/tools/codex/0.156.1/bin/codex`);
381 expect(
382 yield* fs.readFileString(`${executable.managedVersionDirectory}/bin/codex-code-mode-host`),
383 ).toBe("host");
384 expect(yield* fs.readFileString(`${executable.managedVersionDirectory}/codex-path/rg`)).toBe(
385 "rg",
386 );
387 const restarted = yield* makeHarness({ baseDir });
388 expect((yield* restarted.installation.resolve()).version).toBe("0.156.1");
389 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
390);
391​
392it.effect("requires an update before running an older activated managed installation", () =>
393 Effect.gen(function* () {
394 const first = yield* makeHarness();
395 yield* first.installation.start;
396 yield* terminalState(first.installation);
397 const executable = yield* first.installation.resolve();
398 const oldDirectory = `${first.installation.managedDirectory}/0.155.1`;
399 yield* first.fs.rename(executable.managedVersionDirectory!, oldDirectory);
400 for (const name of ["codex-package.json", ".install-complete.json"]) {
401 const file = `${oldDirectory}/${name}`;
402 yield* first.fs.writeFileString(
403 file,
404 (yield* first.fs.readFileString(file)).replaceAll("0.156.1", "0.155.1"),
405 );
406 }
407 yield* first.fs.writeFileString(
408 `${first.installation.managedDirectory}/active.json`,
409 '{"version":"0.155.1"}',
410 );
411 const restarted = yield* makeHarness({ baseDir: first.baseDir });
412 expect((yield* Effect.flip(restarted.installation.resolve())).detail).toContain(
413 "outside the supported range",
414 );
415 yield* restarted.installation.start;
416 expect((yield* terminalState(restarted.installation)).phase).toBe("succeeded");
417 expect((yield* restarted.installation.resolve()).version).toBe("0.156.1");
418 expect(restarted.downloads()).toBe(1);
419 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
420);
421​
422it.effect("rejects corrupted downloads without publishing a runtime", () =>
423 Effect.gen(function* () {
424 const { installation, fs } = yield* makeHarness({
425 options: { releaseAsset: { ...asset, sha256: "0".repeat(64) } },
426 });
427 yield* installation.start;
428 const state = yield* terminalState(installation);
429 expect(state.phase).toBe("failed");
430 expect(state.message).toContain("SHA-256");
431 expect(yield* fs.exists(`${installation.managedDirectory}/active.json`)).toBe(false);
432 expect(yield* fs.exists(`${installation.managedDirectory}/0.156.1`)).toBe(false);
433 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
434);
435​
436it.effect("cancels an in-flight download and cleans the staging directory", () =>
437 Effect.gen(function* () {
438 const downloading = yield* Deferred.make<void>();
439 const body = Stream.fromEffect(
440 Deferred.succeed(downloading, undefined).pipe(Effect.andThen(Effect.never)),
441 );
442 const { installation, fs } = yield* makeHarness({ body });
443 const started = yield* installation.start;
444 yield* Deferred.await(downloading);
445 expect((yield* installation.cancel(started.operationId!)).phase).toBe("cancelled");
446 expect(
447 (yield* fs.readDirectory(installation.managedDirectory)).filter((name) =>
448 name.startsWith(".install-"),
449 ),
450 ).toEqual([]);
451 expect(yield* fs.exists(`${installation.managedDirectory}/active.json`)).toBe(false);
452 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
453);
454​
455it.effect("protects active process leases and removes the runtime after release", () =>
456 Effect.gen(function* () {
457 const { installation, fs } = yield* makeHarness();
458 yield* installation.start;
459 yield* terminalState(installation);
460 const leaseScope = yield* Scope.make();
461 yield* installation.acquire().pipe(Effect.provideService(Scope.Scope, leaseScope));
462 expect((yield* Effect.flip(installation.remove())).detail).toContain("Stop Codex sessions");
463 yield* Scope.close(leaseScope, Exit.void);
464 yield* installation.remove();
465 expect(yield* fs.exists(installation.managedDirectory)).toBe(false);
466 expect((yield* installation.state).installedVersion).toBeNull();
467 expect((yield* installation.state).executablePath).toBeNull();
468 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
469);
470​
471it.effect("keeps an activated runtime when a later update fails verification", () =>
472 Effect.gen(function* () {
473 const first = yield* makeHarness();
474 yield* first.installation.start;
475 yield* terminalState(first.installation);
476 const update = yield* makeHarness({
477 baseDir: first.baseDir,
478 options: { releaseAsset: { ...asset, version: "0.156.2", sha256: "0".repeat(64) } },
479 });
480 expect((yield* update.installation.state).executablePath).toBe(
481 (yield* first.installation.resolve()).executablePath,
482 );
483 yield* update.installation.start;
484 expect((yield* terminalState(update.installation)).phase).toBe("failed");
485 expect((yield* update.installation.resolve()).version).toBe("0.156.1");
486 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
487);
488​
489it("publishes complete packages for all supported platforms", () => {
490 for (const platform of ["darwin", "linux", "win32"] as const)
491 for (const arch of ["x64", "arm64"])
492 expect(CodexInstallation.resolveCodexReleaseAsset(platform, arch)?.url).toContain(
493 "codex-package-",
494 );
495 expect(CodexInstallation.resolveCodexReleaseAsset("linux", "riscv64")).toBeNull();
496});
497// Live clock: staleness compares real filesystem mtimes.
498it.live("startup removes only stale staging directories", () =>
499 Effect.gen(function* () {
500 const fs = yield* FileSystem.FileSystem;
501 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-codex-install-test-" });
502 const managed = `${baseDir}/tools/codex`;
503 const stale = ((yield* Clock.currentTimeMillis) - 25 * 60 * 60_000) / 1000;
504 for (const name of [".install-stale", ".active-stale", ".install-live"]) {
505 yield* fs.makeDirectory(`${managed}/${name}`, { recursive: true });
506 }
507 yield* fs.utimes(`${managed}/.install-stale`, stale, stale);
508 yield* fs.utimes(`${managed}/.active-stale`, stale, stale);
509 const h = yield* makeHarness({ baseDir });
510 expect(yield* fs.readDirectory(managed)).toEqual([".install-live"]);
511 expect((yield* h.installation.state).canRemove).toBe(true);
512​
513 yield* fs.remove(`${managed}/.install-live`, { recursive: true });
514 yield* fs.makeDirectory(`${managed}/.install-stale`);
515 yield* fs.utimes(`${managed}/.install-stale`, stale, stale);
516 const fresh = yield* makeHarness({ baseDir });
517 expect(yield* fs.readDirectory(managed)).toEqual([]);
518 expect((yield* fresh.installation.state).canRemove).toBe(false);
519 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
520);
521​
522const processHandle = (stdout: string) =>
523 ChildProcessSpawner.makeHandle({
524 pid: ChildProcessSpawner.ProcessId(1),
525 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)),
526 isRunning: Effect.succeed(false),
527 kill: () => Effect.void,
528 unref: Effect.succeed(Effect.void),
529 stdin: Sink.drain,
530 stdout: Stream.make(new TextEncoder().encode(stdout)),
531 stderr: Stream.empty,
532 all: Stream.empty,
533 getInputFd: () => Sink.drain,
534 getOutputFd: () => Stream.empty,
535 });
536const windowsPackage: Record<string, string> = {
537 "bin/codex.exe": "codex",
538 "bin/codex-code-mode-host.exe": "host",
539 "codex-path/rg.exe": "rg",
540 "codex-package.json": JSON.stringify({
541 layoutVersion: 1,
542 version: asset.version,
543 target: asset.target,
544 entrypoint: "bin/codex.exe",
545 }),
546};
547// Stands in for Windows' bsdtar: CRLF listings, and extraction writes the Windows layout.
548const makeWindowsTar = (fs: FileSystem.FileSystem, commands: Array<string>) =>
549 ChildProcessSpawner.make((command) =>
550 Effect.gen(function* () {
551 const { command: executable, args } = command as unknown as {
552 readonly command: string;
553 readonly args: ReadonlyArray<string>;
554 };
555 commands.push(executable);
556 const names = Object.keys(windowsPackage);
557 if (args[0] === "-tzf") return processHandle(`${names.join("\r\n")}\r\n`);
558 if (args[0] === "-tvzf")
559 return processHandle(`${names.map((name) => `-rwxr-xr-x 0 0 ${name}`).join("\r\n")}\r\n`);
560 const runtime = args[3] ?? "";
561 for (const [name, contents] of Object.entries(windowsPackage)) {
562 yield* fs.makeDirectory(`${runtime}/${name.split("/").slice(0, -1).join("/")}`, {
563 recursive: true,
564 });
565 yield* fs.writeFileString(`${runtime}/${name}`, contents);
566 }
567 return processHandle("");
568 }).pipe(Effect.orDie),
569 );
570​
571it.effect("installs on Windows via System32 tar with CRLF output and a locked runtime", () =>
572 Effect.gen(function* () {
573 const fs = yield* FileSystem.FileSystem;
574 const commands: Array<string> = [];
575 const h = yield* makeHarness({
576 platform: "win32",
577 spawner: makeWindowsTar(fs, commands),
578 runtimeRenameFailures: 3,
579 });
580 yield* h.installation.start;
581 // Each failed attempt has scheduled its retry before the test fiber resumes.
582 for (let attempt = 0; attempt < 3; attempt++) {
583 yield* Queue.take(h.failedRenames);
584 yield* TestClock.adjust("100 millis");
585 }
586 expect(yield* terminalState(h.installation)).toMatchObject({ phase: "succeeded" });
587 expect(commands).toEqual([
588 "C:\\Windows\\System32\\tar.exe",
589 "C:\\Windows\\System32\\tar.exe",
590 "C:\\Windows\\System32\\tar.exe",
591 ]);
592 const path = yield* Path.Path;
593 expect((yield* h.installation.resolve()).executablePath).toBe(
594 path.join(h.baseDir, "tools", "codex", "0.156.1", "bin", "codex.exe"),
595 );
596 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
597);
598it.effect("does not retry a failed runtime rename outside Windows", () =>
599 Effect.gen(function* () {
600 const h = yield* makeHarness({ runtimeRenameFailures: 1 });
601 yield* h.installation.start;
602 expect((yield* terminalState(h.installation)).phase).toBe("failed");
603 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
604);