Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
fix(llm): stop the Copilot CLI probe hanging on VS Code's bootstrapper
Elian Doran5098e06c7767
diff --git a/apps/client/src/widgets/type_widgets/options/llm/AddProviderModal.css b/apps/client/src/widgets/type_widgets/options/llm/AddProviderModal.cssindex 57a6896598..5b77827182 100644--- a/apps/client/src/widgets/type_widgets/options/llm/AddProviderModal.css+++ b/apps/client/src/widgets/type_widgets/options/llm/AddProviderModal.css@@ -11,6 +11,11 @@margin-bottom: 1rem;}+ .no-items {+ word-break: break-word;+ text-align: left;+ }+.tn-card:last-child {margin-bottom: 0;}diff --git a/apps/server/src/services/llm/providers/copilot_binary.spec.ts b/apps/server/src/services/llm/providers/copilot_binary.spec.tsindex 2cbd9ebb9a..0a77606c90 100644--- a/apps/server/src/services/llm/providers/copilot_binary.spec.ts+++ b/apps/server/src/services/llm/providers/copilot_binary.spec.ts@@ -1,10 +1,11 @@import path from "path";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-// The probe drives the real execFile through util.promisify's callback-// fallback, so the mock receives (binary, args, options, callback).-type ExecFileCallback = (err: Error | null, result?: { stdout: string; stderr: string }) => void;-const execFileMock = vi.hoisted(() => vi.fn<(binary: string, args: string[], options: object, cb: ExecFileCallback) => void>());+type ExecFileCallback = (err: Error | null, stdout: string, stderr: string) => void;+// The probe keeps the child so it can close its stdin; a bare `stdin.end` is+// all the fake needs to provide.+const fakeChild = vi.hoisted(() => ({ stdin: { end: vi.fn() } }));+const execFileMock = vi.hoisted(() => vi.fn<(binary: string, args: string[], options: object, cb: ExecFileCallback) => typeof fakeChild>());vi.mock("child_process", () => ({ execFile: execFileMock }));const existsSyncMock = vi.hoisted(() => vi.fn((_path: string) => true));@@ -28,6 +29,7 @@ describe("resolveCopilotBinaryPath", () => {// stay about the inherited PATH (binary_lookup.spec.ts covers it).delete process.env.SHELL;execFileMock.mockReset();+ fakeChild.stdin.end.mockReset();existsSyncMock.mockReset();existsSyncMock.mockReturnValue(true);process.env.TRILIUM_COPILOT_PATH = "/opt/copilot/copilot";@@ -55,7 +57,18 @@ describe("resolveCopilotBinaryPath", () => {}function probeSucceeds() {- execFileMock.mockImplementation((_binary, _args, _options, cb) => cb(null, { stdout: "1.0.71\n", stderr: "" }));+ execFileMock.mockImplementation((_binary, _args, _options, cb) => {+ cb(null, "1.0.71\n", "");+ return fakeChild;+ });+ }++ /** One probe that ends with `err`, after the child printed `stdout`/`stderr`. */+ function probeFails(err: Error | string, stdout = "", stderr = "") {+ execFileMock.mockImplementationOnce((_binary, _args, _options, cb) => {+ cb(err as Error, stdout, stderr);+ return fakeChild;+ });}it("probes the overridden binary once and shares the result across calls (even concurrent ones)", async () => {@@ -70,12 +83,14 @@ describe("resolveCopilotBinaryPath", () => {expect(execFileMock).toHaveBeenCalledTimes(1);expect(execFileMock.mock.calls[0][0]).toBe("/opt/copilot/copilot");expect(execFileMock.mock.calls[0][1]).toEqual(["--version"]);+ // A wrapper that prompts on stdin must read end-of-file, not wait.+ expect(fakeChild.stdin.end).toHaveBeenCalledTimes(1);});it("rejects with an actionable message on a broken binary and re-probes on the next call", async () => {- execFileMock.mockImplementationOnce((_binary, _args, _options, cb) => cb(new Error("spawn ENOENT")));+ probeFails(new Error("spawn ENOENT"));- await expect(resolveCopilotBinaryPath()).rejects.toThrow(/failed to run.*copilot login/s);+ await expect(resolveCopilotBinaryPath()).rejects.toThrow(/\nbut it failed to run: spawn ENOENT\n\nEnsure .*copilot login/);// The failure must not be cached — a later (fixed) install is picked up.probeSucceeds();@@ -84,9 +99,45 @@ describe("resolveCopilotBinaryPath", () => {});it("stringifies non-Error probe failures into the actionable message", async () => {- execFileMock.mockImplementationOnce((_binary, _args, _options, cb) => cb("killed by signal" as unknown as Error));+ probeFails("killed by signal");++ await expect(resolveCopilotBinaryPath()).rejects.toThrow(/failed to run: killed by signal\n/);+ });++ it("names the timeout and quotes the output instead of the generic 'Command failed'", async () => {+ // What execFile reports when the timeout kills the child: here VS+ // Code's Copilot Chat bootstrapper shim, stuck on its install prompt.+ const killed = Object.assign(new Error('Command failed: "copilot.bat" --version\n'), { killed: true, signal: "SIGTERM" });+ probeFails(killed, "Cannot find GitHub Copilot CLI (https://docs.github.com/copilot-cli)\n", "");- await expect(resolveCopilotBinaryPath()).rejects.toThrow(/failed to run \(killed by signal\)/);+ await expect(resolveCopilotBinaryPath()).rejects.toThrow(+ "but it failed to run: did not exit within 15 seconds.\n\nIt printed:\nCannot find GitHub Copilot CLI (https://docs.github.com/copilot-cli)\n\nEnsure"+ );+ });++ it("rejects a binary that exits cleanly without reporting a version, quoting what it printed", async () => {+ // The same shim with its stdin closed: the prompt reads end-of-file,+ // the install is declined on the user's behalf and it exits 0.+ execFileMock.mockImplementationOnce((_binary, _args, _options, cb) => {+ cb(null, "Cannot find GitHub Copilot CLI (https://docs.github.com/copilot-cli)\n", "Split-Path : Cannot bind argument\r\n");+ return fakeChild;+ });++ await expect(resolveCopilotBinaryPath()).rejects.toThrow(new Error([+ "Found GitHub Copilot CLI at:",+ "/opt/copilot/copilot",+ "but it failed to run: did not report a version.",+ "",+ "It printed:",+ "Cannot find GitHub Copilot CLI (https://docs.github.com/copilot-cli)",+ "Split-Path : Cannot bind argument",+ "",+ "Ensure it is installed correctly and that you've run `copilot login` on the machine running the Trilium server."+ ].join("\n")));++ // Not cached either: installing the real CLI fixes it without a restart.+ probeSucceeds();+ await expect(resolveCopilotBinaryPath()).resolves.toBe("/opt/copilot/copilot");});it("rejects when TRILIUM_COPILOT_PATH points at a missing file, without probing", async () => {diff --git a/apps/server/src/services/llm/providers/copilot_binary.ts b/apps/server/src/services/llm/providers/copilot_binary.tsindex ee0aba736e..122ff88d11 100644--- a/apps/server/src/services/llm/providers/copilot_binary.ts+++ b/apps/server/src/services/llm/providers/copilot_binary.ts@@ -11,16 +11,29 @@* (see `findOnPath`, which also asks the login shell). The resolved binary is* probed with `--version` once so a broken/absent install surfaces as a clear,* actionable error instead of an opaque spawn failure mid-chat.+ *+ * The probe must cope with a wrapper standing in for the CLI: VS Code's+ * Copilot Chat extension puts a `copilot` bootstrapper on the PATH of its+ * terminals that, when the real CLI is not installed, prints why and asks on+ * stdin whether to install it. The probe closes stdin so the question reads+ * end-of-file instead of waiting out the timeout, and requires a version+ * number in the output, because the wrapper then exits 0 without one.*/import { getLog } from "@triliumnext/core";import { execFile } from "child_process";import { existsSync } from "fs";-import { promisify } from "util";import { findOnPath } from "./binary_lookup.js";-const execFileAsync = promisify(execFile);+const PROBE_TIMEOUT_MS = 15000;++/** What `--version` printed before the probe failed. */+class ProbeError extends Error {+ constructor(message: string, readonly output: string) {+ super(message);+ }+}/*** The in-flight/successful resolution. Caching the promise lets concurrent@@ -50,23 +63,64 @@ async function probeBinary(): Promise<string> {// Probe once: confirms the binary actually runs on this host (catches a// wrong-arch/broken install) and records the version for diagnostics.// Async on purpose — this runs on the first chat request, and a sync probe- // would freeze the whole server for up to the 15 s timeout.+ // would freeze the whole server for up to the timeout.let version: string;try {- // `shell` is required for the .cmd/.bat shims npm creates on Windows —- // Node refuses to spawn those directly (CVE-2024-27980). With a shell- // the command line is not auto-quoted, so quote the path ourselves.- const shell = needsShell(binary);- version = (await execFileAsync(shell ? `"${binary}"` : binary, ["--version"], { timeout: 15000, encoding: "utf8", shell })).stdout.trim();+ const output = await runVersionProbe(binary);+ const versionLine = output.split("\n").find((line) => /\d+\.\d+\.\d+/.test(line));+ if (!versionLine) {+ throw new ProbeError("did not report a version", output);+ }+ version = versionLine.trim();} catch (err) {- const detail = err instanceof Error ? err.message : String(err);- throw new Error(`Found GitHub Copilot CLI at "${binary}" but it failed to run (${detail}). Ensure it is installed correctly and that you've run \`copilot login\` on the machine running the Trilium server.`);+ throw new Error([+ "Found GitHub Copilot CLI at:",+ binary,+ `but it failed to run: ${describeProbeFailure(err)}`,+ "",+ "Ensure it is installed correctly and that you've run `copilot login` on the machine running the Trilium server."+ ].join("\n"));}getLog().info(`Copilot Agent provider: using GitHub Copilot CLI at ${binary} (${version})`);return binary;}+/**+ * Runs `binary --version` with stdin closed and resolves with everything it+ * printed, stdout before stderr. Rejects with a `ProbeError` that names the+ * timeout, or carries execFile's own message for a spawn or exit failure.+ */+function runVersionProbe(binary: string): Promise<string> {+ return new Promise((resolve, reject) => {+ // `shell` is required for the .cmd/.bat shims npm creates on Windows —+ // Node refuses to spawn those directly (CVE-2024-27980). With a shell+ // the command line is not auto-quoted, so quote the path ourselves.+ const shell = needsShell(binary);+ const options = { timeout: PROBE_TIMEOUT_MS, encoding: "utf8" as const, shell };+ const child = execFile(shell ? `"${binary}"` : binary, ["--version"], options, (err, stdout, stderr) => {+ const output = [stdout, stderr].map((text) => text.trim()).filter(Boolean).join("\n");+ if (!err) {+ resolve(output);+ } else if (err.killed) {+ reject(new ProbeError(`did not exit within ${PROBE_TIMEOUT_MS / 1000} seconds`, output));+ } else {+ // execFile's message already quotes stderr after the command.+ reject(new ProbeError(err instanceof Error ? err.message : String(err), stdout.trim()));+ }+ });+ child.stdin?.end();+ });+}++/** The reason in the "failed to run" error, followed by the output on lines of its own when there is any. */+function describeProbeFailure(err: unknown): string {+ if (err instanceof ProbeError && err.output) {+ return `${err.message}.\n\nIt printed:\n${err.output}`;+ }+ return err instanceof Error ? err.message.trim() : String(err);+}+async function locateBinary(): Promise<string> {const override = process.env.TRILIUM_COPILOT_PATH?.trim();if (override) {