@devries-cameron20 / t3code-1 / commits / 364f5084d7
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

fix(server): Windows Codex install uses system tar and retries rename (#18523)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Max Weinbach committed Oct 15, 2026 at 13:39 UTC 364f5084d7418e1605220b09de5aaebd46305a73
2 files changed +202 -8
apps/server/src/provider/CodexInstallation.test.ts
+160 -3
@@ -2,16 +2,23 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
2 import * as ModelManifest from "./ModelManifest.ts";
3 import { expect, it } from "@effect/vitest";
4 import * as HostProcess from "@t3tools/shared/HostProcess";
5 +import * as Clock from "effect/Clock";
6 import * as Crypto from "effect/Crypto";
7 import * as Deferred from "effect/Deferred";
8 import * as Effect from "effect/Effect";
9 import * as Hex from "effect/encoding/Hex";
10 import * as FileSystem from "effect/FileSystem";
11 import * as Option from "effect/Option";
12 +import * as Path from "effect/Path";
13 +import * as PlatformError from "effect/PlatformError";
14 import * as Exit from "effect/Exit";
15 +import * as Queue from "effect/Queue";
16 import * as Scope from "effect/Scope";
17 +import * as Sink from "effect/Sink";
18 import * as Stream from "effect/Stream";
19 import { HttpClient, HttpClientResponse } from "effect/http";
20 +import * as TestClock from "effect/testing/TestClock";
21 +import { ChildProcessSpawner } from "effect/process";
22 import * as CodexInstallation from "./CodexInstallation.ts";
23
24 const archive = Buffer.from(
@@ -31,6 +38,10 @@ const makeHarness = Effect.fn("test.makeCodexInstallation")(function* (
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 + // Fails this many renames of an extracted runtime before letting one through.
44 + runtimeRenameFailures?: number;
45 } = {},
46 ) {
47 const fs = yield* FileSystem.FileSystem;
@@ -50,6 +61,30 @@ const makeHarness = Effect.fn("test.makeCodexInstallation")(function* (
61 let downloads = 0;
62 const crypto = yield* Crypto.Crypto;
63 const sha256 = Hex.encode(yield* crypto.digest("SHA-256", archive).pipe(Effect.orDie));
64 + let runtimeRenameFailures = input.runtimeRenameFailures ?? 0;
65 + const failedRenames = yield* Queue.unbounded<void>();
66 + const lockingFs: FileSystem.FileSystem = {
67 + ...fs,
68 + // Suspended so each retry of the same effect is a fresh attempt, like the real rename.
69 + rename: (from, to) =>
70 + Effect.suspend(() =>
71 + /[/\\]runtime$/u.test(from) && runtimeRenameFailures-- > 0
72 + ? Queue.offer(failedRenames, undefined).pipe(
73 + Effect.andThen(
74 + Effect.fail(
75 + PlatformError.systemError({
76 + _tag: "PermissionDenied",
77 + module: "FileSystem",
78 + method: "rename",
79 + pathOrDescriptor: from,
80 + }),
81 + ),
82 + ),
83 + )
84 + : fs.rename(from, to),
85 + ),
86 + };
87 + const spawner = input.spawner ?? (yield* ChildProcessSpawner.ChildProcessSpawner);
88 const installation = yield* CodexInstallation.makeCodexInstallation({
89 baseDir,
90 releaseAsset: { ...asset, sha256 },
@@ -62,9 +97,14 @@ const makeHarness = Effect.fn("test.makeCodexInstallation")(function* (
97 forceRefresh: Effect.succeed(ModelManifest.BUNDLED_MODEL_MANIFEST),
98 refreshInBackground: Effect.void,
99 }),
65 - Effect.provideService(HostProcess.Platform, "darwin"),
100 + Effect.provideService(HostProcess.Platform, input.platform ?? "darwin"),
101 Effect.provideService(HostProcess.Architecture, "arm64"),
67 - Effect.provideService(HostProcess.Environment, { PATH: input.local ? localDirectory : "" }),
102 + Effect.provideService(HostProcess.Environment, {
103 + PATH: input.local ? localDirectory : "",
104 + SystemRoot: "C:\\Windows",
105 + }),
106 + Effect.provideService(FileSystem.FileSystem, lockingFs),
107 + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
108 Effect.provideService(
109 HttpClient.HttpClient,
110 HttpClient.make((request) =>
@@ -81,7 +121,15 @@ const makeHarness = Effect.fn("test.makeCodexInstallation")(function* (
121 ),
122 ),
123 );
84 - return { installation, fs, baseDir, localBinaryPath, probeLog, downloads: () => downloads };
124 + return {
125 + installation,
126 + fs,
127 + baseDir,
128 + localBinaryPath,
129 + probeLog,
130 + failedRenames,
131 + downloads: () => downloads,
132 + };
133 });
134 const terminalState = (installation: CodexInstallation.CodexInstallation["Service"]) =>
135 installation.changes.pipe(
@@ -358,3 +406,112 @@ it("publishes complete packages for all supported platforms", () => {
406 );
407 expect(CodexInstallation.resolveCodexReleaseAsset("linux", "riscv64")).toBeNull();
408 });
409 +// Live clock: staleness compares real filesystem mtimes.
410 +it.live("startup removes only stale staging directories", () =>
411 + Effect.gen(function* () {
412 + const fs = yield* FileSystem.FileSystem;
413 + const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-codex-install-test-" });
414 + const managed = `${baseDir}/tools/codex`;
415 + // utimes takes seconds when given numbers.
416 + const stale = ((yield* Clock.currentTimeMillis) - 25 * 60 * 60_000) / 1000;
417 + for (const name of [".install-stale", ".active-stale", ".install-live"]) {
418 + yield* fs.makeDirectory(`${managed}/${name}`, { recursive: true });
419 + }
420 + yield* fs.utimes(`${managed}/.install-stale`, stale, stale);
421 + yield* fs.utimes(`${managed}/.active-stale`, stale, stale);
422 + const h = yield* makeHarness({ baseDir });
423 + expect(yield* fs.readDirectory(managed)).toEqual([".install-live"]);
424 + expect((yield* h.installation.state).canRemove).toBe(true);
425 +
426 + yield* fs.remove(`${managed}/.install-live`, { recursive: true });
427 + yield* fs.makeDirectory(`${managed}/.install-stale`);
428 + yield* fs.utimes(`${managed}/.install-stale`, stale, stale);
429 + const fresh = yield* makeHarness({ baseDir });
430 + expect(yield* fs.readDirectory(managed)).toEqual([]);
431 + expect((yield* fresh.installation.state).canRemove).toBe(false);
432 + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
433 +);
434 +
435 +const processHandle = (stdout: string) =>
436 + ChildProcessSpawner.makeHandle({
437 + pid: ChildProcessSpawner.ProcessId(1),
438 + exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)),
439 + isRunning: Effect.succeed(false),
440 + kill: () => Effect.void,
441 + unref: Effect.succeed(Effect.void),
442 + stdin: Sink.drain,
443 + stdout: Stream.make(new TextEncoder().encode(stdout)),
444 + stderr: Stream.empty,
445 + all: Stream.empty,
446 + getInputFd: () => Sink.drain,
447 + getOutputFd: () => Stream.empty,
448 + });
449 +const windowsPackage: Record<string, string> = {
450 + "bin/codex.exe": "codex",
451 + "bin/codex-code-mode-host.exe": "host",
452 + "codex-path/rg.exe": "rg",
453 + "codex-package.json": JSON.stringify({
454 + layoutVersion: 1,
455 + version: asset.version,
456 + target: asset.target,
457 + entrypoint: "bin/codex.exe",
458 + }),
459 +};
460 +// Stands in for Windows' bsdtar: CRLF listings, and extraction writes the Windows layout.
461 +const makeWindowsTar = (fs: FileSystem.FileSystem, commands: Array<string>) =>
462 + ChildProcessSpawner.make((command) =>
463 + Effect.gen(function* () {
464 + const { command: executable, args } = command as unknown as {
465 + readonly command: string;
466 + readonly args: ReadonlyArray<string>;
467 + };
468 + commands.push(executable);
469 + const names = Object.keys(windowsPackage);
470 + if (args[0] === "-tzf") return processHandle(`${names.join("\r\n")}\r\n`);
471 + if (args[0] === "-tvzf")
472 + return processHandle(`${names.map((name) => `-rwxr-xr-x 0 0 ${name}`).join("\r\n")}\r\n`);
473 + const runtime = args[3] ?? "";
474 + for (const [name, contents] of Object.entries(windowsPackage)) {
475 + yield* fs.makeDirectory(`${runtime}/${name.split("/").slice(0, -1).join("/")}`, {
476 + recursive: true,
477 + });
478 + yield* fs.writeFileString(`${runtime}/${name}`, contents);
479 + }
480 + return processHandle("");
481 + }).pipe(Effect.orDie),
482 + );
483 +
484 +it.effect("installs on Windows via System32 tar with CRLF output and a locked runtime", () =>
485 + Effect.gen(function* () {
486 + const fs = yield* FileSystem.FileSystem;
487 + const commands: Array<string> = [];
488 + const h = yield* makeHarness({
489 + platform: "win32",
490 + spawner: makeWindowsTar(fs, commands),
491 + runtimeRenameFailures: 3,
492 + });
493 + yield* h.installation.start;
494 + // Each failed attempt has scheduled its retry before the test fiber resumes.
495 + for (let attempt = 0; attempt < 3; attempt++) {
496 + yield* Queue.take(h.failedRenames);
497 + yield* TestClock.adjust("100 millis");
498 + }
499 + expect(yield* terminalState(h.installation)).toMatchObject({ phase: "succeeded" });
500 + expect(commands).toEqual([
501 + "C:\\Windows\\System32\\tar.exe",
502 + "C:\\Windows\\System32\\tar.exe",
503 + "C:\\Windows\\System32\\tar.exe",
504 + ]);
505 + const path = yield* Path.Path;
506 + expect((yield* h.installation.resolve()).executablePath).toBe(
507 + path.join(h.baseDir, "tools", "codex", "0.156.1", "bin", "codex.exe"),
508 + );
509 + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
510 +);
511 +it.effect("does not retry a failed runtime rename outside Windows", () =>
512 + Effect.gen(function* () {
513 + const h = yield* makeHarness({ runtimeRenameFailures: 1 });
514 + yield* h.installation.start;
515 + expect((yield* terminalState(h.installation)).phase).toBe("failed");
516 + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
517 +);
apps/server/src/provider/CodexInstallation.ts
+42 -5
@@ -1,5 +1,6 @@
1 // @effect-diagnostics nodeBuiltinImport:off - Effect has no incremental digest.
2 import { ProviderDriverKind, type ProviderInstallState } from "@t3tools/contracts";
3 +import { cliArchiveTarCommand } from "@t3tools/shared/cliRelease";
4 import * as HostProcess from "@t3tools/shared/HostProcess";
5 import { resolveCommandPath, resolveSpawnCommand } from "@t3tools/shared/shell";
6 import * as Clock from "effect/Clock";
@@ -13,6 +14,7 @@ import * as FileSystem from "effect/FileSystem";
14 import * as Layer from "effect/Layer";
15 import * as Option from "effect/Option";
16 import * as Path from "effect/Path";
17 +import * as Schedule from "effect/Schedule";
18 import * as Schema from "effect/Schema";
19 import * as Scope from "effect/Scope";
20 import * as Semaphore from "effect/Semaphore";
@@ -26,6 +28,7 @@ import * as ModelManifest from "./ModelManifest.ts";
28 import { resolveProviderCompatibility } from "./providerCompatibility.ts";
29
30 const DRIVER = ProviderDriverKind.make("codex");
31 +const STAGING_STALE_AFTER_MS = 24 * 60 * 60_000;
32 const Version = Schema.String.check(Schema.isPattern(/^\d+\.\d+\.\d+(?:-[a-zA-Z0-9.-]+)?$/u));
33 const ActiveRelease = Schema.Struct({ version: Version });
34 const InstalledRelease = Schema.Struct({
@@ -512,8 +515,10 @@ export const makeCodexInstallation = Effect.fn("makeCodexInstallation")(function
515 message: "Extracting Codex.",
516 }) satisfies ProviderInstallState,
517 );
515 - const entries = (yield* runCommand("tar", ["-tzf", archivePath])).trim().split("\n");
516 - const types = (yield* runCommand("tar", ["-tvzf", archivePath])).trim().split("\n");
518 + // Bare `tar` on Windows can resolve to Git's MSYS tar, which reads `C:\...` as a remote host.
519 + const tarCommand = cliArchiveTarCommand(platform, environment);
520 + const entries = (yield* runCommand(tarCommand, ["-tzf", archivePath])).trim().split(/\r?\n/u);
521 + const types = (yield* runCommand(tarCommand, ["-tvzf", archivePath])).trim().split(/\r?\n/u);
522 if (
523 entries.length > 10000 ||
524 entries.length !== types.length ||
@@ -529,7 +534,7 @@ export const makeCodexInstallation = Effect.fn("makeCodexInstallation")(function
534 })
535 )
536 return yield* installationError("extract", "The Codex archive contains unsafe entries.");
532 - yield* runCommand("tar", ["-xzf", archivePath, "-C", runtime]);
537 + yield* runCommand(tarCommand, ["-xzf", archivePath, "-C", runtime]);
538 yield* SubscriptionRef.update(
539 state,
540 (current) =>
@@ -553,7 +558,12 @@ export const makeCodexInstallation = Effect.fn("makeCodexInstallation")(function
558 }),
559 { flag: "wx", mode: 0o600 },
560 );
556 - yield* fs.rename(runtime, destination);
561 + // On Windows, Defender and kernel process rundown can briefly hold the
562 + // verified codex.exe handle open right after `--version` exits.
563 + const renameRuntime = fs.rename(runtime, destination);
564 + yield* platform === "win32"
565 + ? renameRuntime.pipe(Effect.retry({ times: 10, schedule: Schedule.spaced("100 millis") }))
566 + : renameRuntime;
567 yield* activate();
568 },
569 Effect.scoped,
@@ -692,7 +702,34 @@ export const makeCodexInstallation = Effect.fn("makeCodexInstallation")(function
702 );
703
704 yield* Effect.gen(function* () {
695 - const canRemove = yield* fs.exists(managedDirectory);
705 + // Clear staging directories left behind by an interrupted install so they
706 + // neither leak disk nor make an otherwise empty runtime look removable. Two
707 + // servers can share a home, and writes below a staging directory do not
708 + // refresh its mtime, so only directories far older than any real install
709 + // (download is capped at 45 minutes) are treated as abandoned.
710 + let canRemove = false;
711 + if (yield* fs.exists(managedDirectory)) {
712 + const entries = yield* fs
713 + .readDirectory(managedDirectory)
714 + .pipe(Effect.orElseSucceed((): ReadonlyArray<string> => []));
715 + const now = yield* Clock.currentTimeMillis;
716 + for (const entry of entries) {
717 + if (!entry.startsWith(".install-") && !entry.startsWith(".active-")) continue;
718 + const target = path.join(managedDirectory, entry);
719 + const info = yield* fs.stat(target).pipe(Effect.option);
720 + if (Option.isNone(info)) continue;
721 + const modifiedAt = Option.match(info.value.mtime, {
722 + onNone: () => now,
723 + onSome: (date) => date.getTime(),
724 + });
725 + if (now - modifiedAt < STAGING_STALE_AFTER_MS) continue;
726 + yield* fs.remove(target, { recursive: true, force: true }).pipe(Effect.ignore);
727 + }
728 + // The empty root itself stays: deleting it could race another server
729 + // creating a staging directory inside. An unreadable root stays removable.
730 + const remaining = yield* fs.readDirectory(managedDirectory).pipe(Effect.option);
731 + canRemove = Option.isNone(remaining) || remaining.value.length > 0;
732 + }
733 yield* SubscriptionRef.update(state, (current) => ({ ...current, canRemove }));
734 if (yield* reuseLocal()) return;
735 if (!(yield* fs.exists(activePath))) return;