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
test(llm): full patch coverage for the Claude Agent provider stack
Elian Doran40dfb6063c00
diff --git a/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.spec.tsx b/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.spec.tsxnew file mode 100644index 0000000000..839b623b2e--- /dev/null+++ b/apps/client/src/widgets/type_widgets/llm_chat/useLlmChat.spec.tsx@@ -0,0 +1,147 @@+import { render } from "preact";+import { act } from "preact/test-utils";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++const getAvailableModelsMock = vi.hoisted(() => vi.fn());+const streamChatCompletionMock = vi.hoisted(() => vi.fn());+vi.mock("../../../services/llm_chat.js", () => ({+ getAvailableModels: getAvailableModelsMock,+ streamChatCompletion: streamChatCompletionMock+}));++// useTriliumEvent subscribes to the app-wide event bus; stub it so the hook+// renders without the full app context.+vi.mock("../../react/hooks.js", async (importOriginal) => ({+ ...(await importOriginal<typeof import("../../react/hooks.js")>()),+ useTriliumEvent: vi.fn()+}));++// Uninitialized i18n returns undefined; echo the key so labels are assertable.+vi.mock("../../../services/i18n.js", async (importOriginal) => ({+ ...(await importOriginal<typeof import("../../../services/i18n.js")>()),+ t: (key: string) => key+}));++import { useLlmChat } from "./useLlmChat.js";++type LlmChatApi = ReturnType<typeof useLlmChat>;+type LlmChatOptions = Parameters<typeof useLlmChat>[1];++const MODELS = [+ { id: "sonnet", name: "Sonnet", provider: "claude-agent", isDefault: true, isSubscription: true },+ { id: "opus", name: "Opus", provider: "anthropic", costMultiplier: 5 },+ { id: "mini", name: "Mini", provider: "openai" }+];++describe("useLlmChat", () => {+ let captured: LlmChatApi | undefined;+ let host: HTMLDivElement | undefined;++ function Harness(props: { options?: LlmChatOptions }) {+ captured = useLlmChat(undefined, props.options);+ return null;+ }++ /** The hook API as of the latest render. */+ function api(): LlmChatApi {+ if (!captured) {+ throw new Error("useLlmChat harness has not rendered");+ }+ return captured;+ }++ async function mountChat(options?: LlmChatOptions) {+ host = document.createElement("div");+ document.body.appendChild(host);+ const target = host;+ // Two act passes: render, then flush the model-fetch promise.+ await act(async () => {+ render(<Harness options={options} />, target);+ });+ await act(async () => {});+ }++ beforeEach(() => {+ getAvailableModelsMock.mockResolvedValue(MODELS);+ // Minimal successful stream: finish immediately with no content.+ streamChatCompletionMock.mockImplementation(async (_messages, _options, callbacks) => {+ callbacks.onDone();+ });+ });++ afterEach(() => {+ if (host) {+ render(null, host);+ host.remove();+ host = undefined;+ }+ captured = undefined;+ getAvailableModelsMock.mockReset();+ streamChatCompletionMock.mockReset();+ });++ it("selects the default model with its provider and annotates model costs", async () => {+ await mountChat();++ // The default model's provider is recorded alongside the model, so two+ // providers exposing the same model ID stay distinguishable.+ expect(api().selectedModel).toBe("sonnet");+ expect(api().selectedProvider).toBe("claude-agent");+ expect(api().hasProvider).toBe(true);++ const costById = new Map(api().availableModels.map((m) => [m.id, m.costDescription]));+ expect(costById.get("sonnet")).toBe("llm_chat.model_cost_included"); // subscription → "included" label+ expect(costById.get("opus")).toBe("5x"); // metered multiplier+ expect(costById.get("mini")).toBeUndefined(); // baseline cost — no annotation+ });++ it("sends with the provider recorded at model selection", async () => {+ await mountChat();+ await act(async () => {+ api().setInput("hello");+ });+ await act(async () => {+ await api().handleSubmit(new Event("submit"));+ });++ expect(streamChatCompletionMock).toHaveBeenCalledTimes(1);+ const options = streamChatCompletionMock.mock.calls[0][1];+ expect(options.model).toBe("sonnet");+ expect(options.provider).toBe("claude-agent");+ });++ it("resolves the provider by model ID for chats saved before selectedProvider existed", async () => {+ await mountChat();+ // A pre-selectedProvider chat: content carries a model but no provider.+ await act(async () => {+ api().loadFromContent({ version: 1, messages: [], selectedModel: "opus", enableWebSearch: false });+ });+ expect(api().selectedModel).toBe("opus");+ expect(api().selectedProvider).toBeUndefined();+ expect(api().enableWebSearch).toBe(false);++ await act(async () => {+ api().setInput("hi");+ });+ await act(async () => {+ await api().handleSubmit(new Event("submit"));+ });+ expect(streamChatCompletionMock.mock.calls[0][1].provider).toBe("anthropic");+ });++ it("round-trips the selected provider through getContent", async () => {+ await mountChat();++ // Loaded without a provider → saved without one (legacy chats stay byte-stable).+ await act(async () => {+ api().loadFromContent({ version: 1, messages: [], selectedModel: "opus" });+ });+ expect(api().getContent()).toMatchObject({ selectedModel: "opus", selectedProvider: undefined });++ // Re-picking a model records its provider and persists it.+ await act(async () => {+ api().setSelectedModel("mini", "openai");+ });+ expect(api().getContent()).toMatchObject({ selectedModel: "mini", selectedProvider: "openai" });+ });+});diff --git a/apps/server/src/routes/api/llm_chat.spec.ts b/apps/server/src/routes/api/llm_chat.spec.tsindex a62333be91..2b6f84651f 100644--- a/apps/server/src/routes/api/llm_chat.spec.ts+++ b/apps/server/src/routes/api/llm_chat.spec.ts@@ -6,14 +6,24 @@ const state = vi.hoisted(() => ({models: [] as unknown[],chunks: [] as unknown[],availableModels: [{ id: "m1", name: "Model One", isDefault: true }] as { id: string; name: string; isDefault?: boolean }[],- chatThrows: false+ chatThrows: undefined as unknown,+ // When true, the fake provider is chunk-native (implements chatChunks) and+ // records the abort signal the route wires to the response lifecycle.+ chunkNative: false,+ chunkSignal: undefined as AbortSignal | undefined}));vi.mock("../../services/llm/index.js", () => ({hasConfiguredProviders: () => state.configured,getAllModels: () => state.models,getProviderByType: () => ({- chat: () => { if (state.chatThrows) throw new Error("provider exploded"); return {}; },+ chat: () => { if (state.chatThrows !== undefined) throw state.chatThrows; return {}; },+ chatChunks: state.chunkNative+ ? async function* (_messages: unknown, _config: unknown, signal?: AbortSignal) {+ state.chunkSignal = signal;+ for (const c of state.chunks) yield c;+ }+ : undefined,getAvailableModels: () => state.availableModels,getModelPricing: () => ({ input: 0, output: 0 })})@@ -28,26 +38,44 @@ vi.mock("../../services/llm/chat_title.js", () => ({ generateChatTitle: (...argsimport llmChatRoute from "./llm_chat.js";-function fakeRes() {+function fakeRes({ withFlush = false } = {}) {const writes: string[] = [];const headers: Record<string, string> = {};+ const listeners: Record<string, () => void> = {};let statusCode = 200;let jsonBody: unknown;let ended = false;+ let flushes = 0;const res = {setHeader(k: string, v: string) { headers[k] = v; },flushHeaders() {},write(chunk: string) { writes.push(chunk); return true; },end() { ended = true; },status(code: number) { statusCode = code; return this; },- json(body: unknown) { jsonBody = body; return this; }+ json(body: unknown) { jsonBody = body; return this; },+ on(event: string, handler: () => void) { listeners[event] = handler; },+ ...(withFlush ? { flush() { flushes++; } } : {})} as unknown as Response;- return { res, writes, headers, get statusCode() { return statusCode; }, get jsonBody() { return jsonBody; }, get ended() { return ended; } };+ return {+ res, writes, headers, listeners,+ get statusCode() { return statusCode; },+ get jsonBody() { return jsonBody; },+ get ended() { return ended; },+ get flushes() { return flushes; }+ };}describe("LLM chat API", () => {afterEach(() => {- Object.assign(state, { configured: true, models: [], chunks: [], availableModels: [{ id: "m1", name: "Model One", isDefault: true }], chatThrows: false });+ Object.assign(state, {+ configured: true,+ models: [],+ chunks: [],+ availableModels: [{ id: "m1", name: "Model One", isDefault: true }],+ chatThrows: undefined,+ chunkNative: false,+ chunkSignal: undefined+ });generateChatTitle.mockClear();});@@ -101,11 +129,87 @@ describe("LLM chat API", () => {});it("writes an SSE error when the provider throws", async () => {- state.chatThrows = true;+ state.chatThrows = new Error("provider exploded");const r = fakeRes();await llmChatRoute.streamChat(req({ messages: [{ role: "user", content: "hi" }], config: {} }), r.res);expect(r.writes.join("")).toContain("provider exploded");expect(r.ended).toBe(true);});++ it("writes a generic SSE error when the provider throws a non-Error", async () => {+ state.chatThrows = "weird failure";+ const r = fakeRes();+ await llmChatRoute.streamChat(req({ messages: [{ role: "user", content: "hi" }], config: {} }), r.res);+ expect(r.writes.join("")).toContain("Unknown error");+ });++ it("prefers a chunk-native provider, wires the disconnect abort, and flushes each chunk", async () => {+ state.chunkNative = true;+ state.chunks = [{ type: "text", content: "native" }, { type: "done" }];+ const r = fakeRes({ withFlush: true });+ await llmChatRoute.streamChat(req({ messages: [{ role: "user", content: "hi" }], config: { provider: "claude-agent" } }), r.res);++ const body = r.writes.join("");+ expect(body).toContain('"content":"native"');+ expect(r.flushes).toBeGreaterThanOrEqual(2);++ // The provider received the signal tied to the response lifecycle:+ // a client disconnect (res close) aborts the in-flight agent turn.+ const signal = state.chunkSignal;+ expect(signal).toBeInstanceOf(AbortSignal);+ expect(signal?.aborted).toBe(false);+ r.listeners.close();+ expect(signal?.aborted).toBe(true);+ });++ it("falls back to the raw model id as display name for an unlisted model", async () => {+ state.chunks = [{ type: "error", error: "boom" }];+ const r = fakeRes();+ await llmChatRoute.streamChat(req({ messages: [{ role: "user", content: "hi" }], config: { model: "custom-model" } }), r.res);+ expect(r.writes.join("")).toContain("boom");+ expect(r.ended).toBe(true);+ });++ it("titles from the text parts of a multimodal first message, and skips image-only ones", async () => {+ const r1 = fakeRes();+ await llmChatRoute.streamChat(req({+ messages: [{ role: "user", content: [+ { type: "image", attachmentId: "a1", mime: "image/png" },+ { type: "text", text: "describe this" }+ ] }],+ config: { chatNoteId: "abc" }+ }), r1.res);+ expect(generateChatTitle).toHaveBeenCalledWith("abc", "describe this");++ generateChatTitle.mockClear();+ const r2 = fakeRes();+ await llmChatRoute.streamChat(req({+ messages: [{ role: "user", content: [{ type: "image", attachmentId: "a1", mime: "image/png" }] }],+ config: { chatNoteId: "abc" }+ }), r2.res);+ expect(generateChatTitle).not.toHaveBeenCalled();+ });++ it("does not title follow-up turns", async () => {+ const r = fakeRes();+ await llmChatRoute.streamChat(req({+ messages: [+ { role: "user", content: "first" },+ { role: "assistant", content: "reply" },+ { role: "user", content: "second" }+ ],+ config: { chatNoteId: "abc" }+ }), r.res);+ expect(generateChatTitle).not.toHaveBeenCalled();+ });++ it("keeps the chat alive when title generation fails", async () => {+ generateChatTitle.mockRejectedValueOnce(new Error("title model down"));+ state.chunks = [{ type: "done" }];+ const r = fakeRes();+ await llmChatRoute.streamChat(req({ messages: [{ role: "user", content: "hello" }], config: { chatNoteId: "abc" } }), r.res);+ expect(r.writes.join("")).toContain('"type":"done"');+ expect(r.ended).toBe(true);+ });});});diff --git a/apps/server/src/services/llm/index.spec.ts b/apps/server/src/services/llm/index.spec.tsindex 650980a7fb..146eefd75a 100644--- a/apps/server/src/services/llm/index.spec.ts+++ b/apps/server/src/services/llm/index.spec.ts@@ -30,6 +30,7 @@ function makeProviderMock(tag: string) {vi.mock("./providers/anthropic.js", () => ({ AnthropicProvider: makeProviderMock("anthropic") }));vi.mock("./providers/openai.js", () => ({ OpenAiProvider: makeProviderMock("openai") }));vi.mock("./providers/google.js", () => ({ GoogleProvider: makeProviderMock("google") }));+vi.mock("./providers/claude_agent.js", () => ({ ClaudeAgentProvider: makeProviderMock("claude-agent") }));import {clearProviderCache,@@ -76,11 +77,14 @@ describe("llm/index provider registry", () => {setProviders([{ id: "a", name: "A", provider: "anthropic", apiKey: "ka" },{ id: "o", name: "O", provider: "openai", apiKey: "ko" },- { id: "g", name: "G", provider: "google", apiKey: "kg" }+ { id: "g", name: "G", provider: "google", apiKey: "kg" },+ { id: "c", name: "C", provider: "claude-agent", apiKey: "" }]);expect((getProvider("a").constructor as any).lastArgs).toEqual(["ka", undefined]);expect((getProvider("o").constructor as any).lastArgs).toEqual(["ko", undefined]);expect((getProvider("g").constructor as any).lastArgs).toEqual(["kg", undefined]);+ // The subscription provider takes no constructor args — auth is Claude Code's.+ expect((getProvider("c").constructor as any).lastArgs).toEqual([]);});it("throws when no providers are configured (null and empty array)", () => {diff --git a/apps/server/src/services/llm/providers/claude_agent.spec.ts b/apps/server/src/services/llm/providers/claude_agent.spec.tsindex 8e34a10c46..63bd447d76 100644--- a/apps/server/src/services/llm/providers/claude_agent.spec.ts+++ b/apps/server/src/services/llm/providers/claude_agent.spec.ts@@ -42,7 +42,7 @@ vi.mock("./claude_binary.js", () => ({ resolveClaudeBinaryPath: resolveClaudeBinconst resolveAttachmentPartMock = vi.hoisted(() => vi.fn());vi.mock("./attachment_content.js", () => ({ resolveAttachmentPart: resolveAttachmentPartMock }));-const { buildSeededPrompt, ClaudeAgentProvider, hashTranscript } = await import("./claude_agent.js");+const { buildSeededPrompt, ClaudeAgentProvider, hashTranscript, resetAgentCwdForTests } = await import("./claude_agent.js");/** Drain the query prompt into the single user message it streams (multimodal path). */async function drainPrompt(prompt: unknown): Promise<{ role: string; content: unknown[] }> {@@ -484,6 +484,22 @@ describe("ClaudeAgentProvider.chatChunks", () => {expect(errors[0].error).toContain("Failed to start Claude Code");});+ it("forwards a mid-stream abort to the agent's abort controller", async () => {+ scriptAgent([textDelta("partial"), successResult()]);+ const controller = new AbortController();+ const provider = new ClaudeAgentProvider();+ const stream = provider.chatChunks([{ role: "user", content: "hi" }], {}, controller.signal);++ const chunks: LlmStreamChunk[] = [];+ for await (const chunk of stream) {+ chunks.push(chunk);+ // Fire the abort after the first chunk; the mocked SDK stream keeps+ // yielding, proving the listener path itself doesn't break the loop.+ controller.abort();+ }+ expect(chunks.some(c => c.type === "text")).toBe(true);+ });+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.@@ -497,12 +513,288 @@ describe("ClaudeAgentProvider.chatChunks", () => {expect(queryMock).not.toHaveBeenCalled();});- it("rejects a conversation that does not end with a user message", async () => {+ it("rejects a conversation that does not end with a user message (or is empty)", async () => {const provider = new ClaudeAgentProvider();- const chunks = await collect(provider.chatChunks([{ role: "assistant", content: "hi" }], {}));- expect(chunks).toEqual([{ type: "error", error: "The last message must be a user message." }]);+ const expected = [{ type: "error", error: "The last message must be a user message." }];+ expect(await collect(provider.chatChunks([{ role: "assistant", content: "hi" }], {}))).toEqual(expected);+ expect(await collect(provider.chatChunks([], {}))).toEqual(expected);expect(queryMock).not.toHaveBeenCalled();});++ it("exposes the subscription model list, zero pricing, and no chat() implementation", () => {+ const provider = new ClaudeAgentProvider();+ const models = provider.getAvailableModels();+ expect(models.some(m => m.id === "claude-sonnet-5" && m.isDefault)).toBe(true);+ expect(provider.getModelPricing("claude-sonnet-5")).toEqual(expect.objectContaining({ input: 0, output: 0 }));+ expect(provider.getModelPricing("no-such-model")).toBeUndefined();+ expect(() => provider.chat()).toThrow(/chatChunks/);+ });++ it("streams thinking deltas as thinking chunks", async () => {+ scriptAgent([+ {+ type: "stream_event",+ parent_tool_use_id: null,+ session_id: "sess-1",+ event: { type: "content_block_delta", index: 0, delta: { type: "thinking_delta", thinking: "pondering…" } }+ },+ successResult()+ ]);+ const provider = new ClaudeAgentProvider();+ const chunks = await collect(provider.chatChunks([{ role: "user", content: "hi" }], {}));+ expect(chunks).toContainEqual({ type: "thinking", content: "pondering…" });+ });++ it("ignores stream noise: non-tool block starts, unknown deltas, unmapped tool indexes, other events", async () => {+ scriptAgent([+ // content_block_start for a plain text block — no chunk.+ {+ type: "stream_event",+ parent_tool_use_id: null,+ session_id: "sess-1",+ event: { type: "content_block_start", index: 0, content_block: { type: "text", text: "" } }+ },+ // A delta type the provider doesn't map — no chunk.+ {+ type: "stream_event",+ parent_tool_use_id: null,+ session_id: "sess-1",+ event: { type: "content_block_delta", index: 0, delta: { type: "signature_delta", signature: "sig" } }+ },+ // input_json_delta for a block index that never had a tool_use start.+ {+ type: "stream_event",+ parent_tool_use_id: null,+ session_id: "sess-1",+ event: { type: "content_block_delta", index: 9, delta: { type: "input_json_delta", partial_json: "{}" } }+ },+ // A stream event that is neither block start nor delta.+ {+ type: "stream_event",+ parent_tool_use_id: null,+ session_id: "sess-1",+ event: { type: "message_start" }+ },+ // An SDK message type the provider doesn't know (and no session_id).+ { type: "diagnostic" },+ successResult()+ ]);+ const provider = new ClaudeAgentProvider();+ const chunks = await collect(provider.chatChunks([{ role: "user", content: "hi" }], {}));+ expect(chunks.map(c => c.type)).toEqual(["usage", "done"]);+ });++ it("ignores assistant/user messages from subagents and non-array user content", async () => {+ scriptAgent([+ {+ type: "assistant",+ parent_tool_use_id: "toolu_parent",+ session_id: "sess-1",+ message: { content: [{ type: "tool_use", id: "toolu_sub", name: "sub_tool", input: {} }] }+ },+ {+ type: "user",+ parent_tool_use_id: "toolu_parent",+ session_id: "sess-1",+ message: { content: [{ type: "tool_result", tool_use_id: "toolu_sub", content: "sub result" }] }+ },+ {+ type: "user",+ parent_tool_use_id: null,+ session_id: "sess-1",+ message: { content: "a plain string user echo" }+ },+ successResult()+ ]);+ const provider = new ClaudeAgentProvider();+ const chunks = await collect(provider.chatChunks([{ role: "user", content: "hi" }], {}));+ expect(chunks.map(c => c.type)).toEqual(["usage", "done"]);+ });++ it("flattens tool results of every content shape and skips non-result blocks", async () => {+ // No `input` field — exercises the `block.input ?? {}` fallback on the tool_use chunk.+ const toolUse = (id: string) => ({ type: "tool_use", id, name: `mcp__trilium__t_${id}` });+ scriptAgent([+ {+ type: "assistant",+ parent_tool_use_id: null,+ session_id: "sess-1",+ message: { content: [toolUse("t1"), toolUse("t2"), toolUse("t3"), toolUse("t4")] }+ },+ {+ type: "user",+ parent_tool_use_id: null,+ session_id: "sess-1",+ message: {+ content: [+ // A non-result block and an id-less result must both be skipped.+ { type: "text", text: "interleaved commentary" },+ { type: "tool_result", content: "no id" },+ { type: "tool_result", tool_use_id: "t1", content: "plain string" },+ { type: "tool_result", tool_use_id: "t2" }, // no content+ { type: "tool_result", tool_use_id: "t3", content: [{ type: "image" }] },+ { type: "tool_result", tool_use_id: "t4", content: { odd: true } }+ ]+ }+ },+ successResult()+ ]);+ const provider = new ClaudeAgentProvider();+ const chunks = await collect(provider.chatChunks([{ role: "user", content: "hi" }], {}));++ const results = chunks.filter(c => c.type === "tool_result");+ expect(results.map(r => [r.toolName, r.result])).toEqual([+ ["t_t1", "plain string"],+ ["t_t2", ""],+ ["t_t3", ""], // array without text blocks flattens to nothing+ ["t_t4", '{"odd":true}']+ ]);+ });++ it("reports a stop reason when the agent fails without an error list", async () => {+ scriptAgent([+ { ...successResult(), subtype: "error_max_turns", is_error: true }+ ]);+ const provider = new ClaudeAgentProvider();+ const chunks = await collect(provider.chatChunks([{ role: "user", content: "hi" }], {}));+ const errors = chunks.filter(c => c.type === "error");+ expect(errors).toEqual([{ type: "error", error: "Agent stopped: error_max_turns" }]);+ });++ it("maps oauth failures to the login hint and other assistant errors to a generic message", async () => {+ scriptAgent([+ {+ type: "assistant",+ parent_tool_use_id: null,+ session_id: "sess-1",+ error: "oauth_org_not_allowed",+ message: { content: [] }+ },+ {+ type: "assistant",+ parent_tool_use_id: null,+ session_id: "sess-1",+ error: "billing_issue",+ message: { content: [] }+ },+ successResult()+ ]);+ const provider = new ClaudeAgentProvider();+ const chunks = await collect(provider.chatChunks([{ role: "user", content: "hi" }], {}));+ const errors = chunks.filter(c => c.type === "error").map(c => c.error);+ expect(errors[0]).toContain("claude /login");+ expect(errors[1]).toBe("Claude Agent error: billing_issue");+ });++ it("stringifies non-Error throws from the SDK", async () => {+ queryMock.mockImplementation(() => {+ throw "subprocess exploded";+ });+ const provider = new ClaudeAgentProvider();+ const chunks = await collect(provider.chatChunks([{ role: "user", content: "hi" }], {}));+ expect(chunks).toContainEqual({ type: "error", error: "subprocess exploded" });+ });++ it("ignores non-init system messages and inits without a trilium MCP entry", async () => {+ scriptAgent([+ { type: "system", subtype: "compact_boundary", session_id: "s" },+ { type: "system", subtype: "init", session_id: "s" }, // no mcp_servers at all+ { type: "system", subtype: "init", session_id: "s", mcp_servers: [{ name: "other", status: "failed" }] },+ successResult()+ ]);+ const provider = new ClaudeAgentProvider();+ await collect(provider.chatChunks([{ role: "user", content: "hi" }], {}));+ expect(errorLogMock).not.toHaveBeenCalled();+ });++ it("degrades unresolved and natively-unsupported attachments to placeholders around real blocks", async () => {+ resolveAttachmentPartMock+ .mockReturnValueOnce({ kind: "image", bytes: new Uint8Array([1]), mime: "image/png" })+ .mockReturnValueOnce(null) // missing/protected attachment+ .mockReturnValueOnce({ kind: "image", bytes: new Uint8Array([2]), mime: "image/tiff" })+ .mockReturnValueOnce({ kind: "file", bytes: new Uint8Array([3]), mime: "application/zip", filename: "a.zip" });+ scriptAgent([successResult()]);+ const provider = new ClaudeAgentProvider();+ await collect(provider.chatChunks([+ { role: "user", content: [+ { type: "image", attachmentId: "png", mime: "image/png" },+ { type: "image", attachmentId: "gone", mime: "image/png" },+ { type: "image", attachmentId: "tiff", mime: "image/tiff" },+ { type: "file", attachmentId: "zip", mime: "application/zip", filename: "a.zip" }+ ] }+ ], {}));++ const message = await drainPrompt(queryMock.mock.calls[0][0].prompt);+ expect(message.content).toEqual([+ { type: "image", source: { type: "base64", media_type: "image/png", data: "AQ==" } },+ { type: "text", text: "[attached image]" },+ { type: "text", text: "[attached image]" },+ { type: "text", text: "[attached file: a.zip]" }+ ]);+ });++ it("keeps the plain string prompt for parts-form content without attachments", async () => {+ scriptAgent([successResult()]);+ const provider = new ClaudeAgentProvider();+ await collect(provider.chatChunks([+ { role: "user", content: [{ type: "text", text: "line one" }, { type: "text", text: "line two" }] }+ ], {}));+ expect(queryMock.mock.calls[0][0].prompt).toBe("line one\nline two");+ });++ it("creates the isolating .git marker only when it is absent", async () => {+ const path = await import("path");+ const fs = await import("fs");+ const os = await import("os");+ const agentDir = path.join(os.tmpdir(), "trilium-claude-agent-spec", "claude-agent");++ resetAgentCwdForTests();+ fs.rmSync(agentDir, { recursive: true, force: true });+ scriptAgent([successResult()]);+ const provider = new ClaudeAgentProvider();+ await collect(provider.chatChunks([{ role: "user", content: "hi" }], {}));+ expect(fs.existsSync(path.join(agentDir, ".git", "HEAD"))).toBe(true);++ // Second initialization finds the marker in place and leaves it alone.+ const headBefore = fs.statSync(path.join(agentDir, ".git", "HEAD")).mtimeMs;+ resetAgentCwdForTests();+ scriptAgent([successResult()]);+ await collect(provider.chatChunks([{ role: "user", content: "hi" }], {}));+ expect(fs.statSync(path.join(agentDir, ".git", "HEAD")).mtimeMs).toBe(headBefore);+ });++ it("evicts the oldest chat-note mapping once the session cap is exceeded", async () => {+ const provider = new ClaudeAgentProvider();++ scriptAgent([textDelta("r"), successResult("sess-victim")]);+ await collect(provider.chatChunks([{ role: "user", content: "q" }], { chatNoteId: "victim" }));++ // 200 further distinct chat notes push "victim" past the cap.+ for (let i = 0; i < 200; i++) {+ scriptAgent([textDelta("r"), successResult(`sess-${i}`)]);+ await collect(provider.chatChunks([{ role: "user", content: "q" }], { chatNoteId: `filler-${i}` }));+ }++ // Despite a perfectly matching transcript, the victim can no longer resume.+ scriptAgent([successResult()]);+ await collect(provider.chatChunks([+ { role: "user", content: "q" },+ { role: "assistant", content: "r" },+ { role: "user", content: "q2" }+ ], { chatNoteId: "victim" }));+ const lastCall = queryMock.mock.calls[queryMock.mock.calls.length - 1][0];+ expect(lastCall.options.resume).toBeUndefined();++ // A recent filler still resumes — only the oldest entry was dropped.+ scriptAgent([successResult()]);+ await collect(provider.chatChunks([+ { role: "user", content: "q" },+ { role: "assistant", content: "r" },+ { role: "user", content: "q2" }+ ], { chatNoteId: "filler-199" }));+ const fillerCall = queryMock.mock.calls[queryMock.mock.calls.length - 1][0];+ expect(fillerCall.options.resume).toBe("sess-199");+ });});describe("generateTitle", () => {@@ -528,6 +820,15 @@ describe("generateTitle", () => {const provider = new ClaudeAgentProvider();await expect(provider.generateTitle("hello")).resolves.toBe("");});++ it("skips non-result messages and returns empty on a non-success result", async () => {+ scriptAgent([textDelta("streamed noise"), { ...successResult(), result: "The Title" }]);+ const provider = new ClaudeAgentProvider();+ await expect(provider.generateTitle("hello")).resolves.toBe("The Title");++ scriptAgent([{ ...successResult(), subtype: "error_during_execution", is_error: true, errors: [] }]);+ await expect(provider.generateTitle("hello")).resolves.toBe("");+ });});describe("transcript helpers", () => {@@ -536,6 +837,9 @@ describe("transcript helpers", () => {const partsForm = hashTranscript([{ role: "user", content: [{ type: "text", text: "hello" }] }]);expect(stringForm).toBe(partsForm);expect(hashTranscript([{ role: "user", content: "hello!" }])).not.toBe(stringForm);+ // Attachment parts flatten to stable placeholders, so re-sent bytes don't break resume.+ const withImage = hashTranscript([{ role: "user", content: [{ type: "image", attachmentId: "a", mime: "image/png" }] }]);+ expect(withImage).toBe(hashTranscript([{ role: "user", content: "[attached image]" }]));});it("buildSeededPrompt replays the transcript with role labels", () => {diff --git a/apps/server/src/services/llm/providers/claude_agent.ts b/apps/server/src/services/llm/providers/claude_agent.tsindex 81ea678c19..f8e6ce6c7f 100644--- a/apps/server/src/services/llm/providers/claude_agent.ts+++ b/apps/server/src/services/llm/providers/claude_agent.ts@@ -147,9 +147,9 @@ function rememberSession(chatNoteId: string, entry: SessionEntry) {sessionsByChatNote.delete(chatNoteId);sessionsByChatNote.set(chatNoteId, entry);if (sessionsByChatNote.size > MAX_TRACKED_SESSIONS) {- const oldest = sessionsByChatNote.keys().next().value;- if (oldest !== undefined) {+ for (const oldest of sessionsByChatNote.keys()) {sessionsByChatNote.delete(oldest);+ break;}}}@@ -307,17 +307,22 @@ export class ClaudeAgentProvider implements LlmProvider {break;}for (const block of content) {+ if (block.type !== "tool_result" || !block.tool_use_id) {+ continue;+ }// Only surface results for tool calls made this turn —// this also filters any replayed history on resume.- if (block.type === "tool_result" && block.tool_use_id && toolNamesById.has(block.tool_use_id)) {- yield {- type: "tool_result",- toolCallId: block.tool_use_id,- toolName: friendlyToolName(toolNamesById.get(block.tool_use_id) ?? "tool"),- result: flattenToolResult(block.content),- isError: block.is_error === true- };+ const toolName = toolNamesById.get(block.tool_use_id);+ if (toolName === undefined) {+ continue;}+ yield {+ type: "tool_result",+ toolCallId: block.tool_use_id,+ toolName: friendlyToolName(toolName),+ result: flattenToolResult(block.content),+ isError: block.is_error === true+ };}break;}@@ -420,6 +425,9 @@ export class ClaudeAgentProvider implements LlmProvider {// injects the note metadata into the user turn (see buildNoteHint), so// the "you can see the current note's metadata above" notice is accurate.const promptConfig: LlmProviderConfig = { ...config, enableNoteTools: noteToolsAvailable };+ // buildSystemPrompt only returns undefined in its own documented-unreachable+ // no-parts case (the markdown hints are always appended).+ /* v8 ignore next */return buildSystemPrompt(messages, promptConfig) ?? "";}@@ -509,6 +517,11 @@ function getAgentCwd(): string {return agentCwd;}+/** For tests: forget the initialized agent cwd so the next call re-runs setup. */+export function resetAgentCwdForTests(): void {+ agentCwd = undefined;+}+/*** Build the prompt for the current user turn. When the turn carries attachments* the model can consume natively, this returns a one-message stream of Anthropic@@ -523,7 +536,9 @@ function buildPrompt(content: string | LlmMessagePart[], prefix: string, hasAtta}// Nothing the model can take natively — collapse back to text so the// turn stays on the well-worn string path (and out of streaming-input- // mode). Text blocks still carry inlined SVG/text-file content.+ // mode). Text blocks still carry inlined SVG/text-file content. The+ // non-text arm is unreachable: any image/document block returns above.+ /* v8 ignore next */return blocks.map(b => (b.type === "text" ? b.text : "")).filter(Boolean).join("\n\n");}const lastText = flattenContent(content);diff --git a/apps/server/src/services/llm/providers/claude_binary.spec.ts b/apps/server/src/services/llm/providers/claude_binary.spec.tsindex 50b37718e4..8823561b7e 100644--- a/apps/server/src/services/llm/providers/claude_binary.spec.ts+++ b/apps/server/src/services/llm/providers/claude_binary.spec.ts@@ -1,3 +1,4 @@+import path from "path";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";// The probe drives the real execFile through util.promisify's callback@@ -15,6 +16,8 @@ const { resetClaudeBinaryCache, resolveClaudeBinaryPath } = await import("./claudescribe("resolveClaudeBinaryPath", () => {const originalOverride = process.env.TRILIUM_CLAUDE_CODE_PATH;+ const originalPath = process.env.PATH;+ const originalPlatform = Object.getOwnPropertyDescriptor(process, "platform");beforeEach(() => {resetClaudeBinaryCache();@@ -30,8 +33,16 @@ describe("resolveClaudeBinaryPath", () => {} else {process.env.TRILIUM_CLAUDE_CODE_PATH = originalOverride;}+ process.env.PATH = originalPath;+ if (originalPlatform) {+ Object.defineProperty(process, "platform", originalPlatform);+ }});+ function stubPlatform(platform: NodeJS.Platform) {+ Object.defineProperty(process, "platform", { ...originalPlatform, value: platform });+ }+function probeSucceeds() {execFileMock.mockImplementation((_binary, _args, _options, cb) => cb(null, { stdout: "2.0.1\n", stderr: "" }));}@@ -61,10 +72,53 @@ describe("resolveClaudeBinaryPath", () => {expect(execFileMock).toHaveBeenCalledTimes(2);});+ 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));++ await expect(resolveClaudeBinaryPath()).rejects.toThrow(/failed to run \(killed by signal\)/);+ });+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();});++ describe("PATH fallback (no override)", () => {+ beforeEach(() => {+ delete process.env.TRILIUM_CLAUDE_CODE_PATH;+ });++ it("finds the bare `claude` binary on POSIX, skipping empty PATH segments", async () => {+ stubPlatform("linux");+ const hit = path.join("/home/user/bin", "claude");+ // Leading empty segment exercises the `if (!dir) continue` guard.+ process.env.PATH = ["", "/usr/local/bin", "/home/user/bin"].join(path.delimiter);+ existsSyncMock.mockImplementation((candidate: string) => candidate === hit);+ probeSucceeds();++ await expect(resolveClaudeBinaryPath()).resolves.toBe(hit);+ expect(execFileMock.mock.calls[0][0]).toBe(hit);+ });++ it("probes PATHEXT-style extensions on Windows (finds claude.cmd)", async () => {+ stubPlatform("win32");+ const hit = path.join("C:\\npm", "claude.cmd");+ process.env.PATH = ["C:\\npm"].join(path.delimiter);+ existsSyncMock.mockImplementation((candidate: string) => candidate === hit);+ probeSucceeds();++ await expect(resolveClaudeBinaryPath()).resolves.toBe(hit);+ });++ it("rejects with install instructions when `claude` is nowhere on PATH (or PATH is unset)", async () => {+ stubPlatform("linux");+ delete process.env.PATH;+ existsSyncMock.mockReturnValue(false);++ await expect(resolveClaudeBinaryPath()).rejects.toThrow(/Claude Code CLI not found/);+ expect(execFileMock).not.toHaveBeenCalled();+ });+ });});diff --git a/apps/server/src/services/llm/providers/system_prompt.spec.ts b/apps/server/src/services/llm/providers/system_prompt.spec.tsindex 2646e5775b..6635d1ce84 100644--- a/apps/server/src/services/llm/providers/system_prompt.spec.ts+++ b/apps/server/src/services/llm/providers/system_prompt.spec.ts@@ -1,4 +1,14 @@-import { describe, expect, it } from "vitest";+import { describe, expect, it, vi } from "vitest";++// Delegates to the real getTaskStates by default; individual tests override it+// to inject custom task states (the namespace re-export is frozen, so a plain+// spy can't patch it).+const getTaskStatesMock = vi.hoisted(() => vi.fn());+vi.mock("@triliumnext/core", async (importOriginal) => {+ const actual = await importOriginal<typeof import("@triliumnext/core")>();+ getTaskStatesMock.mockImplementation(actual.task_states.getTaskStates);+ return { ...actual, task_states: { ...actual.task_states, getTaskStates: getTaskStatesMock } };+});import { buildSystemPrompt } from "./system_prompt.js";@@ -52,4 +62,19 @@ describe("buildSystemPrompt", () => {expect(prompt).toContain("`- [?]` — Maybe");expect(prompt).toContain("`- [-]` — Cancelled");});++ it("keeps just the native open/completed hint when no custom states are defined", () => {+ getTaskStatesMock.mockReturnValueOnce([]);+ const prompt = buildSystemPrompt([], {}) ?? "";+ expect(prompt).toContain("`- [ ]` for an open task");+ expect(prompt).not.toContain("also defines extra task states");+ });++ it("suffixes custom task states that mark a task as completed", () => {+ getTaskStatesMock.mockReturnValueOnce([+ { name: "verified", title: "Verified", markdownSymbol: "v", isCompleted: true, icon: "bx bx-check-double" }+ ]);+ const prompt = buildSystemPrompt([], {}) ?? "";+ expect(prompt).toContain("`- [v]` — Verified (completed)");+ });});