fix(server): harden Codex/Windows startup and provider resolution (#454)

* fix(server): harden Codex/Windows startup and provider resolution

Addresses #452, #443, #353, #418, #403, #221, #307, and locks in #284.

- Replace custom where.exe/which output parsing with npm `which@^5` plus a
  spawn probe. findExecutable now enumerates all PATH+PATHEXT candidates
  and returns the first invokable one. A WindowsApps-ACL'd codex.exe no
  longer wins over a working codex.cmd (#452).
- Make default provider isAvailable() check the binary instead of always
  returning true. Codex/Claude/OpenCode default isAvailable() now defer
  to isCommandAvailable() so missing CLIs surface as unavailable instead
  of throwing later from spawn (#221, #443).
- Gate AgentManager.resumeAgentFromPersistence on isAvailable() so a
  persisted agent record with a missing binary cannot reach provider
  spawn during rehydration. The daemon stays up and the agent reports
  unavailable (#443, #353, #418, #403).
- Drop --path-format=absolute from rev-parse callers and validate stdout
  through a shared parser that rejects multi-line output and unknown-flag
  echoes. --show-toplevel is absolute by default in modern Git;
  --git-common-dir is resolved against the command cwd. Fixes workspace
  registration on pre-2.31 Git that echoed the unknown flag and produced
  a two-line "path" (#307).

Tests:
- Real-FS executable.test.ts using temp PATH fixtures, covering the .cmd
  fallback after .exe pre-spawn failure (Windows-only) plus the
  null-on-no-invokable-candidate case.
- provider-availability.test.ts builds real provider clients against a
  temp-dir-only PATH for Codex/Claude/OpenCode.
- bootstrap-provider-availability.test.ts builds the daemon and triggers
  ensureAgentLoaded so it actually exercises resumeAgentFromPersistence.
- claude-agent.spawn.test.ts asserts shell: false reaches spawnProcess
  from the Claude SDK spawn override, locking in 39b56af4 for #284.
- checkout-git-rev-parse.test.ts covers nested-checkout resolution and
  the old-Git multi-line stdout case via a tightly-scoped runGitCommand
  fake.

CI:
- server-tests-windows now also runs the new and modified test files so
  the Windows behaviors are exercised on windows-latest.

* fix: update lockfile signatures and Nix hash

* fix(server): handle synchronous spawn UNKNOWN on Windows

On Windows, child_process.spawn() throws synchronously when invoked on
a corrupt or invalid .exe (e.g., a WindowsApps stub the current user
cannot execute, or a zero-byte file). The executable probe did not
guard the spawn call, so the synchronous throw rejected the probe
promise instead of resolving false, preventing findExecutable() from
trying the next candidate. This is the root cause of the daemon-crash
pattern in #452: codex.exe from WindowsApps would hard-fail before the
.cmd shim ever got a chance.

Wrap spawn() in try/catch and settle false on sync throw. The existing
error-event and exit-event handlers already cover async failure modes;
sync throw just needed one more guard.

Also adjust three Windows-only test comparisons that were asserting
platform-dependent string equality:
- executable.test: compare .cmd paths case-insensitively (which@5
  preserves PATHEXT casing, which is uppercase in production).
- workspace-registry-model.test: expect normalizeWorkspaceId(path),
  not the hardcoded POSIX form.
- checkout-git-rev-parse.test: normalize separators/case when
  comparing git's Windows forward-slash output against realpathSync.

* test(server): canonicalize repo root via git on Windows to fix short-name mismatch

realpathSync on Windows preserves 8.3 short names (e.g. RUNNER~1) while git's
rev-parse --show-toplevel always returns the long-name form (runneradmin).
Use git as the canonicalizer on both sides of the assertion so the comparison
holds regardless of how Windows exposes the temp directory path.

* fix(server): Claude is always available in default mode; SDK bundles cli.js

The Phase 2 change wrongly tied Claude's default-mode isAvailable() to
isCommandAvailable("claude"). Claude's default runtime does not use an
external `claude` binary — @anthropic-ai/claude-agent-sdk ships its own
cli.js and spawnClaudeCodeProcess runs it via process.execPath. The
previous `return true` was correct; restore it.

Update provider-availability.test.ts to assert the truthful behavior:
Claude reports available even when no `claude` binary is on PATH.

Codex and OpenCode genuinely require their binaries on PATH, so their
availability checks remain unchanged.

---------

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
This commit is contained in:
Mohamed Boudra
2026-04-16 16:36:13 +08:00
committed by GitHub
co-authored by github-actions[bot] <github-actions[bot]@users.noreply.github.com>
parent 11b407c804
commit 7c50b7a080
20 changed files with 842 additions and 324 deletions
+133 -203
View File
@@ -1,213 +1,157 @@
import { promisify } from "node:util";
import { afterEach, describe, expect, test, vi } from "vitest";
import { chmodSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import os from "node:os";
import path from "node:path";
import { afterEach, describe, expect, test } from "vitest";
type ExecFileCallback = (error: Error | null, stdout: string, stderr: string) => void;
import {
executableExists,
findExecutable,
quoteWindowsArgument,
quoteWindowsCommand,
} from "./executable.js";
async function loadExecutableModule(params?: {
execFileImpl?: (
command: string,
args: string[],
options: unknown,
callback: ExecFileCallback,
) => void;
}) {
vi.resetModules();
const originalEnv = {
PATH: process.env.PATH,
PATHEXT: process.env.PATHEXT,
};
const tempDirs: string[] = [];
const execFileMock = vi.fn(
params?.execFileImpl ??
((_command: string, _args: string[], _options: unknown, callback: ExecFileCallback) => {
callback(new Error("execFile not mocked"), "", "");
}),
);
Object.assign(execFileMock, {
[promisify.custom]: (command: string, args: string[], options: unknown) =>
new Promise<{ stdout: string; stderr: string }>((resolve, reject) => {
execFileMock(
command,
args,
options,
(error: Error | null, stdout: string, stderr: string) => {
if (error) {
reject(error);
return;
}
resolve({ stdout, stderr });
},
);
}),
});
vi.doMock("node:child_process", () => ({
execFile: execFileMock,
}));
const module = await import("./executable.js");
return {
...module,
execFileMock,
};
function makeTempDir(): string {
const dir = mkdtempSync(path.join(os.tmpdir(), "paseo-executable-test-"));
tempDirs.push(dir);
return dir;
}
describe("findExecutable", () => {
const originalPlatform = process.platform;
const missingBinaryName = "nonexistent-binary-xyz-12345";
function prependPath(...dirs: string[]): void {
process.env.PATH = [...dirs, originalEnv.PATH].filter(Boolean).join(path.delimiter);
}
function setPlatform(value: string) {
Object.defineProperty(process, "platform", { value, writable: true });
function writeExecutable(filePath: string, content: string): string {
writeFileSync(filePath, content);
if (process.platform !== "win32") {
chmodSync(filePath, 0o755);
}
return filePath;
}
afterEach(() => {
setPlatform(originalPlatform);
});
function writeInvokableFixture(dir: string, name: string): string {
if (process.platform === "win32") {
return writeExecutable(path.join(dir, `${name}.cmd`), "@echo off\r\necho 0.1\r\n");
}
return writeExecutable(path.join(dir, name), "#!/bin/sh\necho 0.1\n");
}
test("on Windows, resolves executables using where.exe with inherited PATH", async () => {
setPlatform("win32");
const { execFileMock, findExecutable } = await loadExecutableModule({
execFileImpl: (_command, _args, _options, callback) => {
callback(null, "C:\\Users\\boudr\\.local\\bin\\claude.exe\r\n", "");
},
});
function writeBrokenAbsoluteFixture(dir: string): string {
const filePath =
process.platform === "win32" ? path.join(dir, "broken.exe") : path.join(dir, "broken");
writeFileSync(filePath, "not executable");
if (process.platform !== "win32") {
chmodSync(filePath, 0o644);
}
return filePath;
}
await expect(findExecutable("claude")).resolves.toBe(
"C:\\Users\\boudr\\.local\\bin\\claude.exe",
);
expect(execFileMock).toHaveBeenCalledOnce();
const call = execFileMock.mock.calls[0];
expect(call?.[0]).toBe("where.exe");
expect(call?.[1]).toEqual(["claude"]);
expect(call?.[2]).toMatchObject({
encoding: "utf8",
windowsHide: true,
function expectWindowsPathsEqual(actual: string | null, expected: string): void {
expect(actual?.toLowerCase()).toBe(expected.toLowerCase());
}
afterEach(() => {
process.env.PATH = originalEnv.PATH;
process.env.PATHEXT = originalEnv.PATHEXT;
for (const dir of tempDirs.splice(0)) {
rmSync(dir, { recursive: true, force: true });
}
});
describe("findExecutable", () => {
describe.skipIf(process.platform === "win32")("POSIX", () => {
test("finds an extensionless executable and skips an earlier non-executable candidate", async () => {
const executableDir = makeTempDir();
const nonExecutableDir = makeTempDir();
const executable = writeExecutable(path.join(executableDir, "foo"), "#!/bin/sh\necho 0.1\n");
const nonExecutable = path.join(nonExecutableDir, "foo");
writeFileSync(nonExecutable, "#!/bin/sh\necho broken\n");
chmodSync(nonExecutable, 0o644);
prependPath(nonExecutableDir, executableDir);
await expect(findExecutable("foo")).resolves.toBe(executable);
});
});
test("on Windows, prefers an executable match from where.exe output", async () => {
setPlatform("win32");
const { findExecutable } = await loadExecutableModule({
execFileImpl: (_command, _args, _options, callback) => {
callback(null, "C:\\nvm4w\\nodejs\\codex\r\nC:\\nvm4w\\nodejs\\codex.cmd\r\n", "");
},
describe.runIf(process.platform === "win32")("Windows", () => {
test("returns a working .cmd when an invalid .exe candidate appears first", async () => {
const dir = makeTempDir();
process.env.PATHEXT = [".EXE", ".CMD"].join(path.delimiter);
const brokenExe = path.join(dir, "foo.exe");
const cmd = writeExecutable(path.join(dir, "foo.cmd"), "@echo off\r\necho 0.1\r\n");
writeFileSync(brokenExe, "");
prependPath(dir);
expectWindowsPathsEqual(await findExecutable("foo"), cmd);
});
await expect(findExecutable("codex")).resolves.toBe("C:\\nvm4w\\nodejs\\codex.cmd");
test("returns null when the only candidate is a broken .exe", async () => {
const dir = makeTempDir();
process.env.PATHEXT = ".EXE";
writeFileSync(path.join(dir, "foo.exe"), "");
prependPath(dir);
await expect(findExecutable("foo")).resolves.toBeNull();
});
test("returns a .cmd when it is the only candidate", async () => {
const dir = makeTempDir();
process.env.PATHEXT = ".CMD";
const cmd = writeExecutable(path.join(dir, "foo.cmd"), "@echo off\r\necho 0.1\r\n");
prependPath(dir);
expectWindowsPathsEqual(await findExecutable("foo"), cmd);
});
});
test("on Windows, prefers .exe over .cmd, .ps1, and extensionless candidates", async () => {
setPlatform("win32");
const { findExecutable } = await loadExecutableModule({
execFileImpl: (_command, _args, _options, callback) => {
callback(
null,
[
"C:\\nvm4w\\nodejs\\codex",
"C:\\nvm4w\\nodejs\\codex.ps1",
"C:\\nvm4w\\nodejs\\codex.cmd",
"C:\\nvm4w\\nodejs\\codex.exe",
].join("\r\n"),
"",
);
},
});
test("returns an invokable absolute path", async () => {
const dir = makeTempDir();
const fixture = writeInvokableFixture(dir, "absolute-ok");
await expect(findExecutable("codex")).resolves.toBe("C:\\nvm4w\\nodejs\\codex.exe");
await expect(findExecutable(fixture)).resolves.toBe(fixture);
});
test("on Windows, returns null when where.exe output is empty", async () => {
setPlatform("win32");
const { findExecutable } = await loadExecutableModule({
execFileImpl: (_command, _args, _options, callback) => {
callback(null, "\r\n", "");
},
});
test("returns null for an absolute path that cannot spawn", async () => {
const dir = makeTempDir();
const fixture = writeBrokenAbsoluteFixture(dir);
await expect(findExecutable(missingBinaryName)).resolves.toBeNull();
await expect(findExecutable(fixture)).resolves.toBeNull();
});
test("on Windows, falls back to the first extensionless candidate when needed", async () => {
setPlatform("win32");
const { findExecutable } = await loadExecutableModule({
execFileImpl: (_command, _args, _options, callback) => {
callback(null, "C:\\nvm4w\\nodejs\\codex\r\n", "");
},
});
test("returns null when the command is not on PATH", async () => {
const dir = makeTempDir();
prependPath(dir);
await expect(findExecutable("codex")).resolves.toBe("C:\\nvm4w\\nodejs\\codex");
});
test("on Unix, uses the last line from which output", async () => {
const { execFileMock, findExecutable } = await loadExecutableModule({
execFileImpl: (_command, _args, _options, callback) => {
callback(null, "/usr/local/bin/codex\n", "");
},
});
await expect(findExecutable("codex")).resolves.toBe("/usr/local/bin/codex");
expect(execFileMock).toHaveBeenCalledWith(
process.platform === "win32" ? "where.exe" : "which",
["codex"],
process.platform === "win32" ? { encoding: "utf8", windowsHide: true } : { encoding: "utf8" },
expect.any(Function),
);
});
test.skipIf(process.platform === "win32")(
"warns and returns null when the final which line is not an absolute path",
async () => {
const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
const { findExecutable } = await loadExecutableModule({
execFileImpl: (_command, _args, _options, callback) => {
callback(null, "codex\n", "");
},
});
await expect(findExecutable("codex")).resolves.toBeNull();
expect(warnSpy).toHaveBeenCalledOnce();
warnSpy.mockRestore();
},
);
test("returns null when which lookup fails", async () => {
const { findExecutable } = await loadExecutableModule({
execFileImpl: (_command, _args, _options, callback) => {
callback(new Error("which failed"), "", "");
},
});
await expect(findExecutable(missingBinaryName)).resolves.toBeNull();
await expect(findExecutable("paseo-definitely-missing-command")).resolves.toBeNull();
});
});
describe("executableExists", () => {
const originalPlatform = process.platform;
function setPlatform(value: string) {
Object.defineProperty(process, "platform", { value, writable: true });
}
afterEach(() => {
setPlatform(originalPlatform);
});
test("returns the path when it already exists", async () => {
const { executableExists } = await loadExecutableModule();
const exists = vi.fn((candidate: string) => candidate === "/usr/local/bin/codex");
test("returns the path when it already exists", () => {
const exists = (candidate: string) => candidate === "/usr/local/bin/codex";
expect(executableExists("/usr/local/bin/codex", exists)).toBe("/usr/local/bin/codex");
});
test("on Windows, falls back to .exe, .cmd, then .ps1 for extensionless paths", async () => {
setPlatform("win32");
const { executableExists } = await loadExecutableModule();
const exists = vi.fn((candidate: string) => candidate === "C:\\tools\\codex.cmd");
test("on Windows, falls back to .exe, .cmd, then .ps1 for extensionless paths", () => {
const originalPlatform = process.platform;
Object.defineProperty(process, "platform", { value: "win32", writable: true });
try {
const exists = (candidate: string) => candidate === "C:\\tools\\codex.cmd";
expect(executableExists("C:\\tools\\codex", exists)).toBe("C:\\tools\\codex.cmd");
expect(executableExists("C:\\tools\\codex", exists)).toBe("C:\\tools\\codex.cmd");
} finally {
Object.defineProperty(process, "platform", { value: originalPlatform, writable: true });
}
});
test("returns null when no matching path exists", async () => {
const { executableExists } = await loadExecutableModule();
const exists = vi.fn(() => false);
expect(executableExists("/missing/codex", exists)).toBeNull();
test("returns null when no matching path exists", () => {
expect(executableExists("/missing/codex", () => false)).toBeNull();
});
});
@@ -222,71 +166,61 @@ describe("quoteWindowsCommand", () => {
setPlatform(originalPlatform);
});
test("quotes a Windows path with spaces", async () => {
test("quotes a Windows path with spaces", () => {
setPlatform("win32");
const { quoteWindowsCommand } = await loadExecutableModule();
expect(quoteWindowsCommand("C:\\Program Files\\Anthropic\\claude.exe")).toBe(
'"C:\\Program Files\\Anthropic\\claude.exe"',
);
});
test("does not double-quote an already-quoted path", async () => {
test("does not double-quote an already-quoted path", () => {
setPlatform("win32");
const { quoteWindowsCommand } = await loadExecutableModule();
expect(quoteWindowsCommand('"C:\\Program Files\\Anthropic\\claude.exe"')).toBe(
'"C:\\Program Files\\Anthropic\\claude.exe"',
);
});
test("returns the command unchanged when there are no spaces", async () => {
test("returns the command unchanged when there are no spaces", () => {
setPlatform("win32");
const { quoteWindowsCommand } = await loadExecutableModule();
expect(quoteWindowsCommand("C:\\nvm4w\\nodejs\\codex")).toBe("C:\\nvm4w\\nodejs\\codex");
});
test("escapes ampersands", async () => {
test("escapes ampersands", () => {
setPlatform("win32");
const { quoteWindowsCommand } = await loadExecutableModule();
expect(quoteWindowsCommand("feature&bugfix")).toBe("feature^&bugfix");
});
test("escapes pipes", async () => {
test("escapes pipes", () => {
setPlatform("win32");
const { quoteWindowsCommand } = await loadExecutableModule();
expect(quoteWindowsCommand("feature|bugfix")).toBe("feature^|bugfix");
});
test("doubles percent signs", async () => {
test("doubles percent signs", () => {
setPlatform("win32");
const { quoteWindowsCommand } = await loadExecutableModule();
expect(quoteWindowsCommand("100%")).toBe("100%%");
});
test("escapes carets", async () => {
test("escapes carets", () => {
setPlatform("win32");
const { quoteWindowsCommand } = await loadExecutableModule();
expect(quoteWindowsCommand("feature^bugfix")).toBe("feature^^bugfix");
});
test("escapes multiple metacharacters", async () => {
test("escapes multiple metacharacters", () => {
setPlatform("win32");
const { quoteWindowsCommand } = await loadExecutableModule();
expect(quoteWindowsCommand("build&(test|deploy)!<output>")).toBe(
"build^&^(test^|deploy^)^!^<output^>",
);
});
test("quotes commands with spaces after escaping metacharacters", async () => {
test("quotes commands with spaces after escaping metacharacters", () => {
setPlatform("win32");
const { quoteWindowsCommand } = await loadExecutableModule();
expect(quoteWindowsCommand("C:\\Program Files\\My Tool&Stuff\\run 100%.cmd")).toBe(
'"C:\\Program Files\\My Tool^&Stuff\\run 100%%.cmd"',
);
});
test("returns the command unchanged on non-Windows platforms", async () => {
test("returns the command unchanged on non-Windows platforms", () => {
setPlatform("darwin");
const { quoteWindowsCommand } = await loadExecutableModule();
expect(quoteWindowsCommand("/usr/local/bin/claude code")).toBe("/usr/local/bin/claude code");
});
});
@@ -302,31 +236,27 @@ describe("quoteWindowsArgument", () => {
setPlatform(originalPlatform);
});
test("quotes a Windows argument with spaces", async () => {
test("quotes a Windows argument with spaces", () => {
setPlatform("win32");
const { quoteWindowsArgument } = await loadExecutableModule();
expect(quoteWindowsArgument("C:\\Program Files\\Anthropic\\cli.js")).toBe(
'"C:\\Program Files\\Anthropic\\cli.js"',
);
});
test("does not double-quote an already-quoted argument", async () => {
test("does not double-quote an already-quoted argument", () => {
setPlatform("win32");
const { quoteWindowsArgument } = await loadExecutableModule();
expect(quoteWindowsArgument('"C:\\Program Files\\Anthropic\\cli.js"')).toBe(
'"C:\\Program Files\\Anthropic\\cli.js"',
);
});
test("returns the argument unchanged when there are no spaces", async () => {
test("returns the argument unchanged when there are no spaces", () => {
setPlatform("win32");
const { quoteWindowsArgument } = await loadExecutableModule();
expect(quoteWindowsArgument("--version")).toBe("--version");
});
test("returns the argument unchanged on non-Windows platforms", async () => {
test("returns the argument unchanged on non-Windows platforms", () => {
setPlatform("darwin");
const { quoteWindowsArgument } = await loadExecutableModule();
expect(quoteWindowsArgument("/usr/local/bin/claude code")).toBe("/usr/local/bin/claude code");
});
});