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): address review findings on the Claude Agent provider
Elian Doranc768eb01bb6c
diff --git a/apps/server/src/services/llm/providers/claude_agent.spec.ts b/apps/server/src/services/llm/providers/claude_agent.spec.tsindex 3af1ecddf0..8e34a10c46 100644--- a/apps/server/src/services/llm/providers/claude_agent.spec.ts+++ b/apps/server/src/services/llm/providers/claude_agent.spec.ts@@ -32,9 +32,9 @@ const buildNoteHintMock = vi.hoisted(() => vi.fn((noteId: string): string | nullvi.mock("./note_hint.js", () => ({ buildNoteHint: buildNoteHintMock }));// BYO binary resolution shells out to the user's `claude`; stub it so tests-// don't depend on a real install. Returns a path by default; can be made to-// throw (missing binary) per-test.-const resolveClaudeBinaryMock = vi.hoisted(() => vi.fn(() => "/usr/bin/claude"));+// don't depend on a real install. Resolves a path by default; can be made to+// reject (missing binary) per-test.+const resolveClaudeBinaryMock = vi.hoisted(() => vi.fn(async () => "/usr/bin/claude"));vi.mock("./claude_binary.js", () => ({ resolveClaudeBinaryPath: resolveClaudeBinaryMock }));// Attachment resolution reads bytes out of Becca, which the core mock above@@ -371,9 +371,9 @@ describe("ClaudeAgentProvider.chatChunks", () => {});it("surfaces a friendly error (and never spawns) when Claude Code isn't installed", async () => {- resolveClaudeBinaryMock.mockImplementationOnce(() => {- throw new Error("Claude Code CLI not found. Install it and run `claude /login`...");- });+ resolveClaudeBinaryMock.mockRejectedValueOnce(+ new Error("Claude Code CLI not found. Install it and run `claude /login`...")+ );const provider = new ClaudeAgentProvider();const chunks = await collect(provider.chatChunks([{ role: "user", content: "hi" }], {}));@@ -484,6 +484,19 @@ describe("ClaudeAgentProvider.chatChunks", () => {expect(errors[0].error).toContain("Failed to start Claude Code");});+ it("does not spawn the agent when the signal is already aborted at entry", async () => {+ // An abort listener alone would never fire for a pre-aborted signal —+ // the provider must bail out before spawning the subprocess.+ const controller = new AbortController();+ controller.abort();++ const provider = new ClaudeAgentProvider();+ const chunks = await collect(provider.chatChunks([{ role: "user", content: "hi" }], {}, controller.signal));++ expect(chunks).toEqual([]);+ expect(queryMock).not.toHaveBeenCalled();+ });+it("rejects a conversation that does not end with a user message", async () => {const provider = new ClaudeAgentProvider();const chunks = await collect(provider.chatChunks([{ role: "assistant", content: "hi" }], {}));diff --git a/apps/server/src/services/llm/providers/claude_agent.ts b/apps/server/src/services/llm/providers/claude_agent.tsindex c1cf5ae4f9..81ea678c19 100644--- a/apps/server/src/services/llm/providers/claude_agent.ts+++ b/apps/server/src/services/llm/providers/claude_agent.ts@@ -171,6 +171,13 @@ export class ClaudeAgentProvider implements LlmProvider {}async *chatChunks(messages: LlmMessage[], config: LlmProviderConfig, signal?: AbortSignal): AsyncIterable<LlmStreamChunk> {+ if (signal?.aborted) {+ // The abort listener below would never fire for an already-aborted+ // signal — and the client is gone anyway, so don't spawn an agent+ // subprocess nobody will read from.+ return;+ }+const conversation = messages.filter(m => m.role !== "system");const lastMessage = conversation[conversation.length - 1];if (!lastMessage || lastMessage.role !== "user") {@@ -223,7 +230,7 @@ export class ClaudeAgentProvider implements LlmProvider {const response = query({prompt,options: {- ...this.buildBaseOptions(config),+ ...await this.buildBaseOptions(config),systemPrompt: this.composeSystemPrompt(messages, config),model,resume,@@ -380,7 +387,7 @@ export class ClaudeAgentProvider implements LlmProvider {const response = query({prompt: `Generate a short title (at most 5 words) summarizing this chat message. Reply with only the title, no quotes or punctuation around it:\n\n${firstMessage.substring(0, 500)}`,options: {- ...this.buildBaseOptions({ enableNoteTools: false }),+ ...await this.buildBaseOptions({ enableNoteTools: false }),systemPrompt: "You generate short, descriptive titles. Reply with only the title text — no quotes, no punctuation around it.",model: TITLE_MODEL,maxTurns: 1,@@ -417,7 +424,7 @@ export class ClaudeAgentProvider implements LlmProvider {}/** Options shared by every agent invocation. */- private buildBaseOptions(config: Pick<LlmProviderConfig, "enableNoteTools" | "enableWebSearch" | "enableExtendedThinking">): AgentOptions {+ private async buildBaseOptions(config: Pick<LlmProviderConfig, "enableNoteTools" | "enableWebSearch" | "enableExtendedThinking">): Promise<AgentOptions> {// Built-in Claude Code tools (file access, bash, …) stay disabled — the// agent runs on the server host and must only ever touch notes. Web// search is the one opt-in exception.@@ -427,7 +434,7 @@ export class ClaudeAgentProvider implements LlmProvider {const options: AgentOptions = {// Bring-your-own-binary: the SDK's bundled native binary is stripped// at install time; drive the user's own installed Claude Code CLI.- pathToClaudeCodeExecutable: resolveClaudeBinaryPath(),+ pathToClaudeCodeExecutable: await resolveClaudeBinaryPath(),cwd: getAgentCwd(),tools: builtinTools,settingSources: [],diff --git a/apps/server/src/services/llm/providers/claude_binary.spec.ts b/apps/server/src/services/llm/providers/claude_binary.spec.tsnew file mode 100644index 0000000000..50b37718e4--- /dev/null+++ b/apps/server/src/services/llm/providers/claude_binary.spec.ts@@ -0,0 +1,70 @@+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>());+vi.mock("child_process", () => ({ execFile: execFileMock }));++const existsSyncMock = vi.hoisted(() => vi.fn(() => true));+vi.mock("fs", () => ({ existsSync: existsSyncMock }));++vi.mock("@triliumnext/core", () => ({ getLog: () => ({ info: vi.fn(), error: vi.fn() }) }));++const { resetClaudeBinaryCache, resolveClaudeBinaryPath } = await import("./claude_binary.js");++describe("resolveClaudeBinaryPath", () => {+ const originalOverride = process.env.TRILIUM_CLAUDE_CODE_PATH;++ beforeEach(() => {+ resetClaudeBinaryCache();+ execFileMock.mockReset();+ existsSyncMock.mockReset();+ existsSyncMock.mockReturnValue(true);+ process.env.TRILIUM_CLAUDE_CODE_PATH = "/opt/claude/claude";+ });++ afterEach(() => {+ if (originalOverride === undefined) {+ delete process.env.TRILIUM_CLAUDE_CODE_PATH;+ } else {+ process.env.TRILIUM_CLAUDE_CODE_PATH = originalOverride;+ }+ });++ function probeSucceeds() {+ execFileMock.mockImplementation((_binary, _args, _options, cb) => cb(null, { stdout: "2.0.1\n", stderr: "" }));+ }++ it("probes the overridden binary once and shares the result across calls (even concurrent ones)", async () => {+ probeSucceeds();++ const [first, second] = await Promise.all([resolveClaudeBinaryPath(), resolveClaudeBinaryPath()]);+ const third = await resolveClaudeBinaryPath();++ expect(first).toBe("/opt/claude/claude");+ expect(second).toBe("/opt/claude/claude");+ expect(third).toBe("/opt/claude/claude");+ expect(execFileMock).toHaveBeenCalledTimes(1);+ expect(execFileMock.mock.calls[0][0]).toBe("/opt/claude/claude");+ expect(execFileMock.mock.calls[0][1]).toEqual(["--version"]);+ });++ 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")));++ await expect(resolveClaudeBinaryPath()).rejects.toThrow(/failed to run.*claude \/login/s);++ // The failure must not be cached — a later (fixed) install is picked up.+ probeSucceeds();+ await expect(resolveClaudeBinaryPath()).resolves.toBe("/opt/claude/claude");+ expect(execFileMock).toHaveBeenCalledTimes(2);+ });++ it("rejects when TRILIUM_CLAUDE_CODE_PATH points at a missing file, without probing", async () => {+ existsSyncMock.mockReturnValue(false);++ await expect(resolveClaudeBinaryPath()).rejects.toThrow(/TRILIUM_CLAUDE_CODE_PATH/);+ expect(execFileMock).not.toHaveBeenCalled();+ });+});diff --git a/apps/server/src/services/llm/providers/claude_binary.ts b/apps/server/src/services/llm/providers/claude_binary.tsindex 8fbbd6e61b..c31ccf6539 100644--- a/apps/server/src/services/llm/providers/claude_binary.ts+++ b/apps/server/src/services/llm/providers/claude_binary.ts@@ -15,40 +15,54 @@*/import { getLog } from "@triliumnext/core";-import { execFileSync } from "child_process";+import { execFile } from "child_process";import { existsSync } from "fs";import path from "path";+import { promisify } from "util";-/** Cached only on success, so a later install is picked up without a restart. */-let cachedPath: string | undefined;+const execFileAsync = promisify(execFile);-export function resolveClaudeBinaryPath(): string {- if (cachedPath) {- return cachedPath;+/**+ * The in-flight/successful resolution. Caching the promise lets concurrent+ * first calls share one probe; a failed probe clears it so a later install is+ * picked up without a restart.+ */+let cachedResolution: Promise<string> | undefined;++export function resolveClaudeBinaryPath(): Promise<string> {+ if (!cachedResolution) {+ cachedResolution = probeBinary().catch((err: unknown) => {+ cachedResolution = undefined;+ throw err;+ });}+ return cachedResolution;+}++/** For tests: forget the probed binary so the next call re-resolves. */+export function resetClaudeBinaryCache(): void {+ cachedResolution = undefined;+}+async function probeBinary(): Promise<string> {const binary = locateBinary();// 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.let version: string;try {- version = execFileSync(binary, ["--version"], { timeout: 15000, encoding: "utf8" }).trim();+ version = (await execFileAsync(binary, ["--version"], { timeout: 15000, encoding: "utf8" })).stdout.trim();} catch (err) {const detail = err instanceof Error ? err.message : String(err);throw new Error(`Found Claude Code at "${binary}" but it failed to run (${detail}). Ensure it is installed correctly and that you've run \`claude /login\` on the machine running the Trilium server.`);}getLog().info(`Claude Agent provider: using Claude Code at ${binary} (${version})`);- cachedPath = binary;return binary;}-/** For tests: forget the probed binary so the next call re-resolves. */-export function resetClaudeBinaryCache(): void {- cachedPath = undefined;-}-function locateBinary(): string {const override = process.env.TRILIUM_CLAUDE_CODE_PATH?.trim();if (override) {