From 8b2e14f3d2b7f56647f957e7dc52c055930a0e42 Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Tue, 24 Nov 2026 14:37:28 +0700 Subject: [PATCH] Run resolved forge CLI executables directly (#10685) * fix(server): run resolved forge CLI executables directly The GitHub, GitLab, and Gitea adapters resolved gh, glab, and tea with findExecutable, then discarded the resolved path and spawned the bare command name. On Windows, spawning an extensionless bare name routes through cmd.exe, which resolves commands against cwd first, expands %VAR% references, and truncates multiline arguments such as gh api graphql queries. Forward the resolved executablePath from each forge adapter and auth probe into the shared runner, resolve bare binary names inside createForgeCliRunner when omitted, and restrict bare-name PATH discovery in findExecutable to absolute PATH directories. * fix(server): re-resolve cached forge CLI paths if the binary disappears Cached CLI path resolvers now support targeted invalidation, and forge adapters plus createForgeCliRunner invalidate and retry once when a previously resolved executable disappears at launch time (ENOENT, or a missing Windows batch launcher). This preserves cached lookups on normal runs while recovering automatically when a user uninstalls or relocates an installation while another copy remains on PATH. * fix(server): refresh cached forge CLI path on any unlaunchable spawn error Match executable-resolution's unlaunchable spawn error set (ENOENT, EACCES, ENOEXEC, UNKNOWN) when deciding whether to invalidate and re-resolve a cached forge CLI path, so losing execute permission falls back to another working copy on PATH. --- .../executable-resolution.test.ts | 28 ++ .../executable-resolution.ts | 45 ++- .../src/services/forge-cli-command.test.ts | 317 +++++++++++++++++- .../server/src/services/forge-cli-command.ts | 146 +++++++- .../server/src/services/gitea-service.test.ts | 97 ++++++ packages/server/src/services/gitea-service.ts | 35 +- .../services/github-repository-search.test.ts | 8 +- .../src/services/github-service.test.ts | 44 +++ .../server/src/services/github-service.ts | 23 +- .../src/services/gitlab-service.test.ts | 45 +++ .../server/src/services/gitlab-service.ts | 22 +- 11 files changed, 762 insertions(+), 48 deletions(-) diff --git a/packages/server/src/executable-resolution/executable-resolution.test.ts b/packages/server/src/executable-resolution/executable-resolution.test.ts index 2ee0bd90d..a635f7aa8 100644 --- a/packages/server/src/executable-resolution/executable-resolution.test.ts +++ b/packages/server/src/executable-resolution/executable-resolution.test.ts @@ -74,6 +74,19 @@ describe("findExecutable", () => { await expect(findExecutable("foo")).resolves.toBe(executable); }); + + test("ignores relative PATH entries when resolving a bare command name", async () => { + const dir = makeTempDir(); + const previousCwd = process.cwd(); + writeExecutable(path.join(dir, "rel-only-cmd"), "#!/bin/sh\necho 0.1\n"); + process.chdir(dir); + try { + process.env.PATH = [".", originalEnv.PATH].filter(Boolean).join(path.delimiter); + await expect(findExecutable("rel-only-cmd")).resolves.toBeNull(); + } finally { + process.chdir(previousCwd); + } + }); }); describe.runIf(isPlatform("win32"))("Windows", () => { @@ -142,6 +155,21 @@ describe("findExecutable", () => { process.env.LOCALAPPDATA = originalLocalAppData; } }); + + test("ignores commands in the current working directory when not explicitly on PATH", async () => { + const repoDir = makeTempDir(); + const emptyPathDir = makeTempDir(); + const previousCwd = process.cwd(); + process.env.PATHEXT = [".EXE", ".CMD"].join(path.delimiter); + writeExecutable(path.join(repoDir, "cwd-only-cmd.cmd"), "@echo off\r\necho 0.1\r\n"); + process.chdir(repoDir); + try { + process.env.PATH = emptyPathDir; + await expect(findExecutable("cwd-only-cmd")).resolves.toBeNull(); + } finally { + process.chdir(previousCwd); + } + }); }); test("returns an invokable absolute path", async () => { diff --git a/packages/server/src/executable-resolution/executable-resolution.ts b/packages/server/src/executable-resolution/executable-resolution.ts index 064dcec64..82da201f1 100644 --- a/packages/server/src/executable-resolution/executable-resolution.ts +++ b/packages/server/src/executable-resolution/executable-resolution.ts @@ -1,5 +1,5 @@ import { existsSync } from "node:fs"; -import { delimiter, resolve } from "node:path"; +import { delimiter, dirname, isAbsolute, resolve } from "node:path"; import type { ProcessEnvRecord } from "../server/paseo-env.js"; import { execCommand } from "../utils/spawn.js"; import which from "which"; @@ -11,11 +11,46 @@ function hasPathSeparator(value: string): boolean { return value.includes("/") || value.includes("\\"); } -async function enumerateCandidates(name: string, env?: ProcessEnvRecord): Promise { - if (process.platform !== "win32" && existsSync("/usr/bin/which")) { - return enumerateCandidatesViaSystemWhich(name, env); +function stripWindowsPathQuotes(entry: string): string { + return process.platform === "win32" && + entry.length >= 2 && + entry.startsWith('"') && + entry.endsWith('"') + ? entry.slice(1, -1) + : entry; +} + +function normalizeDirectory(dir: string): string { + const resolved = resolve(dir); + return process.platform === "win32" ? resolved.toLowerCase() : resolved; +} + +function extractAbsolutePathDirs(rawPath: string | undefined): string[] { + if (!rawPath) { + return []; } - return enumerateCandidatesViaLibrary(name, env); + return rawPath + .split(delimiter) + .map(stripWindowsPathQuotes) + .filter((entry) => entry.length > 0 && isAbsolute(entry)); +} + +async function enumerateCandidates(name: string, env?: ProcessEnvRecord): Promise { + const rawPath = env?.PATH !== undefined ? env.PATH : process.env.PATH; + const absolutePathDirs = extractAbsolutePathDirs(rawPath); + if (absolutePathDirs.length === 0) { + return []; + } + const filteredEnv: ProcessEnvRecord = { + ...(env ?? process.env), + PATH: absolutePathDirs.join(delimiter), + }; + const allowedDirs = new Set(absolutePathDirs.map(normalizeDirectory)); + const candidates = + process.platform !== "win32" && existsSync("/usr/bin/which") + ? await enumerateCandidatesViaSystemWhich(name, filteredEnv) + : await enumerateCandidatesViaLibrary(name, filteredEnv); + return candidates.filter((candidate) => allowedDirs.has(normalizeDirectory(dirname(candidate)))); } async function enumerateCandidatesViaSystemWhich( diff --git a/packages/server/src/services/forge-cli-command.test.ts b/packages/server/src/services/forge-cli-command.test.ts index 143066f5b..82f7f6f2f 100644 --- a/packages/server/src/services/forge-cli-command.test.ts +++ b/packages/server/src/services/forge-cli-command.test.ts @@ -1,6 +1,6 @@ -import { chmodSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { chmodSync, copyFileSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; -import { join } from "node:path"; +import { delimiter, join } from "node:path"; import { afterEach, beforeEach, describe, expect, it } from "vitest"; import { createCachedCliPathResolver, @@ -70,6 +70,44 @@ exit 1 }), ).resolves.toBe(false); }); + + it("invokes the resolved executable path instead of re-searching PATH by bare name", async () => { + const originalPath = process.env.PATH; + const earlierDir = join(tempDir, "earlier-bin"); + const workingDir = join(tempDir, "working-bin"); + mkdirSync(earlierDir); + mkdirSync(workingDir); + + const shadowingCli = join(earlierDir, "forge-probe-cli"); + const workingCli = join(workingDir, "forge-probe-cli"); + writeFileSync( + workingCli, + `#!/bin/sh +if [ "$1" = "--version" ]; then + printf '#!/bin/sh\\nexit 1\\n' > "${shadowingCli}" + chmod 755 "${shadowingCli}" + exit 0 +fi +if [ "$1" = "auth" ] && [ "$2" = "status" ] && [ "$3" = "--hostname" ] && [ "$4" = "git.acme.internal" ]; then + exit 0 +fi +exit 1 +`, + ); + chmodSync(workingCli, 0o755); + + process.env.PATH = [earlierDir, workingDir, originalPath].filter(Boolean).join(delimiter); + try { + await expect( + probeHostViaCliAuthStatus({ + cli: "forge-probe-cli", + host: "git.acme.internal", + }), + ).resolves.toBe(true); + } finally { + process.env.PATH = originalPath; + } + }); }); describe.skipIf(isPlatform("win32"))("createForgeCliRunner", () => { @@ -138,6 +176,264 @@ describe.skipIf(isPlatform("win32"))("createForgeCliRunner", () => { expect(normalized).toBeInstanceOf(FakeCommandError); expect((normalized as FakeCommandError).stderr).toMatch(/timed out after 100ms/); }); + + it("executes the provided executablePath instead of re-resolving binary from PATH", async () => { + const originalPath = process.env.PATH; + const pathDir = join(tempDir, "path-bin"); + const resolvedDir = join(tempDir, "resolved-bin"); + mkdirSync(pathDir); + mkdirSync(resolvedDir); + + const pathCli = join(pathDir, "forge-cli-test"); + writeFileSync(pathCli, "#!/bin/sh\necho from-path\n"); + chmodSync(pathCli, 0o755); + + const resolvedCli = join(resolvedDir, "forge-cli-test"); + writeFileSync(resolvedCli, "#!/bin/sh\necho from-resolved\n"); + chmodSync(resolvedCli, 0o755); + + const runner = createForgeCliRunner({ + binary: "forge-cli-test", + envOverlay: {}, + timeoutMs: 2_000, + isAuthFailureText: () => false, + errorClasses: { + isAlreadyClassified: () => false, + isCommandError: (error): error is FakeCommandError => error instanceof FakeCommandError, + createAuthError: (stderr) => new Error(`auth: ${stderr}`), + createMissingError: () => new Error("missing"), + createCommandError: (params) => new FakeCommandError(params), + }, + }); + + process.env.PATH = [pathDir, originalPath].filter(Boolean).join(delimiter); + try { + const result = await runner.run(["status"], { + cwd: tempDir, + executablePath: resolvedCli, + }); + expect(result.stdout.trim()).toBe("from-resolved"); + } finally { + process.env.PATH = originalPath; + } + }); + + it("resolves a bare binary via resolveExecutablePath when executablePath is omitted", async () => { + const originalPath = process.env.PATH; + const pathDir = join(tempDir, "path-bin"); + const resolvedDir = join(tempDir, "resolved-bin"); + mkdirSync(pathDir); + mkdirSync(resolvedDir); + + const pathCli = join(pathDir, "forge-cli-default"); + writeFileSync(pathCli, "#!/bin/sh\necho from-path\n"); + chmodSync(pathCli, 0o755); + + const resolvedCli = join(resolvedDir, "forge-cli-default"); + writeFileSync(resolvedCli, "#!/bin/sh\necho from-resolver\n"); + chmodSync(resolvedCli, 0o755); + + const runner = createForgeCliRunner({ + binary: "forge-cli-default", + envOverlay: {}, + timeoutMs: 2_000, + isAuthFailureText: () => false, + resolveExecutablePath: async () => resolvedCli, + errorClasses: { + isAlreadyClassified: () => false, + isCommandError: (error): error is FakeCommandError => error instanceof FakeCommandError, + createAuthError: (stderr) => new Error(`auth: ${stderr}`), + createMissingError: () => new Error("missing"), + createCommandError: (params) => new FakeCommandError(params), + }, + }); + + process.env.PATH = [pathDir, originalPath].filter(Boolean).join(delimiter); + try { + const result = await runner.run(["status"], { cwd: tempDir }); + expect(result.stdout.trim()).toBe("from-resolver"); + } finally { + process.env.PATH = originalPath; + } + }); + + it("throws createMissingError when a bare binary cannot be resolved", async () => { + const runner = createForgeCliRunner({ + binary: "forge-cli-uninstalled", + envOverlay: {}, + timeoutMs: 2_000, + isAuthFailureText: () => false, + resolveExecutablePath: async () => null, + errorClasses: { + isAlreadyClassified: () => false, + isCommandError: (error): error is FakeCommandError => error instanceof FakeCommandError, + createAuthError: (stderr) => new Error(`auth: ${stderr}`), + createMissingError: () => new Error("forge-cli-missing"), + createCommandError: (params) => new FakeCommandError(params), + }, + }); + + await expect(runner.run(["status"], { cwd: tempDir })).rejects.toThrow("forge-cli-missing"); + }); + + it("re-resolves and retries once when the cached executable is removed from PATH", async () => { + const originalPath = process.env.PATH; + const firstDir = join(tempDir, "first-bin"); + const secondDir = join(tempDir, "second-bin"); + mkdirSync(firstDir); + mkdirSync(secondDir); + + const firstCli = join(firstDir, "forge-cli-fallback"); + writeFileSync(firstCli, "#!/bin/sh\necho from-first\n"); + chmodSync(firstCli, 0o755); + + const secondCli = join(secondDir, "forge-cli-fallback"); + writeFileSync(secondCli, "#!/bin/sh\necho from-second\n"); + chmodSync(secondCli, 0o755); + + const runner = createForgeCliRunner({ + binary: "forge-cli-fallback", + envOverlay: {}, + timeoutMs: 2_000, + isAuthFailureText: () => false, + errorClasses: { + isAlreadyClassified: () => false, + isCommandError: (error): error is FakeCommandError => error instanceof FakeCommandError, + createAuthError: (stderr) => new Error(`auth: ${stderr}`), + createMissingError: () => new Error("missing"), + createCommandError: (params) => new FakeCommandError(params), + }, + }); + + process.env.PATH = [firstDir, secondDir, originalPath].filter(Boolean).join(delimiter); + try { + await expect(runner.run(["status"], { cwd: tempDir })).resolves.toMatchObject({ + stdout: "from-first\n", + }); + rmSync(firstCli); + await expect(runner.run(["status"], { cwd: tempDir })).resolves.toMatchObject({ + stdout: "from-second\n", + }); + } finally { + process.env.PATH = originalPath; + } + }); + + it("re-resolves and retries once when the cached executable loses execute permission", async () => { + const originalPath = process.env.PATH; + const firstDir = join(tempDir, "first-perm-bin"); + const secondDir = join(tempDir, "second-perm-bin"); + mkdirSync(firstDir); + mkdirSync(secondDir); + + const firstCli = join(firstDir, "forge-cli-perm"); + writeFileSync(firstCli, "#!/bin/sh\necho from-first\n"); + chmodSync(firstCli, 0o755); + + const secondCli = join(secondDir, "forge-cli-perm"); + writeFileSync(secondCli, "#!/bin/sh\necho from-second\n"); + chmodSync(secondCli, 0o755); + + const runner = createForgeCliRunner({ + binary: "forge-cli-perm", + envOverlay: {}, + timeoutMs: 2_000, + isAuthFailureText: () => false, + errorClasses: { + isAlreadyClassified: () => false, + isCommandError: (error): error is FakeCommandError => error instanceof FakeCommandError, + createAuthError: (stderr) => new Error(`auth: ${stderr}`), + createMissingError: () => new Error("missing"), + createCommandError: (params) => new FakeCommandError(params), + }, + }); + + process.env.PATH = [firstDir, secondDir, originalPath].filter(Boolean).join(delimiter); + try { + await expect(runner.run(["status"], { cwd: tempDir })).resolves.toMatchObject({ + stdout: "from-first\n", + }); + chmodSync(firstCli, 0o644); + await expect(runner.run(["status"], { cwd: tempDir })).resolves.toMatchObject({ + stdout: "from-second\n", + }); + } finally { + process.env.PATH = originalPath; + } + }); +}); + +describe.runIf(isPlatform("win32"))("createForgeCliRunner (Windows)", () => { + let tempDir: string; + + beforeEach(() => { + tempDir = mkdtempSync(join(tmpdir(), "forge-cli-win-")); + }); + + afterEach(() => { + rmSync(tempDir, { recursive: true, force: true }); + }); + + class FakeCommandError extends Error { + readonly stderr: string; + constructor(params: { stderr: string }) { + super("command failed"); + this.stderr = params.stderr; + } + } + + it("runs the resolved executable instead of a cwd-local script and preserves percent-delimited args", async () => { + const originalPath = process.env.PATH; + const originalVar = process.env.PASEO_FORGE_ARG_LITERAL; + const binDir = join(tempDir, "bin"); + const repoDir = join(tempDir, "repo"); + mkdirSync(binDir); + mkdirSync(repoDir); + + const installedExe = join(binDir, "forge-win-cli.exe"); + copyFileSync(process.execPath, installedExe); + writeFileSync(join(repoDir, "forge-win-cli.cmd"), "@echo off\r\necho from-cwd\r\n"); + + const runner = createForgeCliRunner({ + binary: "forge-win-cli", + envOverlay: {}, + timeoutMs: 5_000, + isAuthFailureText: () => false, + errorClasses: { + isAlreadyClassified: () => false, + isCommandError: (error): error is FakeCommandError => error instanceof FakeCommandError, + createAuthError: (stderr) => new Error(`auth: ${stderr}`), + createMissingError: () => new Error("missing"), + createCommandError: (params) => new FakeCommandError(params), + }, + }); + + process.env.PATH = [binDir, originalPath].filter(Boolean).join(delimiter); + process.env.PASEO_FORGE_ARG_LITERAL = "expanded-env-value"; + try { + const result = await runner.run( + [ + "-e", + "process.stdout.write(JSON.stringify(process.argv.slice(1)))", + "--", + "%PASEO_FORGE_ARG_LITERAL%", + "query=query Test {\n viewer { login }\n}", + ], + { cwd: repoDir }, + ); + expect(JSON.parse(result.stdout)).toEqual([ + "%PASEO_FORGE_ARG_LITERAL%", + "query=query Test {\n viewer { login }\n}", + ]); + } finally { + process.env.PATH = originalPath; + if (originalVar === undefined) { + delete process.env.PASEO_FORGE_ARG_LITERAL; + } else { + process.env.PASEO_FORGE_ARG_LITERAL = originalVar; + } + } + }); }); describe("createCachedCliPathResolver", () => { @@ -175,4 +471,21 @@ describe("createCachedCliPathResolver", () => { await Promise.all([resolveCliPath(), resolveCliPath(), resolveCliPath()]); expect(calls).toBe(1); }); + + it("re-resolves after invalidate matches the cached path and ignores mismatched paths", async () => { + let calls = 0; + const resolveCliPath = createCachedCliPathResolver(async () => { + calls += 1; + return calls === 1 ? "/first/bin/forge-cli" : "/second/bin/forge-cli"; + }); + + await expect(resolveCliPath()).resolves.toBe("/first/bin/forge-cli"); + resolveCliPath.invalidate("/other/bin/forge-cli"); + await expect(resolveCliPath()).resolves.toBe("/first/bin/forge-cli"); + expect(calls).toBe(1); + + resolveCliPath.invalidate("/first/bin/forge-cli"); + await expect(resolveCliPath()).resolves.toBe("/second/bin/forge-cli"); + expect(calls).toBe(2); + }); }); diff --git a/packages/server/src/services/forge-cli-command.ts b/packages/server/src/services/forge-cli-command.ts index 798f79c65..e1f87192f 100644 --- a/packages/server/src/services/forge-cli-command.ts +++ b/packages/server/src/services/forge-cli-command.ts @@ -1,3 +1,4 @@ +import { access } from "node:fs/promises"; import { z } from "zod"; import { findExecutable } from "../executable-resolution/executable-resolution.js"; import { runGitCommand } from "../utils/run-git-command.js"; @@ -59,6 +60,7 @@ interface ProbeHostViaCliAuthStatusOptions { export interface ForgeCliRunnerOptions { cwd: string; envOverlay?: Record; + executablePath?: string; } export interface ForgeCliRunnerResult { @@ -85,6 +87,7 @@ export interface CreateForgeCliRunnerOptions { timeoutMs: number; isAuthFailureText: (text: string) => boolean; errorClasses: ForgeCliRunnerErrorClasses; + resolveExecutablePath?: () => Promise; } export interface ForgeCliRunnerFactory { @@ -95,6 +98,48 @@ export interface ForgeCliRunnerFactory { ) => Error; } +function hasPathSeparator(value: string): boolean { + return value.includes("/") || value.includes("\\"); +} + +const UNLAUNCHABLE_EXECUTABLE_ERROR_CODES = new Set([ + "ENOENT", + "EACCES", + "ENOEXEC", + "UNKNOWN", +]); + +function isWindowsBatchScript(executablePath: string): boolean { + if (process.platform !== "win32") { + return false; + } + const lower = executablePath.toLowerCase(); + return lower.endsWith(".cmd") || lower.endsWith(".bat"); +} + +async function isUnlaunchableExecutableError( + error: unknown, + executablePath: string, +): Promise { + if ( + typeof error === "object" && + error !== null && + "code" in error && + UNLAUNCHABLE_EXECUTABLE_ERROR_CODES.has((error as { code?: unknown }).code) + ) { + return true; + } + if (!isWindowsBatchScript(executablePath)) { + return false; + } + try { + await access(executablePath); + return false; + } catch { + return true; + } +} + /** * Shared shape behind the gh/glab/tea CLI adapters: an exec wrapper (10MB * maxBuffer, per-call env overlay merged over the binary's defaults, a @@ -102,13 +147,41 @@ export interface ForgeCliRunnerFactory { * trio. The three adapters differ only in the params passed here. */ export function createForgeCliRunner(options: CreateForgeCliRunnerOptions): ForgeCliRunnerFactory { - const run: ForgeCliRunner = (args, runOptions) => - execCommand(options.binary, args, { + const resolveBinaryPath = createCachedCliPathResolver( + options.resolveExecutablePath ?? (() => findExecutable(options.binary)), + ); + + function execResolved( + command: string, + args: string[], + runOptions: ForgeCliRunnerOptions, + ): Promise { + return execCommand(command, args, { cwd: runOptions.cwd, envOverlay: { ...options.envOverlay, ...runOptions.envOverlay }, maxBuffer: 10 * 1024 * 1024, timeout: options.timeoutMs, }); + } + + const run: ForgeCliRunner = async (args, runOptions) => { + const candidate = runOptions.executablePath ?? options.binary; + if (hasPathSeparator(candidate)) { + return execResolved(candidate, args, runOptions); + } + if (candidate === options.binary) { + return runWithResolvedCliPath({ + resolvePath: resolveBinaryPath, + createMissingError: options.errorClasses.createMissingError, + run: (command) => execResolved(command, args, runOptions), + }); + } + const resolved = await findExecutable(candidate); + if (!resolved) { + throw options.errorClasses.createMissingError(); + } + return execResolved(resolved, args, runOptions); + }; function normalizeError( error: unknown, @@ -179,37 +252,88 @@ export class ForgeCommandError extends Error { } } +export interface CachedCliPathResolver { + (): Promise; + invalidate(expectedPath?: string): void; +} + /** * Memoize a CLI path resolver (`findExecutable`) for the lifetime of a service - * instance. A found path is cached permanently; a miss (or a rejected probe) - * evicts the cache so a CLI installed after the daemon started is picked up - * on the next call instead of requiring a restart. Concurrent callers during - * resolution share the same in-flight promise. + * instance. A found path stays cached until invalidated (for example, when the + * binary disappears at launch time); a miss or rejected probe evicts the cache + * so a CLI installed after the daemon started is picked up on the next call. + * Concurrent callers during resolution share the same in-flight promise. */ export function createCachedCliPathResolver( resolve: () => Promise, -): () => Promise { +): CachedCliPathResolver { let pending: Promise | null = null; - return function resolveCliPath(): Promise { + let resolvedPath: string | null = null; + + const resolveCliPath = function resolveCliPath(): Promise { if (pending) { return pending; } const current: Promise = resolve() .then((path) => { - if (path === null && pending === current) { - pending = null; + if (pending === current) { + resolvedPath = path; + if (path === null) { + pending = null; + } } return path; }) .catch((error: unknown) => { if (pending === current) { + resolvedPath = null; pending = null; } throw error; }); pending = current; return current; + } as CachedCliPathResolver; + + resolveCliPath.invalidate = (expectedPath?: string) => { + if (expectedPath === undefined || resolvedPath === expectedPath) { + resolvedPath = null; + pending = null; + } }; + + return resolveCliPath; +} + +/** + * Execute an operation with a cached CLI executable path, invalidating and + * re-resolving once if the previously resolved executable disappeared from disk. + */ +export async function runWithResolvedCliPath(options: { + resolvePath: CachedCliPathResolver; + createMissingError: () => Error; + run: (executablePath: string) => Promise; +}): Promise { + const executablePath = await options.resolvePath(); + if (!executablePath) { + throw options.createMissingError(); + } + try { + return await options.run(executablePath); + } catch (error) { + if (!(await isUnlaunchableExecutableError(error, executablePath))) { + throw error; + } + options.resolvePath.invalidate(executablePath); + const refreshedPath = await options.resolvePath(); + if (!refreshedPath) { + throw options.createMissingError(); + } + if (refreshedPath === executablePath) { + throw error; + } + return options.run(refreshedPath); + } } export function bufferOrStringToString(value: unknown): string { @@ -304,7 +428,7 @@ export async function probeHostViaCliAuthStatus( return false; } try { - await execCommand(options.cli, ["auth", "status", "--hostname", options.host], { + await execCommand(cliPath, ["auth", "status", "--hostname", options.host], { envOverlay: options.envOverlay, timeout: CLI_AUTH_PROBE_TIMEOUT_MS, }); diff --git a/packages/server/src/services/gitea-service.test.ts b/packages/server/src/services/gitea-service.test.ts index b4aca78bd..d2235c617 100644 --- a/packages/server/src/services/gitea-service.test.ts +++ b/packages/server/src/services/gitea-service.test.ts @@ -1,3 +1,6 @@ +import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { delimiter, join } from "node:path"; import { describe, expect, it } from "vitest"; import type { PullRequestCommandStatus, PullRequestTimelineItem } from "./forge-service.js"; @@ -5,11 +8,13 @@ import { type CreateGiteaServiceOptions, createGiteaService, detectGiteaFamilySoftware, + probeGiteaHost, TeaAuthenticationError, TeaCommandError, type TeaCommandResult, type TeaCommandRunner, } from "./gitea-service.js"; +import { isPlatform } from "../test-utils/platform.js"; type Responder = (args: string[]) => TeaCommandResult | Promise; @@ -3304,3 +3309,95 @@ describe("detectGiteaFamilySoftware", () => { expect(software).toBe("gitea"); }); }); + +describe("Gitea CLI executable resolution", () => { + it("forwards the resolved tea executablePath to the command runner", async () => { + const seenExecutablePaths: Array = []; + const service = createGiteaService({ + resolveTeaPath: async () => "/opt/tea-cli/bin/tea", + resolveRemoteUrl: async () => "https://gitea.com/example-user/sample-repo.git", + runner: async (_args, options) => { + seenExecutablePaths.push(options.executablePath); + return ok("[]"); + }, + }); + + await service.searchIssuesAndPrs({ cwd: "/repo", query: "sample", kinds: ["github-pr"] }); + expect(seenExecutablePaths).toEqual(["/opt/tea-cli/bin/tea"]); + }); + + it("re-resolves tea and retries when the previously cached executable disappears", async () => { + let availablePath = "/first/bin/tea"; + const seenExecutablePaths: Array = []; + const service = createGiteaService({ + resolveTeaPath: async () => availablePath, + resolveRemoteUrl: async () => "https://gitea.com/example-user/sample-repo.git", + runner: async (_args, options) => { + seenExecutablePaths.push(options.executablePath); + if (options.executablePath !== availablePath) { + const error = new Error("spawn ENOENT") as NodeJS.ErrnoException; + error.code = "ENOENT"; + throw error; + } + return ok("[]"); + }, + }); + + await service.searchIssuesAndPrs({ cwd: "/repo", query: "first", kinds: ["github-pr"] }); + availablePath = "/second/bin/tea"; + const secondResult = await service.searchIssuesAndPrs({ + cwd: "/repo", + query: "second", + kinds: ["github-pr"], + }); + + expect(secondResult.featuresEnabled).toBe(true); + expect(seenExecutablePaths).toEqual(["/first/bin/tea", "/first/bin/tea", "/second/bin/tea"]); + }); + + it.skipIf(isPlatform("win32"))( + "probeGiteaHost and detectGiteaFamilySoftware invoke the resolved tea executable", + async () => { + const originalPath = process.env.PATH; + const tempDir = mkdtempSync(join(tmpdir(), "gitea-probe-cli-")); + const earlierDir = join(tempDir, "earlier-bin"); + const workingDir = join(tempDir, "working-bin"); + mkdirSync(earlierDir); + mkdirSync(workingDir); + + const shadowingTea = join(earlierDir, "tea"); + const workingTea = join(workingDir, "tea"); + writeFileSync( + workingTea, + `#!/bin/sh +if [ "$1" = "--version" ]; then + printf '#!/bin/sh\\nexit 1\\n' > "${shadowingTea}" + chmod 755 "${shadowingTea}" + exit 0 +fi +if [ "$1" = "login" ] && [ "$2" = "list" ]; then + printf '[{"name":"forge.acme.it","url":"https://forge.acme.it"}]' + exit 0 +fi +if [ "$1" = "api" ]; then + printf '{"version":"1.0+gitea"}' + printf 'HTTP/1.1 200 OK\\n' >&2 + exit 0 +fi +exit 1 +`, + ); + chmodSync(workingTea, 0o755); + + process.env.PATH = [earlierDir, workingDir, originalPath].filter(Boolean).join(delimiter); + try { + await expect(probeGiteaHost("forge.acme.it")).resolves.toBe(true); + rmSync(shadowingTea, { force: true }); + await expect(detectGiteaFamilySoftware("forge.acme.it")).resolves.toBe("forgejo"); + } finally { + process.env.PATH = originalPath; + rmSync(tempDir, { recursive: true, force: true }); + } + }, + ); +}); diff --git a/packages/server/src/services/gitea-service.ts b/packages/server/src/services/gitea-service.ts index 507c82759..780668c26 100644 --- a/packages/server/src/services/gitea-service.ts +++ b/packages/server/src/services/gitea-service.ts @@ -18,6 +18,7 @@ import { CLI_AUTH_PROBE_TIMEOUT_MS, defaultResolveRemoteUrl, parseCliJsonOutput, + runWithResolvedCliPath, ForgeCommandError, type ForgeCommandFailureParams, } from "./forge-cli-command.js"; @@ -137,6 +138,7 @@ export class TeaCommandError extends ForgeCommandError { export interface TeaCommandRunnerOptions { cwd: string; envOverlay?: Record; + executablePath?: string; } export interface TeaCommandResult { @@ -1030,7 +1032,7 @@ export async function probeGiteaHost(host: string): Promise { return false; } try { - const { stdout } = await execCommand("tea", ["login", "list", "-o", "json"], { + const { stdout } = await execCommand(teaPath, ["login", "list", "-o", "json"], { envOverlay: TEA_ENV, timeout: CLI_AUTH_PROBE_TIMEOUT_MS, }); @@ -1061,12 +1063,19 @@ export interface DetectGiteaFamilyOptions { runTea?: TeaApiRunner; } -async function defaultRunTea(args: string[]): Promise<{ stdout: string; stderr: string }> { - const { stdout, stderr } = await execCommand("tea", args, { - envOverlay: TEA_ENV, - timeout: GITEA_SOFTWARE_PROBE_TIMEOUT_MS, - }); - return { stdout, stderr }; +function createDefaultRunTea(): TeaApiRunner { + const resolveTea = createCachedCliPathResolver(resolveTeaPath); + return async (args: string[]): Promise<{ stdout: string; stderr: string }> => { + const teaPath = await resolveTea(); + if (!teaPath) { + throw new TeaCliMissingError(); + } + const { stdout, stderr } = await execCommand(teaPath, args, { + envOverlay: TEA_ENV, + timeout: GITEA_SOFTWARE_PROBE_TIMEOUT_MS, + }); + return { stdout, stderr }; + }; } const HTTP_STATUS_LINE = /^HTTP\/\d(?:\.\d)?\s+(\d{3})/m; @@ -1129,7 +1138,7 @@ export async function detectGiteaFamilySoftware( host: string, options: DetectGiteaFamilyOptions = {}, ): Promise { - const runTea = options.runTea ?? defaultRunTea; + const runTea = options.runTea ?? createDefaultRunTea(); const viaTea = await probeForgejoNamespaceByTea(host, runTea); if (viaTea !== null) { @@ -1208,12 +1217,12 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For args: string[], runOptions: TeaCommandRunnerOptions, ): Promise { - const teaPath = await resolveTea(); - if (!teaPath) { - throw new TeaCliMissingError(); - } try { - return await runner(args, runOptions); + return await runWithResolvedCliPath({ + resolvePath: resolveTea, + createMissingError: () => new TeaCliMissingError(), + run: (teaPath) => runner(args, { ...runOptions, executablePath: teaPath }), + }); } catch (error) { throw teaCliRunner.normalizeError(error, { args: redactTeaArgs(args), cwd: runOptions.cwd }); } diff --git a/packages/server/src/services/github-repository-search.test.ts b/packages/server/src/services/github-repository-search.test.ts index 88837d120..58b6ff49d 100644 --- a/packages/server/src/services/github-repository-search.test.ts +++ b/packages/server/src/services/github-repository-search.test.ts @@ -66,11 +66,11 @@ describe("GitHub repository search", () => { "--limit", "8", ], - options: { cwd: "/tmp" }, + options: { cwd: "/tmp", executablePath: "/usr/bin/gh" }, }, { args: ["config", "get", "git_protocol", "--host", "github.com"], - options: { cwd: "/tmp" }, + options: { cwd: "/tmp", executablePath: "/usr/bin/gh" }, }, ]); }); @@ -123,11 +123,11 @@ describe("GitHub repository search", () => { "--order", "desc", ], - options: { cwd: "/tmp" }, + options: { cwd: "/tmp", executablePath: "/usr/bin/gh" }, }, { args: ["config", "get", "git_protocol", "--host", "github.com"], - options: { cwd: "/tmp" }, + options: { cwd: "/tmp", executablePath: "/usr/bin/gh" }, }, ]); }); diff --git a/packages/server/src/services/github-service.test.ts b/packages/server/src/services/github-service.test.ts index e9875cb08..2d8dbdddb 100644 --- a/packages/server/src/services/github-service.test.ts +++ b/packages/server/src/services/github-service.test.ts @@ -5341,3 +5341,47 @@ it("skips pagination after the last exact observer releases its PR", async () => vi.useRealTimers(); } }); + +it("forwards the resolved gh executablePath to the command runner", async () => { + const seenExecutablePaths: Array = []; + const service = createGitHubService({ + resolveGhPath: async () => "/opt/github-cli/bin/gh", + resolveRepoHost: async () => null, + runner: async (_args, options) => { + seenExecutablePaths.push(options.executablePath); + return { stdout: "[]", stderr: "" }; + }, + }); + + await service.searchIssuesAndPrs({ cwd: "/repo", query: "test", kinds: ["github-issue"] }); + expect(seenExecutablePaths).toEqual(["/opt/github-cli/bin/gh"]); +}); + +it("re-resolves gh and retries when the previously cached executable disappears", async () => { + let availablePath = "/first/bin/gh"; + const seenExecutablePaths: Array = []; + const service = createGitHubService({ + resolveGhPath: async () => availablePath, + resolveRepoHost: async () => null, + runner: async (_args, options) => { + seenExecutablePaths.push(options.executablePath); + if (options.executablePath !== availablePath) { + const error = new Error("spawn ENOENT") as NodeJS.ErrnoException; + error.code = "ENOENT"; + throw error; + } + return { stdout: "[]", stderr: "" }; + }, + }); + + await service.searchIssuesAndPrs({ cwd: "/repo", query: "first", kinds: ["github-issue"] }); + availablePath = "/second/bin/gh"; + const secondResult = await service.searchIssuesAndPrs({ + cwd: "/repo", + query: "second", + kinds: ["github-issue"], + }); + + expect(secondResult.featuresEnabled).toBe(true); + expect(seenExecutablePaths).toEqual(["/first/bin/gh", "/first/bin/gh", "/second/bin/gh"]); +}); diff --git a/packages/server/src/services/github-service.ts b/packages/server/src/services/github-service.ts index 556b307de..0110e68a5 100644 --- a/packages/server/src/services/github-service.ts +++ b/packages/server/src/services/github-service.ts @@ -22,12 +22,15 @@ import { import { execCommand } from "../utils/spawn.js"; import { resolveSshHostname } from "../utils/ssh-hostname.js"; import { + type CachedCliPathResolver, CLI_AUTH_PROBE_TIMEOUT_MS, + createCachedCliPathResolver, createForgeCliRunner, ForgeAuthenticationError, ForgeCliMissingError, parseCliJsonOutput, probeHostViaCliAuthStatus, + runWithResolvedCliPath, ForgeCommandError, type ForgeCommandFailureParams, } from "./forge-cli-command.js"; @@ -966,7 +969,7 @@ interface CacheEntry { interface GitHubServiceDependencies { runner: GitHubCommandRunner; - resolveGhPath: () => Promise; + resolveGhPath: CachedCliPathResolver; now: () => number; /** * GitHub Enterprise host for a workspace, or null for github.com (where `gh` @@ -991,6 +994,7 @@ interface GitHubServiceDependencies { export interface GitHubCommandRunnerOptions { cwd: string; envOverlay?: Record; + executablePath?: string; } export interface GitHubCommandResult { @@ -1148,7 +1152,7 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G const ttlMs = options.ttlMs ?? DEFAULT_GITHUB_CACHE_TTL_MS; const deps: GitHubServiceDependencies = { runner: options.runner ?? runGhCommand, - resolveGhPath: options.resolveGhPath ?? resolveGhPath, + resolveGhPath: createCachedCliPathResolver(options.resolveGhPath ?? resolveGhPath), now: options.now ?? Date.now, resolveRepoHost: options.resolveRepoHost ?? resolveGitHubEnterpriseHost, resolveRepoSlug: options.resolveRepoSlug ?? resolveGitHubSlugFromOrigin, @@ -1367,8 +1371,8 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G runOptions: GitHubCommandRunnerOptions, explicitHost?: string, ): Promise { - const ghPath = await deps.resolveGhPath(); - if (!ghPath) { + const initialGhPath = await deps.resolveGhPath(); + if (!initialGhPath) { throw new GitHubCliMissingError(); } // Route every gh invocation to the workspace's host. `gh api`/`graphql` @@ -1376,11 +1380,15 @@ export function createGitHubService(options: CreateGitHubServiceOptions = {}): G // which silently queries the wrong server on GitHub Enterprise. GH_HOST is // safe even for auto-routing subcommands because it matches the repo's host. const host = explicitHost ?? (await resolveRepoHostCached(runOptions.cwd)); - const effectiveOptions: GitHubCommandRunnerOptions = host + const baseOptions: GitHubCommandRunnerOptions = host ? { ...runOptions, envOverlay: { ...runOptions.envOverlay, GH_HOST: host } } : runOptions; try { - const result = await deps.runner(args, effectiveOptions); + const result = await runWithResolvedCliPath({ + resolvePath: deps.resolveGhPath, + createMissingError: () => new GitHubCliMissingError(), + run: (ghPath) => deps.runner(args, { ...baseOptions, executablePath: ghPath }), + }); return result.stdout.trim(); } catch (error) { throw githubCliRunner.normalizeError(error, { @@ -3169,7 +3177,8 @@ const githubCliRunner = createForgeCliRunner({ timeoutMs: GITHUB_COMMAND_TIMEOUT_MS, isAuthFailureText, errorClasses: { - isAlreadyClassified: (candidate) => candidate instanceof GitHubAuthenticationError, + isAlreadyClassified: (candidate) => + candidate instanceof GitHubAuthenticationError || candidate instanceof GitHubCliMissingError, isCommandError: (candidate): candidate is GitHubCommandError => candidate instanceof GitHubCommandError, createAuthError: (stderr) => new GitHubAuthenticationError({ stderr }), diff --git a/packages/server/src/services/gitlab-service.test.ts b/packages/server/src/services/gitlab-service.test.ts index cb2034a2c..b662c84d4 100644 --- a/packages/server/src/services/gitlab-service.test.ts +++ b/packages/server/src/services/gitlab-service.test.ts @@ -1654,4 +1654,49 @@ describe("createGitLabService", () => { GlabCommandError, ); }); + + it("forwards the resolved glab executablePath to the command runner", async () => { + const seenExecutablePaths: Array = []; + const service = createGitLabService({ + resolveGlabPath: async () => "/opt/gitlab-cli/bin/glab", + resolveRemoteUrl: async () => "git@gitlab.example.com:example-group/example-project.git", + runner: async (_args, options) => { + seenExecutablePaths.push(options.executablePath); + return ok("[]"); + }, + }); + + await expect(service.isAuthenticated({ cwd: "/repo" })).resolves.toBe(true); + await service.searchIssuesAndPrs({ cwd: "/repo", query: "release", kinds: ["github-pr"] }); + expect(seenExecutablePaths).toEqual(["/opt/gitlab-cli/bin/glab", "/opt/gitlab-cli/bin/glab"]); + }); + + it("re-resolves glab and retries when the previously cached executable disappears", async () => { + let availablePath = "/first/bin/glab"; + const seenExecutablePaths: Array = []; + const service = createGitLabService({ + resolveGlabPath: async () => availablePath, + resolveRemoteUrl: async () => "git@gitlab.example.com:example-group/example-project.git", + runner: async (_args, options) => { + seenExecutablePaths.push(options.executablePath); + if (options.executablePath !== availablePath) { + const error = new Error("spawn ENOENT") as NodeJS.ErrnoException; + error.code = "ENOENT"; + throw error; + } + return ok("[]"); + }, + }); + + await service.searchIssuesAndPrs({ cwd: "/repo", query: "first", kinds: ["github-pr"] }); + availablePath = "/second/bin/glab"; + const secondResult = await service.searchIssuesAndPrs({ + cwd: "/repo", + query: "second", + kinds: ["github-pr"], + }); + + expect(secondResult.featuresEnabled).toBe(true); + expect(seenExecutablePaths).toEqual(["/first/bin/glab", "/first/bin/glab", "/second/bin/glab"]); + }); }); diff --git a/packages/server/src/services/gitlab-service.ts b/packages/server/src/services/gitlab-service.ts index 6f65a127a..6da7d4b06 100644 --- a/packages/server/src/services/gitlab-service.ts +++ b/packages/server/src/services/gitlab-service.ts @@ -9,6 +9,7 @@ import { defaultResolveRemoteUrl, parseCliJsonOutput, probeHostViaCliAuthStatus, + runWithResolvedCliPath, ForgeCommandError, type ForgeCommandFailureParams, } from "./forge-cli-command.js"; @@ -97,6 +98,7 @@ export class GlabCommandError extends ForgeCommandError { export interface GlabCommandRunnerOptions { cwd: string; envOverlay?: Record; + executablePath?: string; } export interface GlabCommandResult { @@ -933,12 +935,12 @@ export function createGitLabService(options: CreateGitLabServiceOptions = {}): F args: string[], runOptions: GlabCommandRunnerOptions, ): Promise { - const glabPath = await resolveGlab(); - if (!glabPath) { - throw new GlabCliMissingError(); - } try { - return await runner(args, runOptions); + return await runWithResolvedCliPath({ + resolvePath: resolveGlab, + createMissingError: () => new GlabCliMissingError(), + run: (glabPath) => runner(args, { ...runOptions, executablePath: glabPath }), + }); } catch (error) { throw glabCliRunner.normalizeError(error, { args, cwd: runOptions.cwd }); } @@ -1191,7 +1193,15 @@ export function createGitLabService(options: CreateGitLabServiceOptions = {}): F return false; } try { - await runner(["auth", "status", "--hostname", host], { cwd: input.cwd }); + await runWithResolvedCliPath({ + resolvePath: resolveGlab, + createMissingError: () => new GlabCliMissingError(), + run: (resolvedPath) => + runner(["auth", "status", "--hostname", host], { + cwd: input.cwd, + executablePath: resolvedPath, + }), + }); return true; } catch { return false;