fix(services): report the committed cliproxy version and recover nested binaries

- getInstalledVersion() reads the version_manager row before the version
  directories, so a rollback or an older install is not reported as the
  newest directory, and ignores directories with no extracted binary.
- resolveSpawnArgs() recovery reuses findBinaryInDir(), so a binary nested
  in the archive's wrapper folder is found when the managed copy is missing.
- Installer paths use the data dir db/core.ts resolved (absolute, past its
  unwritable fallback); binaryManager resolves a relative DATA_DIR.

Refs #20180
This commit is contained in:
Rafa Martins
2026-11-18 21:24:15 -03:00
committed by diegosouzapw
parent d2d1fdb64c
commit 664ec53b58
3 changed files with 165 additions and 94 deletions

View File

@@ -20,12 +20,18 @@ import {
installVersion,
getCurrentBinaryPath,
getInstalledVersions,
findBinaryInDir,
} from "@/lib/versionManager/binaryManager.ts";
export const CLIPROXY_DEFAULT_PORT = 8317;
/**
* The data directory db/core.ts resolved at boot: absolute even for a relative
* DATA_DIR, and already past its unwritable-directory fallback, so the binary and
* config always sit next to the database instead of under a raw env value.
*/
export function getEffectiveDataDir(): string {
return process.env.DATA_DIR || DATA_DIR;
return DATA_DIR;
}
export function getBinDir(): string {
@@ -53,9 +59,10 @@ export interface SpawnArgs {
}
/**
* Reads the installed version from the symlink target directory name,
* falling back on Windows (or where copyFile was used instead of symlink)
* to inspecting installed version directories and the version_manager DB table.
* Reads the installed version from the symlink target directory name. Where the
* managed binary is a copy instead of a symlink (Windows), its parent is plain
* bin/, so fall back to the committed version_manager row and then to the newest
* version directory that really holds an extracted binary (#20180).
*/
export async function getInstalledVersion(): Promise<string | null> {
const effectiveDir = getEffectiveDataDir();
@@ -66,23 +73,34 @@ export async function getInstalledVersion(): Promise<string | null> {
if (m) return m[1];
}
// Windows fallback: when unprivileged symlinks are unavailable, installVersion
// copies the binary directly to bin/cliproxyapi.exe so dirname is "bin".
// Check versioned subdirectories in bin/ (cliproxyapi-<version>/) or DB row.
try {
const versions = await getInstalledVersions(effectiveDir);
if (versions.length > 0) {
versions.sort((a, b) => b.localeCompare(a, undefined, { numeric: true }));
return versions[0];
}
} catch {}
// install()/rollbackTool() record the version they put in place; the newest
// directory is not it after a rollback or an install of an older release.
const committed = await readCommittedVersion();
if (committed) return committed;
return newestExtractedVersion(effectiveDir);
}
async function readCommittedVersion(): Promise<string | null> {
try {
const tool = await getVersionManagerTool("cliproxy");
if (tool?.installedVersion) return tool.installedVersion;
} catch {}
return tool?.installedVersion || null;
} catch {
return null;
}
}
return null;
/**
* downloadRelease() creates cliproxyapi-<version>/ before the download, so a failed
* update leaves an empty directory behind: only count directories with a binary.
*/
async function newestExtractedVersion(dataDir: string): Promise<string | null> {
const binDir = path.join(dataDir, "bin");
const versions = (await getInstalledVersions(dataDir)).filter((version) =>
findBinaryInDir(path.join(binDir, `cliproxyapi-${version}`))
);
versions.sort((a, b) => b.localeCompare(a, undefined, { numeric: true }));
return versions[0] ?? null;
}
export async function getLatestVersion(): Promise<string | null> {
@@ -132,6 +150,37 @@ export async function update(): Promise<InstallResult> {
return install("latest");
}
/**
* #20180: the managed copy/symlink in bin/ can go missing (a failed Windows copy, a
* cleaned bin/). Use the newest extracted version, found with the installer's own
* lookup (nested archive folders included), and try to restore the managed entry so
* the next start finds it directly. Synchronous, like resolveSpawnArgs().
*/
function recoverManagedBinary(binDir: string, managedPath: string): string | null {
let versionDirs: string[];
try {
versionDirs = fs.readdirSync(binDir).filter((entry) => entry.startsWith("cliproxyapi-"));
} catch {
return null;
}
versionDirs.sort((a, b) => b.localeCompare(a, undefined, { numeric: true }));
for (const versionDir of versionDirs) {
const binary = findBinaryInDir(path.join(binDir, versionDir));
if (!binary) continue;
try {
if (os.platform() === "win32") {
fs.copyFileSync(binary, managedPath);
} else {
fs.symlinkSync(binary, managedPath);
}
} catch {
// Best effort: spawning the versioned binary directly still works.
}
return binary;
}
return null;
}
/**
* Build spawn args for ServiceSupervisor.start().
*
@@ -150,42 +199,10 @@ export function resolveSpawnArgs(port: number, managementKey?: string): SpawnArg
// path on Windows and failing with ENOENT even when a valid .exe exists
// (same fold class as b43a212680 / #10244/#10293).
const executableName = os.platform() === "win32" ? "cliproxyapi.exe" : "cliproxyapi";
let symlinkPath = path.join(binDir, executableName);
if (!fs.existsSync(symlinkPath)) {
// If the top-level binary copy/symlink does not exist, look into versioned dirs
try {
const entries = fs.readdirSync(binDir);
const versionDirs = entries
.filter((e) => e.startsWith("cliproxyapi-"))
.sort((a, b) => b.localeCompare(a, undefined, { numeric: true }));
for (const vDir of versionDirs) {
const candidates = [
"cli-proxy-api.exe",
"CLIProxyAPI.exe",
"cliproxyapi.exe",
"cli-proxy-api",
"CLIProxyAPI",
"cliproxyapi",
];
for (const name of candidates) {
const candidate = path.join(binDir, vDir, name);
if (fs.existsSync(candidate)) {
try {
if (os.platform() === "win32") {
fs.copyFileSync(candidate, symlinkPath);
} else {
fs.symlinkSync(candidate, symlinkPath);
}
} catch {}
symlinkPath = candidate;
break;
}
}
if (symlinkPath !== path.join(binDir, executableName)) break;
}
} catch {}
}
const managedPath = path.join(binDir, executableName);
const symlinkPath = fs.existsSync(managedPath)
? managedPath
: (recoverManagedBinary(binDir, managedPath) ?? managedPath);
fs.mkdirSync(configDir, { recursive: true });
const configPath = path.join(configDir, "config.yaml");

View File

@@ -8,11 +8,15 @@ import { pipeline } from "stream/promises";
import { execFile } from "child_process";
import { promisify } from "util";
import { getChecksums, getReleaseByVersion } from "./releaseChecker.ts";
import { getDefaultDataDir } from "../dataPaths.ts";
import { resolveDataDir } from "../dataPaths.ts";
const execFileAsync = promisify(execFile);
/**
* DATA_DIR made absolute (a relative value would break the managed symlink target),
* else the OS default data directory.
*/
export function getDefaultBinaryDataDir(): string {
return process.env.DATA_DIR || getDefaultDataDir();
return resolveDataDir();
}
type Platform = "linux" | "darwin" | "windows" | "freebsd";
@@ -125,7 +129,8 @@ function managedBinaryName(): string {
return os.platform() === "win32" ? "cliproxyapi.exe" : "cliproxyapi";
}
function findBinaryInDir(dir: string): string | null {
/** The extracted CLIProxyAPI executable in `dir` or one wrapper folder below it. */
export function findBinaryInDir(dir: string): string | null {
const candidates = [
"cli-proxy-api",
"cli-proxy-api.exe",
@@ -144,7 +149,7 @@ function findBinaryInDir(dir: string): string | null {
const entries = fsSync.readdirSync(dir, { withFileTypes: true });
for (const entry of entries) {
if (entry.isDirectory()) {
const subDir = path.join(dir, entry.name);
const subDir = path.join(/* turbopackIgnore: true */ dir, entry.name);
for (const name of candidates) {
const candidatePath = path.join(/* turbopackIgnore: true */ subDir, name);
if (fsSync.existsSync(candidatePath)) {

View File

@@ -1,62 +1,111 @@
import { describe, it, beforeEach, afterEach } from "node:test";
import { describe, it, beforeEach, after } from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import {
getInstalledVersion,
resolveSpawnArgs,
CLIPROXY_DEFAULT_PORT,
} from "../../../../src/lib/services/installers/cliproxy.ts";
import { getDefaultBinaryDataDir } from "../../../../src/lib/versionManager/binaryManager.ts";
const ORIGINAL_DATA_DIR = process.env.DATA_DIR;
// src/lib/db/core.ts resolves DATA_DIR once, the first time it is imported (through
// cliproxy.ts), so pin one temp dir before the dynamic imports below and reset only
// the installer folders between tests — same pattern as the #6877 spawn-args test.
const FIXED_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omni-cliproxy-win-"));
process.env.DATA_DIR = FIXED_DATA_DIR;
const { getInstalledVersion, getEffectiveDataDir, resolveSpawnArgs, CLIPROXY_DEFAULT_PORT } =
await import("../../../../src/lib/services/installers/cliproxy.ts");
const { getDefaultBinaryDataDir } =
await import("../../../../src/lib/versionManager/binaryManager.ts");
const { upsertVersionManagerTool, deleteVersionManagerTool } =
await import("../../../../src/lib/db/versionManager.ts");
const { resetDbInstance } = await import("../../../../src/lib/db/core.ts");
const binDir = path.join(FIXED_DATA_DIR, "bin");
const managedName = () => (os.platform() === "win32" ? "cliproxyapi.exe" : "cliproxyapi");
const extractedName = () => (os.platform() === "win32" ? "cli-proxy-api.exe" : "cli-proxy-api");
function extractVersion(version: string, nestedFolder?: string): string {
const dir = path.join(binDir, `cliproxyapi-${version}`, ...(nestedFolder ? [nestedFolder] : []));
fs.mkdirSync(dir, { recursive: true });
const binary = path.join(dir, extractedName());
fs.writeFileSync(binary, `binary-${version}`);
return binary;
}
describe("cliproxy windows support (#20180)", () => {
let tmpDataDir: string;
let originalDataDir: string | undefined;
beforeEach(() => {
tmpDataDir = fs.mkdtempSync(path.join(os.tmpdir(), "omni-cliproxy-win-"));
originalDataDir = process.env.DATA_DIR;
process.env.DATA_DIR = tmpDataDir;
beforeEach(async () => {
process.env.DATA_DIR = FIXED_DATA_DIR;
for (const sub of ["bin", "services"]) {
fs.rmSync(path.join(FIXED_DATA_DIR, sub), { recursive: true, force: true });
}
await deleteVersionManagerTool("cliproxy");
});
afterEach(() => {
if (originalDataDir !== undefined) {
process.env.DATA_DIR = originalDataDir;
} else {
after(() => {
resetDbInstance();
if (ORIGINAL_DATA_DIR === undefined) {
delete process.env.DATA_DIR;
} else {
process.env.DATA_DIR = ORIGINAL_DATA_DIR;
}
if (fs.existsSync(tmpDataDir)) {
fs.rmSync(tmpDataDir, { recursive: true, force: true });
}
fs.rmSync(FIXED_DATA_DIR, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
});
it("getInstalledVersion extracts version from versioned subfolder when binary is copied to bin", async () => {
const binDir = path.join(tmpDataDir, "bin");
const versionDir = path.join(binDir, "cliproxyapi-1.4.2");
fs.mkdirSync(versionDir, { recursive: true });
const executableName = os.platform() === "win32" ? "cliproxyapi.exe" : "cliproxyapi";
// Create copied binary in bin/ (which simulates Windows copyFile fallback)
fs.writeFileSync(path.join(binDir, executableName), "dummy-binary");
fs.writeFileSync(path.join(versionDir, executableName), "dummy-binary");
extractVersion("1.4.2");
// Copied binary in bin/ (the Windows copyFile path), so its parent names no version.
fs.writeFileSync(path.join(binDir, managedName()), "binary-1.4.2");
const version = await getInstalledVersion();
assert.equal(version, "1.4.2");
assert.equal(await getInstalledVersion(), "1.4.2");
});
it("getInstalledVersion reports the committed version, not the newest directory", async () => {
// Rolled back to 1.0.0: the copy in bin/ is 1.0.0 while 2.0.0 is still on disk.
extractVersion("1.0.0");
extractVersion("2.0.0");
fs.writeFileSync(path.join(binDir, managedName()), "binary-1.0.0");
await upsertVersionManagerTool({
tool: "cliproxy",
installedVersion: "1.0.0",
status: "installed",
});
assert.equal(await getInstalledVersion(), "1.0.0");
});
it("getInstalledVersion skips a version directory left empty by a failed update", async () => {
extractVersion("1.4.2");
fs.mkdirSync(path.join(binDir, "cliproxyapi-2.0.0"), { recursive: true });
fs.writeFileSync(path.join(binDir, managedName()), "binary-1.4.2");
assert.equal(await getInstalledVersion(), "1.4.2");
});
it("resolveSpawnArgs falls back to versioned directory when bin copy is missing and repairs it", () => {
const binDir = path.join(tmpDataDir, "bin");
const versionDir = path.join(binDir, "cliproxyapi-2.0.1");
fs.mkdirSync(versionDir, { recursive: true });
const binName = os.platform() === "win32" ? "cli-proxy-api.exe" : "cli-proxy-api";
const binaryFile = path.join(versionDir, binName);
fs.writeFileSync(binaryFile, "binary-content");
extractVersion("2.0.1");
const spawnArgs = resolveSpawnArgs(CLIPROXY_DEFAULT_PORT);
assert.ok(fs.existsSync(spawnArgs.command), `Command must exist: ${spawnArgs.command}`);
});
it("resolveSpawnArgs finds a binary nested in the archive's wrapper folder", () => {
const nested = extractVersion("2.0.1", "release");
const spawnArgs = resolveSpawnArgs(CLIPROXY_DEFAULT_PORT);
assert.equal(spawnArgs.command, nested);
});
it("installer paths follow the data dir db/core.ts resolved, not a later raw env value", () => {
process.env.DATA_DIR = "relative-data-dir";
assert.equal(getEffectiveDataDir(), FIXED_DATA_DIR);
});
it("getDefaultBinaryDataDir honors process.env.DATA_DIR override", () => {
assert.equal(getDefaultBinaryDataDir(), tmpDataDir);
assert.equal(getDefaultBinaryDataDir(), FIXED_DATA_DIR);
});
it("getDefaultBinaryDataDir makes a relative DATA_DIR absolute", () => {
process.env.DATA_DIR = "relative-data-dir";
assert.equal(getDefaultBinaryDataDir(), path.resolve("relative-data-dir"));
});
});