TypeScript
fix(server): Windows Codex install uses system tar and retries rename (#18523)
Max Weinbach364f5084d741
diff --git a/apps/server/src/provider/CodexInstallation.test.ts b/apps/server/src/provider/CodexInstallation.test.tsindex abc67ad55ea..045d005f87b 100644--- a/apps/server/src/provider/CodexInstallation.test.ts+++ b/apps/server/src/provider/CodexInstallation.test.ts@@ -2,16 +2,23 @@ import * as NodeServices from "@effect/platform-node/NodeServices";import * as ModelManifest from "./ModelManifest.ts";import { expect, it } from "@effect/vitest";import * as HostProcess from "@t3tools/shared/HostProcess";+import * as Clock from "effect/Clock";import * as Crypto from "effect/Crypto";import * as Deferred from "effect/Deferred";import * as Effect from "effect/Effect";import * as Hex from "effect/encoding/Hex";import * as FileSystem from "effect/FileSystem";import * as Option from "effect/Option";+import * as Path from "effect/Path";+import * as PlatformError from "effect/PlatformError";import * as Exit from "effect/Exit";+import * as Queue from "effect/Queue";import * as Scope from "effect/Scope";+import * as Sink from "effect/Sink";import * as Stream from "effect/Stream";import { HttpClient, HttpClientResponse } from "effect/http";+import * as TestClock from "effect/testing/TestClock";+import { ChildProcessSpawner } from "effect/process";import * as CodexInstallation from "./CodexInstallation.ts";const archive = Buffer.from(@@ -31,6 +38,10 @@ const makeHarness = Effect.fn("test.makeCodexInstallation")(function* (body?: Stream.Stream<Uint8Array>;baseDir?: string;local?: { version: string; appServerFails?: boolean; versionFails?: boolean };+ platform?: NodeJS.Platform;+ spawner?: ChildProcessSpawner.ChildProcessSpawner["Service"];+ // Fails this many renames of an extracted runtime before letting one through.+ runtimeRenameFailures?: number;} = {},) {const fs = yield* FileSystem.FileSystem;@@ -50,6 +61,30 @@ const makeHarness = Effect.fn("test.makeCodexInstallation")(function* (let downloads = 0;const crypto = yield* Crypto.Crypto;const sha256 = Hex.encode(yield* crypto.digest("SHA-256", archive).pipe(Effect.orDie));+ let runtimeRenameFailures = input.runtimeRenameFailures ?? 0;+ const failedRenames = yield* Queue.unbounded<void>();+ const lockingFs: FileSystem.FileSystem = {+ ...fs,+ // Suspended so each retry of the same effect is a fresh attempt, like the real rename.+ rename: (from, to) =>+ Effect.suspend(() =>+ /[/\\]runtime$/u.test(from) && runtimeRenameFailures-- > 0+ ? Queue.offer(failedRenames, undefined).pipe(+ Effect.andThen(+ Effect.fail(+ PlatformError.systemError({+ _tag: "PermissionDenied",+ module: "FileSystem",+ method: "rename",+ pathOrDescriptor: from,+ }),+ ),+ ),+ )+ : fs.rename(from, to),+ ),+ };+ const spawner = input.spawner ?? (yield* ChildProcessSpawner.ChildProcessSpawner);const installation = yield* CodexInstallation.makeCodexInstallation({baseDir,releaseAsset: { ...asset, sha256 },@@ -62,9 +97,14 @@ const makeHarness = Effect.fn("test.makeCodexInstallation")(function* (forceRefresh: Effect.succeed(ModelManifest.BUNDLED_MODEL_MANIFEST),refreshInBackground: Effect.void,}),- Effect.provideService(HostProcess.Platform, "darwin"),+ Effect.provideService(HostProcess.Platform, input.platform ?? "darwin"),Effect.provideService(HostProcess.Architecture, "arm64"),- Effect.provideService(HostProcess.Environment, { PATH: input.local ? localDirectory : "" }),+ Effect.provideService(HostProcess.Environment, {+ PATH: input.local ? localDirectory : "",+ SystemRoot: "C:\\Windows",+ }),+ Effect.provideService(FileSystem.FileSystem, lockingFs),+ Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),Effect.provideService(HttpClient.HttpClient,HttpClient.make((request) =>@@ -81,7 +121,15 @@ const makeHarness = Effect.fn("test.makeCodexInstallation")(function* (),),);- return { installation, fs, baseDir, localBinaryPath, probeLog, downloads: () => downloads };+ return {+ installation,+ fs,+ baseDir,+ localBinaryPath,+ probeLog,+ failedRenames,+ downloads: () => downloads,+ };});const terminalState = (installation: CodexInstallation.CodexInstallation["Service"]) =>installation.changes.pipe(@@ -358,3 +406,112 @@ it("publishes complete packages for all supported platforms", () => {);expect(CodexInstallation.resolveCodexReleaseAsset("linux", "riscv64")).toBeNull();});+// Live clock: staleness compares real filesystem mtimes.+it.live("startup removes only stale staging directories", () =>+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-codex-install-test-" });+ const managed = `${baseDir}/tools/codex`;+ // utimes takes seconds when given numbers.+ const stale = ((yield* Clock.currentTimeMillis) - 25 * 60 * 60_000) / 1000;+ for (const name of [".install-stale", ".active-stale", ".install-live"]) {+ yield* fs.makeDirectory(`${managed}/${name}`, { recursive: true });+ }+ yield* fs.utimes(`${managed}/.install-stale`, stale, stale);+ yield* fs.utimes(`${managed}/.active-stale`, stale, stale);+ const h = yield* makeHarness({ baseDir });+ expect(yield* fs.readDirectory(managed)).toEqual([".install-live"]);+ expect((yield* h.installation.state).canRemove).toBe(true);++ yield* fs.remove(`${managed}/.install-live`, { recursive: true });+ yield* fs.makeDirectory(`${managed}/.install-stale`);+ yield* fs.utimes(`${managed}/.install-stale`, stale, stale);+ const fresh = yield* makeHarness({ baseDir });+ expect(yield* fs.readDirectory(managed)).toEqual([]);+ expect((yield* fresh.installation.state).canRemove).toBe(false);+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),+);++const processHandle = (stdout: string) =>+ ChildProcessSpawner.makeHandle({+ pid: ChildProcessSpawner.ProcessId(1),+ exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)),+ isRunning: Effect.succeed(false),+ kill: () => Effect.void,+ unref: Effect.succeed(Effect.void),+ stdin: Sink.drain,+ stdout: Stream.make(new TextEncoder().encode(stdout)),+ stderr: Stream.empty,+ all: Stream.empty,+ getInputFd: () => Sink.drain,+ getOutputFd: () => Stream.empty,+ });+const windowsPackage: Record<string, string> = {+ "bin/codex.exe": "codex",+ "bin/codex-code-mode-host.exe": "host",+ "codex-path/rg.exe": "rg",+ "codex-package.json": JSON.stringify({+ layoutVersion: 1,+ version: asset.version,+ target: asset.target,+ entrypoint: "bin/codex.exe",+ }),+};+// Stands in for Windows' bsdtar: CRLF listings, and extraction writes the Windows layout.+const makeWindowsTar = (fs: FileSystem.FileSystem, commands: Array<string>) =>+ ChildProcessSpawner.make((command) =>+ Effect.gen(function* () {+ const { command: executable, args } = command as unknown as {+ readonly command: string;+ readonly args: ReadonlyArray<string>;+ };+ commands.push(executable);+ const names = Object.keys(windowsPackage);+ if (args[0] === "-tzf") return processHandle(`${names.join("\r\n")}\r\n`);+ if (args[0] === "-tvzf")+ return processHandle(`${names.map((name) => `-rwxr-xr-x 0 0 ${name}`).join("\r\n")}\r\n`);+ const runtime = args[3] ?? "";+ for (const [name, contents] of Object.entries(windowsPackage)) {+ yield* fs.makeDirectory(`${runtime}/${name.split("/").slice(0, -1).join("/")}`, {+ recursive: true,+ });+ yield* fs.writeFileString(`${runtime}/${name}`, contents);+ }+ return processHandle("");+ }).pipe(Effect.orDie),+ );++it.effect("installs on Windows via System32 tar with CRLF output and a locked runtime", () =>+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const commands: Array<string> = [];+ const h = yield* makeHarness({+ platform: "win32",+ spawner: makeWindowsTar(fs, commands),+ runtimeRenameFailures: 3,+ });+ yield* h.installation.start;+ // Each failed attempt has scheduled its retry before the test fiber resumes.+ for (let attempt = 0; attempt < 3; attempt++) {+ yield* Queue.take(h.failedRenames);+ yield* TestClock.adjust("100 millis");+ }+ expect(yield* terminalState(h.installation)).toMatchObject({ phase: "succeeded" });+ expect(commands).toEqual([+ "C:\\Windows\\System32\\tar.exe",+ "C:\\Windows\\System32\\tar.exe",+ "C:\\Windows\\System32\\tar.exe",+ ]);+ const path = yield* Path.Path;+ expect((yield* h.installation.resolve()).executablePath).toBe(+ path.join(h.baseDir, "tools", "codex", "0.156.1", "bin", "codex.exe"),+ );+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),+);+it.effect("does not retry a failed runtime rename outside Windows", () =>+ Effect.gen(function* () {+ const h = yield* makeHarness({ runtimeRenameFailures: 1 });+ yield* h.installation.start;+ expect((yield* terminalState(h.installation)).phase).toBe("failed");+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),+);diff --git a/apps/server/src/provider/CodexInstallation.ts b/apps/server/src/provider/CodexInstallation.tsindex 9bd746c608a..d7b62424c6d 100644--- a/apps/server/src/provider/CodexInstallation.ts+++ b/apps/server/src/provider/CodexInstallation.ts@@ -1,5 +1,6 @@// @effect-diagnostics nodeBuiltinImport:off - Effect has no incremental digest.import { ProviderDriverKind, type ProviderInstallState } from "@t3tools/contracts";+import { cliArchiveTarCommand } from "@t3tools/shared/cliRelease";import * as HostProcess from "@t3tools/shared/HostProcess";import { resolveCommandPath, resolveSpawnCommand } from "@t3tools/shared/shell";import * as Clock from "effect/Clock";@@ -13,6 +14,7 @@ import * as FileSystem from "effect/FileSystem";import * as Layer from "effect/Layer";import * as Option from "effect/Option";import * as Path from "effect/Path";+import * as Schedule from "effect/Schedule";import * as Schema from "effect/Schema";import * as Scope from "effect/Scope";import * as Semaphore from "effect/Semaphore";@@ -26,6 +28,7 @@ import * as ModelManifest from "./ModelManifest.ts";import { resolveProviderCompatibility } from "./providerCompatibility.ts";const DRIVER = ProviderDriverKind.make("codex");+const STAGING_STALE_AFTER_MS = 24 * 60 * 60_000;const Version = Schema.String.check(Schema.isPattern(/^\d+\.\d+\.\d+(?:-[a-zA-Z0-9.-]+)?$/u));const ActiveRelease = Schema.Struct({ version: Version });const InstalledRelease = Schema.Struct({@@ -512,8 +515,10 @@ export const makeCodexInstallation = Effect.fn("makeCodexInstallation")(functionmessage: "Extracting Codex.",}) satisfies ProviderInstallState,);- const entries = (yield* runCommand("tar", ["-tzf", archivePath])).trim().split("\n");- const types = (yield* runCommand("tar", ["-tvzf", archivePath])).trim().split("\n");+ // Bare `tar` on Windows can resolve to Git's MSYS tar, which reads `C:\...` as a remote host.+ const tarCommand = cliArchiveTarCommand(platform, environment);+ const entries = (yield* runCommand(tarCommand, ["-tzf", archivePath])).trim().split(/\r?\n/u);+ const types = (yield* runCommand(tarCommand, ["-tvzf", archivePath])).trim().split(/\r?\n/u);if (entries.length > 10000 ||entries.length !== types.length ||@@ -529,7 +534,7 @@ export const makeCodexInstallation = Effect.fn("makeCodexInstallation")(function}))return yield* installationError("extract", "The Codex archive contains unsafe entries.");- yield* runCommand("tar", ["-xzf", archivePath, "-C", runtime]);+ yield* runCommand(tarCommand, ["-xzf", archivePath, "-C", runtime]);yield* SubscriptionRef.update(state,(current) =>@@ -553,7 +558,12 @@ export const makeCodexInstallation = Effect.fn("makeCodexInstallation")(function}),{ flag: "wx", mode: 0o600 },);- yield* fs.rename(runtime, destination);+ // On Windows, Defender and kernel process rundown can briefly hold the+ // verified codex.exe handle open right after `--version` exits.+ const renameRuntime = fs.rename(runtime, destination);+ yield* platform === "win32"+ ? renameRuntime.pipe(Effect.retry({ times: 10, schedule: Schedule.spaced("100 millis") }))+ : renameRuntime;yield* activate();},Effect.scoped,@@ -692,7 +702,34 @@ export const makeCodexInstallation = Effect.fn("makeCodexInstallation")(function);yield* Effect.gen(function* () {- const canRemove = yield* fs.exists(managedDirectory);+ // Clear staging directories left behind by an interrupted install so they+ // neither leak disk nor make an otherwise empty runtime look removable. Two+ // servers can share a home, and writes below a staging directory do not+ // refresh its mtime, so only directories far older than any real install+ // (download is capped at 45 minutes) are treated as abandoned.+ let canRemove = false;+ if (yield* fs.exists(managedDirectory)) {+ const entries = yield* fs+ .readDirectory(managedDirectory)+ .pipe(Effect.orElseSucceed((): ReadonlyArray<string> => []));+ const now = yield* Clock.currentTimeMillis;+ for (const entry of entries) {+ if (!entry.startsWith(".install-") && !entry.startsWith(".active-")) continue;+ const target = path.join(managedDirectory, entry);+ const info = yield* fs.stat(target).pipe(Effect.option);+ if (Option.isNone(info)) continue;+ const modifiedAt = Option.match(info.value.mtime, {+ onNone: () => now,+ onSome: (date) => date.getTime(),+ });+ if (now - modifiedAt < STAGING_STALE_AFTER_MS) continue;+ yield* fs.remove(target, { recursive: true, force: true }).pipe(Effect.ignore);+ }+ // The empty root itself stays: deleting it could race another server+ // creating a staging directory inside. An unreadable root stays removable.+ const remaining = yield* fs.readDirectory(managedDirectory).pipe(Effect.option);+ canRemove = Option.isNone(remaining) || remaining.value.length > 0;+ }yield* SubscriptionRef.update(state, (current) => ({ ...current, canRemove }));if (yield* reuseLocal()) return;if (!(yield* fs.exists(activePath))) return;