Skip to content

Build your personal knowledge base with Trilium Notes

fix(llm): repair the Copilot MCP rebinding guard and cover the provider

Elian Doran03f5b7507c62
diff --git a/apps/server/src/services/llm/index.spec.ts b/apps/server/src/services/llm/index.spec.ts
index 146eefd75a..7b36382428 100644
--- a/apps/server/src/services/llm/index.spec.ts
+++ b/apps/server/src/services/llm/index.spec.ts
@@ -31,6 +31,7 @@ vi.mock("./providers/anthropic.js", () => ({ AnthropicProvider: makeProviderMock
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") }));
+vi.mock("./providers/copilot_agent.js", () => ({ CopilotAgentProvider: makeProviderMock("copilot-agent") }));
import {
clearProviderCache,
@@ -78,13 +79,16 @@ describe("llm/index provider registry", () => {
{ 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: "c", name: "C", provider: "claude-agent", apiKey: "" }
+ { id: "c", name: "C", provider: "claude-agent", apiKey: "" },
+ { id: "gh", name: "GH", provider: "copilot-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.
+ // The subscription providers take no constructor args — auth belongs
+ // to Claude Code and the Copilot CLI respectively.
expect((getProvider("c").constructor as any).lastArgs).toEqual([]);
+ expect((getProvider("gh").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/acp_client.spec.ts b/apps/server/src/services/llm/providers/acp_client.spec.ts
index 2046932377..4e2e8428d4 100644
--- a/apps/server/src/services/llm/providers/acp_client.spec.ts
+++ b/apps/server/src/services/llm/providers/acp_client.spec.ts
@@ -1,8 +1,9 @@
import { EventEmitter } from "events";
import { PassThrough } from "stream";
-import { beforeEach, describe, expect, it, vi } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-vi.mock("@triliumnext/core", () => ({ getLog: () => ({ info: vi.fn(), error: vi.fn() }) }));
+const infoLogMock = vi.hoisted(() => vi.fn());
+vi.mock("@triliumnext/core", () => ({ getLog: () => ({ info: infoLogMock, error: vi.fn() }) }));
// A fake ChildProcess: stdin captures what the client writes, stdout/stderr are
// streams the test pushes into, and it is an EventEmitter for exit/error.
@@ -45,6 +46,11 @@ describe("AcpClient", () => {
proc = new FakeProc();
spawnMock.mockReset();
spawnMock.mockReturnValue(proc);
+ infoLogMock.mockReset();
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
});
it("spawns with --acp and the given args", () => {
@@ -65,6 +71,17 @@ describe("AcpClient", () => {
);
});
+ it("logs the agent's stderr, skipping blank chunks", () => {
+ AcpClient.start("/bin/copilot", { cwd: "/tmp" });
+
+ proc.stderr.emit("data", Buffer.from(" \n"));
+ expect(infoLogMock).not.toHaveBeenCalled();
+
+ proc.stderr.emit("data", Buffer.from("warning: model is busy\n"));
+ expect(infoLogMock).toHaveBeenCalledTimes(1);
+ expect(infoLogMock).toHaveBeenCalledWith("ACP agent stderr: warning: model is busy");
+ });
+
it("correlates a response to its request by id", async () => {
const client = AcpClient.start("/bin/copilot", { cwd: "/tmp" });
const promise = client.request<{ ok: boolean }>("initialize", { v: 1 });
@@ -85,6 +102,46 @@ describe("AcpClient", () => {
await expect(promise).rejects.toMatchObject({ code: -32000, message: "no auth" });
});
+ it("rejects a request that outlives its timeout", async () => {
+ vi.useFakeTimers();
+ const client = AcpClient.start("/bin/copilot", { cwd: "/tmp" });
+ const promise = client.request("session/prompt", {}, 5_000);
+
+ vi.advanceTimersByTime(5_000);
+ await expect(promise).rejects.toThrow(`ACP request "session/prompt" timed out after 5 s.`);
+ });
+
+ it("rejects and cleans up when the write to stdin fails synchronously", async () => {
+ const client = AcpClient.start("/bin/copilot", { cwd: "/tmp" });
+ const write = vi.spyOn(proc.stdin, "write").mockImplementation(() => {
+ throw new Error("stdin closed");
+ });
+ await expect(client.request("initialize", {})).rejects.toThrow("stdin closed");
+
+ // A non-Error thrown value is stringified rather than swallowed.
+ write.mockImplementation(() => {
+ throw "stdin vanished";
+ });
+ await expect(client.request("initialize", {})).rejects.toThrow("stdin vanished");
+
+ // Neither failure poisoned the client: the next exchange still completes.
+ write.mockRestore();
+ const promise = client.request("session/new", {});
+ proc.send({ jsonrpc: "2.0", id: lastWritten(proc).id, result: { sessionId: "s1" } });
+ await expect(promise).resolves.toEqual({ sessionId: "s1" });
+ });
+
+ it("writes a notification without an id", () => {
+ const client = AcpClient.start("/bin/copilot", { cwd: "/tmp" });
+ client.notify("session/cancel", { sessionId: "s1" });
+
+ expect(lastWritten(proc)).toEqual({
+ jsonrpc: "2.0",
+ method: "session/cancel",
+ params: { sessionId: "s1" }
+ });
+ });
+
it("routes notifications (no id) to onNotification", async () => {
const onNotification = vi.fn();
AcpClient.start("/bin/copilot", { cwd: "/tmp", onNotification });
@@ -126,6 +183,20 @@ describe("AcpClient", () => {
});
});
+ it("stringifies a non-Error rejection from the agent-request handler", async () => {
+ const onAgentRequest = vi.fn(() => Promise.reject("permission backend offline"));
+ AcpClient.start("/bin/copilot", { cwd: "/tmp", onAgentRequest });
+
+ proc.send({ jsonrpc: "2.0", id: 10, method: "session/request_permission", params: {} });
+ await vi.waitFor(() => {
+ const reply = lastWritten(proc);
+ expect(reply).toMatchObject({
+ id: 10,
+ error: { code: -32603, message: "permission backend offline" }
+ });
+ });
+ });
+
it("rejects in-flight requests when the subprocess exits unexpectedly", async () => {
const client = AcpClient.start("/bin/copilot", { cwd: "/tmp" });
const promise = client.request("session/prompt", {});
@@ -134,6 +205,17 @@ describe("AcpClient", () => {
await expect(promise).rejects.toThrow(/exited unexpectedly/);
});
+ it("fails in-flight requests when the subprocess cannot be started", async () => {
+ const client = AcpClient.start("/bin/copilot", { cwd: "/tmp" });
+ const promise = client.request("initialize", {});
+
+ proc.emit("error", new Error("spawn ENOENT"));
+ await expect(promise).rejects.toThrow("Failed to start the ACP agent: spawn ENOENT");
+ // The failure is sticky: later requests short-circuit with the same error.
+ await expect(client.request("session/new", {}))
+ .rejects.toThrow(/Failed to start the ACP agent/);
+ });
+
it("does not treat a post-dispose exit as an unexpected failure", async () => {
const client = AcpClient.start("/bin/copilot", { cwd: "/tmp" });
client.dispose();
@@ -143,6 +225,18 @@ describe("AcpClient", () => {
await expect(client.request("initialize", {})).rejects.toThrow(/disposed/);
});
+ it("rejects in-flight requests on dispose and ignores a second dispose", async () => {
+ const client = AcpClient.start("/bin/copilot", { cwd: "/tmp" });
+ const promise = client.request("session/prompt", {});
+
+ client.dispose();
+ await expect(promise).rejects.toThrow("The ACP client was disposed.");
+
+ proc.killed = false;
+ client.dispose();
+ expect(proc.killed).toBe(false);
+ });
+
it("ignores lines that are not JSON objects", async () => {
const onNotification = vi.fn();
AcpClient.start("/bin/copilot", { cwd: "/tmp", onNotification });
@@ -155,6 +249,35 @@ describe("AcpClient", () => {
expect(onNotification).toHaveBeenCalledTimes(1);
});
+ it("ignores blank lines and messages with neither an id nor a method", async () => {
+ const onNotification = vi.fn();
+ AcpClient.start("/bin/copilot", { cwd: "/tmp", onNotification });
+
+ proc.stdout.write("\n");
+ proc.stdout.write(" \n");
+ proc.send({ jsonrpc: "2.0" }); // neither a response nor a notification
+ proc.send({ jsonrpc: "2.0", method: "session/update", params: { n: 1 } });
+ await vi.waitFor(() =>
+ expect(onNotification).toHaveBeenCalledWith("session/update", { n: 1 })
+ );
+ expect(onNotification).toHaveBeenCalledTimes(1);
+ });
+
+ it("drops a response with an unknown id and a notification with no handler", async () => {
+ const client = AcpClient.start("/bin/copilot", { cwd: "/tmp" });
+ const promise = client.request("initialize", {});
+ const { id } = lastWritten(proc);
+
+ proc.send({ jsonrpc: "2.0", id: 4242, result: { stray: true } }); // never requested
+ proc.send({ jsonrpc: "2.0", method: "session/update", params: {} }); // no onNotification
+ proc.send({ jsonrpc: "2.0", id, result: { ok: true } });
+ await expect(promise).resolves.toEqual({ ok: true });
+
+ // A duplicate response for an id that already settled is dropped too.
+ proc.send({ jsonrpc: "2.0", id, result: { ok: false } });
+ await expect(promise).resolves.toEqual({ ok: true });
+ });
+
it("survives an EPIPE on the subprocess's stdin", () => {
AcpClient.start("/bin/copilot", { cwd: "/tmp" });
diff --git a/apps/server/src/services/llm/providers/copilot_agent.spec.ts b/apps/server/src/services/llm/providers/copilot_agent.spec.ts
index 73b71e1367..b828d3e672 100644
--- a/apps/server/src/services/llm/providers/copilot_agent.spec.ts
+++ b/apps/server/src/services/llm/providers/copilot_agent.spec.ts
@@ -1,9 +1,13 @@
import type { LlmStreamChunk } from "@triliumnext/commons";
+import fs from "fs";
+import os from "os";
+import path from "path";
import { beforeEach, describe, expect, it, vi } from "vitest";
const errorLogMock = vi.hoisted(() => vi.fn());
+const infoLogMock = vi.hoisted(() => vi.fn());
vi.mock("@triliumnext/core", () => ({
- getLog: () => ({ info: vi.fn(), error: errorLogMock }),
+ getLog: () => ({ info: infoLogMock, error: errorLogMock }),
// buildSystemPrompt reads the workspace task states; none in this unit test.
task_states: { getTaskStates: () => [] }
}));
@@ -14,6 +18,9 @@ vi.mock("../../data_dir.js", async () => {
return { default: { TRILIUM_DATA_DIR: path.join(os.tmpdir(), "trilium-copilot-agent-spec") } };
});
+/** The directory the provider derives from the mocked data dir above. */
+const AGENT_CWD = path.resolve(os.tmpdir(), "trilium-copilot-agent-spec", "copilot-agent");
+
// BYO binary resolution shells out to the user's `copilot`; stub it.
const resolveCopilotBinaryMock = vi.hoisted(() => vi.fn(async () => "/usr/bin/copilot"));
vi.mock("./copilot_binary.js", () => ({
@@ -43,7 +50,12 @@ class FakeAcpClient {
static current: FakeAcpClient | undefined;
static promptScript: (client: FakeAcpClient) => Promise<{ stopReason?: string }> = async () => ({ stopReason: "end_turn" });
+ static initializeError: Error | undefined;
static sessionNewError: Error | undefined;
+ static sessionLoadError: Error | undefined;
+ static setModelError: Error | undefined;
+ /** Id handed out by the next `session/new` (the real CLI never reuses one). */
+ static newSessionId = "sess-1";
constructor(opts: { onNotification: (m: string, p: unknown) => void; onAgentRequest?: (m: string, p: unknown) => unknown }) {
this.onNotification = opts.onNotification;
@@ -57,12 +69,24 @@ class FakeAcpClient {
async request<T>(method: string, params: unknown): Promise<T> {
this.requests.push({ method, params });
- if (method === "initialize") return {} as T;
+ if (method === "initialize") {
+ if (FakeAcpClient.initializeError) throw FakeAcpClient.initializeError;
+ return {} as T;
+ }
if (method === "session/new") {
if (FakeAcpClient.sessionNewError) throw FakeAcpClient.sessionNewError;
- return { sessionId: "sess-1" } as T;
+ return { sessionId: FakeAcpClient.newSessionId } as T;
+ }
+ if (method === "session/load") {
+ if (FakeAcpClient.sessionLoadError) throw FakeAcpClient.sessionLoadError;
+ // A real load replays the session's history as notifications.
+ this.update({ sessionUpdate: "agent_message_chunk", content: { type: "text", text: "REPLAY" } });
+ return {} as T;
+ }
+ if (method === "session/set_model") {
+ if (FakeAcpClient.setModelError) throw FakeAcpClient.setModelError;
+ return {} as T;
}
- if (method === "session/set_model") return {} as T;
if (method === "session/prompt") return (await FakeAcpClient.promptScript(this)) as T;
return {} as T;
}
@@ -89,7 +113,7 @@ class FakeAcpError extends Error {
vi.mock("./acp_client.js", () => ({ AcpClient: FakeAcpClient, AcpError: FakeAcpError }));
-const { buildPromptBlocks, CopilotAgentProvider, decidePermission, resetAgentCwdForTests } = await import("./copilot_agent.js");
+const { buildPromptBlocks, CopilotAgentProvider, createUpdateCollector, decidePermission, resetAgentCwdForTests } = await import("./copilot_agent.js");
async function collect(iterable: AsyncIterable<LlmStreamChunk>): Promise<LlmStreamChunk[]> {
const chunks: LlmStreamChunk[] = [];
@@ -100,17 +124,36 @@ async function collect(iterable: AsyncIterable<LlmStreamChunk>): Promise<LlmStre
}
const userMessage = (text: string) => ({ role: "user" as const, content: text });
+const assistantMessage = (text: string) => ({ role: "assistant" as const, content: text });
+
+function resetFakes() {
+ errorLogMock.mockReset();
+ infoLogMock.mockReset();
+ resolveAttachmentPartMock.mockReset();
+ resetAgentCwdForTests();
+ mcpEndpointMock.mockClear();
+ FakeAcpClient.current = undefined;
+ FakeAcpClient.initializeError = undefined;
+ FakeAcpClient.sessionNewError = undefined;
+ FakeAcpClient.sessionLoadError = undefined;
+ FakeAcpClient.setModelError = undefined;
+ FakeAcpClient.newSessionId = "sess-1";
+ FakeAcpClient.promptScript = async () => ({ stopReason: "end_turn" });
+}
-describe("CopilotAgentProvider.chatChunks", () => {
- beforeEach(() => {
- errorLogMock.mockReset();
- resolveAttachmentPartMock.mockReset();
- resetAgentCwdForTests();
- mcpEndpointMock.mockClear();
- FakeAcpClient.current = undefined;
- FakeAcpClient.sessionNewError = undefined;
- FakeAcpClient.promptScript = async () => ({ stopReason: "end_turn" });
+describe("CopilotAgentProvider metadata", () => {
+ it("exposes the subscription model list and refuses the AI-SDK chat entry point", () => {
+ const provider = new CopilotAgentProvider();
+
+ expect(provider.getAvailableModels().filter(m => m.isDefault).map(m => m.id)).toEqual(["auto"]);
+ expect(provider.getModelPricing("gpt-5.4")).toEqual({ input: 0, output: 0 });
+ expect(provider.getModelPricing("gpt-4-turbo")).toBeUndefined();
+ expect(() => provider.chat()).toThrow(/chatChunks/);
});
+});
+
+describe("CopilotAgentProvider.chatChunks", () => {
+ beforeEach(resetFakes);
it("maps message, thought, and tool updates to chunks and ends with done", async () => {
FakeAcpClient.promptScript = async client => {
@@ -289,6 +332,219 @@ describe("CopilotAgentProvider.chatChunks", () => {
const blocks = (prompt?.params as { prompt: { type: string; text: string }[] }).prompt;
expect(blocks[0].text).toContain("NOTE_META(note123)");
});
+
+ it("flags attachments to the note hint and leads the prompt blocks with the prefix", async () => {
+ resolveAttachmentPartMock.mockReturnValue(undefined);
+
+ const provider = new CopilotAgentProvider();
+ await collect(provider.chatChunks([{
+ role: "user",
+ content: [
+ { type: "text", text: "what is this?" },
+ { type: "file", attachmentId: "p", mime: "application/pdf", filename: "doc.pdf" }
+ ]
+ }], { contextNoteId: "note123" }));
+
+ expect(buildNoteHintMock).toHaveBeenCalledWith("note123", true);
+ const prompt = FakeAcpClient.current?.requests.find(r => r.method === "session/prompt");
+ const blocks = (prompt?.params as { prompt: { type: string; text: string }[] }).prompt;
+ expect(blocks[0].text).toContain("NOTE_META(note123)");
+ expect(blocks.at(-1)).toEqual({ type: "text", text: "[attached file: doc.pdf]" });
+ });
+
+ it("resumes a mapped session, suppressing the load replay, and reseeds once the transcript diverges", async () => {
+ const provider = new CopilotAgentProvider();
+ FakeAcpClient.promptScript = async client => {
+ client.update({ sessionUpdate: "agent_message_chunk", content: { type: "text", text: "answer" } });
+ return { stopReason: "end_turn" };
+ };
+ await collect(provider.chatChunks([userMessage("hi")], { chatNoteId: "chat-resume" }));
+
+ // Same transcript → session/load instead of a fresh session/new, and no
+ // system instructions or history replay in the prompt.
+ FakeAcpClient.promptScript = async () => ({ stopReason: "end_turn" });
+ const resumed = await collect(provider.chatChunks(
+ [userMessage("hi"), assistantMessage("answer"), userMessage("more")],
+ { chatNoteId: "chat-resume" }
+ ));
+
+ const load = FakeAcpClient.current?.requests.find(r => r.method === "session/load");
+ expect(load?.params).toMatchObject({ sessionId: "sess-1", cwd: AGENT_CWD });
+ expect(FakeAcpClient.current?.requests.some(r => r.method === "session/new")).toBe(false);
+ expect(resumed).toEqual([{ type: "done" }]);
+ const prompt = FakeAcpClient.current?.requests.find(r => r.method === "session/prompt");
+ const blocks = (prompt?.params as { prompt: { type: string; text: string }[] }).prompt;
+ expect(blocks[0].text).toBe("more");
+
+ // An edited history no longer hashes to the mapped session, so the next
+ // turn must reseed rather than resume.
+ await collect(provider.chatChunks(
+ [userMessage("rewritten"), assistantMessage("answer"), userMessage("more")],
+ { chatNoteId: "chat-resume" }
+ ));
+ expect(FakeAcpClient.current?.requests.some(r => r.method === "session/load")).toBe(false);
+ expect(FakeAcpClient.current?.requests.some(r => r.method === "session/new")).toBe(true);
+ });
+
+ it("reseeds a fresh session when session/load fails", async () => {
+ const provider = new CopilotAgentProvider();
+ await collect(provider.chatChunks([userMessage("hi")], { chatNoteId: "chat-load-fail" }));
+
+ FakeAcpClient.sessionLoadError = new Error("unknown session");
+ FakeAcpClient.newSessionId = "sess-2";
+ const chunks = await collect(provider.chatChunks(
+ [userMessage("hi"), assistantMessage(""), userMessage("more")],
+ { chatNoteId: "chat-load-fail" }
+ ));
+
+ expect(FakeAcpClient.current?.requests.map(r => r.method))
+ .toEqual(["initialize", "session/load", "session/new", "session/prompt"]);
+ expect(infoLogMock).toHaveBeenCalledWith(expect.stringContaining("session/load failed (unknown session)"));
+ expect(chunks).toEqual([{ type: "done" }]);
+ // A reseeded session is told everything again: instructions + replay.
+ const prompt = FakeAcpClient.current?.requests.find(r => r.method === "session/prompt");
+ const blocks = (prompt?.params as { prompt: { type: string; text: string }[] }).prompt;
+ expect(blocks[0].text).toContain("<system_instructions>");
+ expect(blocks[0].text).toContain("<conversation_history>");
+ });
+
+ it("continues with the agent's default model when session/set_model fails", async () => {
+ FakeAcpClient.setModelError = new Error("model unavailable");
+
+ const provider = new CopilotAgentProvider();
+ const chunks = await collect(provider.chatChunks([userMessage("hi")], { model: "gpt-5.4" }));
+
+ expect(errorLogMock).toHaveBeenCalledWith(expect.stringContaining(`failed to select model "gpt-5.4"`));
+ expect(chunks).toEqual([{ type: "done" }]);
+ });
+
+ it("disposes the client and reports the failure when the initialize handshake fails", async () => {
+ FakeAcpClient.initializeError = new Error("handshake rejected");
+
+ const provider = new CopilotAgentProvider();
+ const chunks = await collect(provider.chatChunks([userMessage("hi")], {}));
+
+ expect(chunks).toEqual([{ type: "error", error: "handshake rejected" }]);
+ expect(FakeAcpClient.current?.disposed).toBe(true);
+ expect(FakeAcpClient.current?.requests.some(r => r.method === "session/new")).toBe(false);
+ });
+
+ it("maps prompt failures to actionable messages", async () => {
+ const provider = new CopilotAgentProvider();
+
+ FakeAcpClient.promptScript = async () => { throw new Error("the agent crashed"); };
+ expect(await collect(provider.chatChunks([userMessage("hi")], {})))
+ .toEqual([{ type: "error", error: "the agent crashed" }]);
+
+ // Non-Error rejections are stringified rather than dropped.
+ FakeAcpClient.promptScript = () => Promise.reject("plain rejection");
+ expect(await collect(provider.chatChunks([userMessage("hi")], {})))
+ .toEqual([{ type: "error", error: "plain rejection" }]);
+
+ // A spawn failure names the CLI that could not start.
+ FakeAcpClient.sessionNewError = new Error("spawn copilot ENOENT");
+ expect(await collect(provider.chatChunks([userMessage("hi")], {})))
+ .toEqual([{ type: "error", error: "Failed to start the GitHub Copilot CLI: spawn copilot ENOENT" }]);
+
+ // Auth problems are recognized by wording too, not only by error code.
+ FakeAcpClient.sessionNewError = new FakeAcpError(-32603, "authentication required");
+ expect(await collect(provider.chatChunks([userMessage("hi")], {})))
+ .toEqual([{ type: "error", error: expect.stringContaining("copilot login") }]);
+ });
+
+ it("describes early and unknown stop reasons", async () => {
+ const provider = new CopilotAgentProvider();
+ const errorFor = async (stopReason: string) => {
+ FakeAcpClient.promptScript = async () => ({ stopReason });
+ const chunks = await collect(provider.chatChunks([userMessage("hi")], {}));
+ return chunks.find(c => c.type === "error");
+ };
+
+ expect(await errorFor("max_tokens")).toEqual({ type: "error", error: expect.stringContaining("max tokens") });
+ expect(await errorFor("max_turn_requests")).toEqual({ type: "error", error: expect.stringContaining("max turn requests") });
+ expect(await errorFor("something_new")).toEqual({ type: "error", error: "Agent stopped: something_new" });
+ });
+
+ it("answers the permission callback and refuses every other agent request", async () => {
+ const provider = new CopilotAgentProvider();
+ await collect(provider.chatChunks([userMessage("hi")], {}));
+
+ const onAgentRequest = FakeAcpClient.current?.onAgentRequest;
+ expect(onAgentRequest?.("session/request_permission", {
+ toolCall: { toolCallId: "toolu_x", title: "Echo hello", kind: "execute" },
+ options: [{ optionId: "reject_once", kind: "reject_once" }]
+ })).toEqual({ outcome: { outcome: "selected", optionId: "reject_once" } });
+ expect(() => onAgentRequest?.("fs/read_text_file", {})).toThrow(`Trilium does not support "fs/read_text_file".`);
+ });
+
+ it("creates the agent cwd with a .git marker so enclosing repo config is not inherited", async () => {
+ fs.rmSync(AGENT_CWD, { recursive: true, force: true });
+
+ const provider = new CopilotAgentProvider();
+ await collect(provider.chatChunks([userMessage("hi")], {}));
+
+ expect(fs.readFileSync(path.join(AGENT_CWD, ".git", "HEAD"), "utf8")).toBe("ref: refs/heads/main\n");
+ expect(fs.existsSync(path.join(AGENT_CWD, ".git", "objects"))).toBe(true);
+ expect(fs.existsSync(path.join(AGENT_CWD, ".git", "refs"))).toBe(true);
+ });
+
+ it("evicts the oldest mapping once more chat notes are tracked than the limit", async () => {
+ const provider = new CopilotAgentProvider();
+ // One more than MAX_TRACKED_SESSIONS (200), so "lru-0" falls out.
+ for (let i = 0; i <= 200; i++) {
+ await collect(provider.chatChunks([userMessage("hi")], { chatNoteId: `lru-${i}` }));
+ }
+
+ const followUp = [userMessage("hi"), assistantMessage(""), userMessage("more")];
+ await collect(provider.chatChunks(followUp, { chatNoteId: "lru-0" }));
+ expect(FakeAcpClient.current?.requests.some(r => r.method === "session/load")).toBe(false);
+
+ await collect(provider.chatChunks(followUp, { chatNoteId: "lru-200" }));
+ expect(FakeAcpClient.current?.requests.some(r => r.method === "session/load")).toBe(true);
+ });
+});
+
+describe("CopilotAgentProvider.generateTitle", () => {
+ beforeEach(resetFakes);
+
+ it("accumulates the streamed title on the cheap model, trimming quotes and capping length", async () => {
+ const longTitle = "Weekly planning notes".padEnd(120, "!");
+ FakeAcpClient.promptScript = async client => {
+ client.onNotification("session/idle", {});
+ client.update({ sessionUpdate: "agent_thought_chunk", content: { type: "text", text: "thinking" } });
+ client.update({ sessionUpdate: "agent_message_chunk", content: { type: "image", data: "x", mimeType: "image/png" } });
+ client.update({ sessionUpdate: "agent_message_chunk", content: { type: "text", text: ` "${longTitle.slice(0, 30)}` } });
+ client.update({ sessionUpdate: "agent_message_chunk", content: { type: "text", text: `${longTitle.slice(30)}" ` } });
+ return { stopReason: "end_turn" };
+ };
+
+ const title = await new CopilotAgentProvider().generateTitle("plan my week");
+
+ expect(title).toBe(longTitle.substring(0, 100));
+ expect(FakeAcpClient.current?.requests.find(r => r.method === "session/set_model")?.params)
+ .toMatchObject({ modelId: "gpt-5-mini" });
+ expect(FakeAcpClient.current?.requests.find(r => r.method === "session/new")?.params)
+ .toMatchObject({ mcpServers: [] });
+ expect(FakeAcpClient.current?.disposed).toBe(true);
+ });
+
+ it("still produces a title when the cheap model cannot be selected", async () => {
+ FakeAcpClient.setModelError = new Error("model unavailable");
+ FakeAcpClient.promptScript = async client => {
+ client.update({ sessionUpdate: "agent_message_chunk", content: { type: "text", text: "Fallback title" } });
+ return { stopReason: "end_turn" };
+ };
+
+ expect(await new CopilotAgentProvider().generateTitle("hi")).toBe("Fallback title");
+ });
+
+ it("returns an empty title and logs when the agent fails", async () => {
+ FakeAcpClient.sessionNewError = new Error("spawn copilot ENOENT");
+
+ expect(await new CopilotAgentProvider().generateTitle("hi")).toBe("");
+ expect(errorLogMock).toHaveBeenCalledWith(expect.stringContaining("Failed to start the GitHub Copilot CLI"));
+ expect(FakeAcpClient.current?.disposed).toBe(true);
+ });
});
describe("decidePermission (fail-closed)", () => {
@@ -323,6 +579,84 @@ describe("decidePermission (fail-closed)", () => {
it("cancels the turn when only allow options are offered (never allows)", () => {
const decision = decidePermission({ toolCall: { toolCallId: "toolu_y" }, options: [{ optionId: "a", kind: "allow_once" }] });
expect(decision).toEqual({ outcome: { outcome: "cancelled" } });
+ // ...and when the request carries no tool call or options at all.
+ expect(decidePermission({})).toEqual({ outcome: { outcome: "cancelled" } });
+ });
+});
+
+describe("createUpdateCollector", () => {
+ type UpdateCollector = ReturnType<typeof createUpdateCollector>;
+
+ const notify = (collector: UpdateCollector, update: Record<string, unknown>, sessionId = "sess-1") =>
+ collector.onNotification("session/update", { sessionId, update });
+
+ /** A collector already bound to "sess-1", collecting into the returned array. */
+ function boundCollector(): { collector: UpdateCollector; chunks: LlmStreamChunk[] } {
+ const chunks: LlmStreamChunk[] = [];
+ const collector = createUpdateCollector(chunk => chunks.push(chunk));
+ collector.sessionId = "sess-1";
+ return { collector, chunks };
+ }
+
+ it("ignores other methods, muted replay, empty updates, and stray sessions", () => {
+ const chunks: LlmStreamChunk[] = [];
+ const collector = createUpdateCollector(chunk => chunks.push(chunk));
+ const message = { sessionUpdate: "agent_message_chunk", content: { type: "text", text: "nope" } };
+
+ collector.onNotification("session/idle", {});
+ collector.muted = true;
+ notify(collector, message);
+ collector.muted = false;
+ collector.onNotification("session/update", { sessionId: "sess-1" });
+ collector.sessionId = "sess-1";
+ notify(collector, message, "sess-other");
+
+ expect(chunks).toEqual([]);
+ });
+
+ it("drops message and thought chunks that carry no text, and unknown update kinds", () => {
+ const { collector, chunks } = boundCollector();
+
+ notify(collector, { sessionUpdate: "agent_message_chunk" });
+ notify(collector, { sessionUpdate: "agent_message_chunk", content: { type: "image", data: "x", mimeType: "image/png" } });
+ notify(collector, { sessionUpdate: "agent_thought_chunk", content: { type: "text", text: "" } });
+ notify(collector, { sessionUpdate: "plan", entries: [] });
+
+ expect(chunks).toEqual([]);
+ });
+
+ it("ignores malformed, duplicate, and unannounced tool calls", () => {
+ const { collector, chunks } = boundCollector();
+
+ notify(collector, { sessionUpdate: "tool_call", title: "missing id" });
+ notify(collector, { sessionUpdate: "tool_call_update", status: "completed" });
+ notify(collector, { sessionUpdate: "tool_call_update", toolCallId: "never-announced", status: "completed" });
+ expect(chunks).toEqual([]);
+
+ // A re-announcement keeps the first registration (untitled → "tool").
+ notify(collector, { sessionUpdate: "tool_call", toolCallId: "t1" });
+ notify(collector, { sessionUpdate: "tool_call", toolCallId: "t1", title: "re-announced" });
+ // Progress without a terminal status is not a result yet.
+ notify(collector, { sessionUpdate: "tool_call_update", toolCallId: "t1", status: "in_progress" });
+
+ expect(chunks).toEqual([{ type: "tool_use", toolCallId: "t1", toolName: "tool", toolInput: {} }]);
+ });
+
+ it("reports a failed tool call and falls back to rawOutput for the result text", () => {
+ const { collector, chunks } = boundCollector();
+
+ notify(collector, { sessionUpdate: "tool_call", toolCallId: "t1", title: "create_note" });
+ notify(collector, { sessionUpdate: "tool_call_update", toolCallId: "t1", status: "failed", rawOutput: { error: "denied" } });
+ notify(collector, { sessionUpdate: "tool_call", toolCallId: "t2", title: "read_note" });
+ // No usable text in the blocks and no rawOutput → an empty result.
+ notify(collector, { sessionUpdate: "tool_call_update", toolCallId: "t2", status: "completed", content: [null, { type: "image" }] });
+
+ expect(chunks).toEqual([
+ { type: "tool_use", toolCallId: "t1", toolName: "create_note", toolInput: {} },
+ { type: "tool_result", toolCallId: "t1", toolName: "create_note", result: `{"error":"denied"}`, isError: true },
+ { type: "tool_use", toolCallId: "t2", toolName: "read_note", toolInput: {} },
+ { type: "tool_result", toolCallId: "t2", toolName: "read_note", result: "", isError: false }
+ ]);
});
});
@@ -337,10 +671,13 @@ describe("buildPromptBlocks", () => {
expect(buildPromptBlocks("hello", "")).toEqual([{ type: "text", text: "hello" }]);
});
- it("emits an image block for a supported image attachment", () => {
+ it("emits an image block for a supported image attachment, led by the prefix", () => {
resolveAttachmentPartMock.mockReturnValue({ kind: "image", mime: "image/png", bytes: new Uint8Array([1, 2, 3]) });
- const blocks = buildPromptBlocks([{ type: "image", attachmentId: "a", mime: "image/png" }], "");
- expect(blocks).toEqual([{ type: "image", data: expect.any(String), mimeType: "image/png" }]);
+ const blocks = buildPromptBlocks([{ type: "image", attachmentId: "a", mime: "image/png" }], "PREFIX");
+ expect(blocks).toEqual([
+ { type: "text", text: "PREFIX" },
+ { type: "image", data: expect.any(String), mimeType: "image/png" }
+ ]);
});
it("inlines text attachments and placeholders unsupported ones", () => {
diff --git a/apps/server/src/services/llm/providers/copilot_agent.ts b/apps/server/src/services/llm/providers/copilot_agent.ts
index bf5904de4c..e5c135af28 100644
--- a/apps/server/src/services/llm/providers/copilot_agent.ts
+++ b/apps/server/src/services/llm/providers/copilot_agent.ts
@@ -637,6 +637,9 @@ function buildPromptBlocks(content: string | LlmMessagePart[], prefix: string):
/** Wrap the Trilium system prompt for delivery inside the first user prompt. */
function wrapSystemInstructions(systemPrompt: string): string | null {
+ // buildSystemPrompt appends the Markdown hints unconditionally, so the only
+ // caller can never pass an empty string — this is unreachable defence.
+ /* v8 ignore next 3 -- composeSystemPrompt never yields an empty prompt */
if (!systemPrompt) {
return null;
}
diff --git a/apps/server/src/services/llm/providers/copilot_mcp_endpoint.spec.ts b/apps/server/src/services/llm/providers/copilot_mcp_endpoint.spec.ts
new file mode 100644
index 0000000000..57f56a0d16
--- /dev/null
+++ b/apps/server/src/services/llm/providers/copilot_mcp_endpoint.spec.ts
@@ -0,0 +1,260 @@
+import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
+import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
+import { EventEmitter } from "events";
+import http from "http";
+import net from "net";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const infoLogMock = vi.hoisted(() => vi.fn());
+const errorLogMock = vi.hoisted(() => vi.fn());
+vi.mock("@triliumnext/core", () => ({
+ getLog: () => ({ info: infoLogMock, error: errorLogMock })
+}));
+
+// The real factory registers every LLM tool and drags in becca/the DB. Hand back
+// a bare SDK server instead, so the transport still talks to a genuine MCP peer.
+const createMcpServerMock = vi.hoisted(() => vi.fn());
+vi.mock("../../mcp/mcp_server.js", () => ({ createMcpServer: createMcpServerMock }));
+
+const { getCopilotMcpEndpointUrl, resetCopilotMcpEndpointForTests } =
+ await import("./copilot_mcp_endpoint.js");
+
+/** Loopback address, ephemeral port, 128-bit secret path. */
+const ENDPOINT_URL = /^http:\/\/127\.0\.0\.1:\d+\/mcp-[0-9a-f]{32}$/;
+
+/** What the Streamable HTTP transport insists on for a POST. */
+const MCP_HEADERS = {
+ "content-type": "application/json",
+ "accept": "application/json, text/event-stream"
+};
+
+/** A stand-in for http.createServer whose listen() fails, as a taken port would. */
+class UnstartableServer extends EventEmitter {
+ listen() {
+ setImmediate(() => this.emit("error", new Error("listen EADDRINUSE")));
+ return this;
+ }
+}
+
+interface HttpOptions {
+ method?: string;
+ headers?: Record<string, string>;
+ body?: Buffer | string;
+}
+
+interface HttpResult {
+ status: number;
+ body: string;
+}
+
+/** A one-off, non-keep-alive request so that `server.close()` never waits on us. */
+function request(url: string, opts: HttpOptions = {}): Promise<HttpResult> {
+ return new Promise<HttpResult>((resolve, reject) => {
+ const req = http.request(url, {
+ method: opts.method ?? "GET",
+ headers: { connection: "close", ...opts.headers },
+ agent: false
+ }, res => {
+ const chunks: Buffer[] = [];
+ res.on("data", (chunk: Buffer) => chunks.push(chunk));
+ res.on("end", () => resolve({
+ status: res.statusCode ?? 0,
+ body: Buffer.concat(chunks).toString()
+ }));
+ });
+ req.on("error", reject);
+ if (opts.body !== undefined) {
+ req.write(opts.body);
+ }
+ req.end();
+ });
+}
+
+/** HTTP/1.0 needs no Host header — the only way to reach the endpoint without one. */
+function rawGetWithoutHost(url: string): Promise<string> {
+ const { port, pathname } = new URL(url);
+ return new Promise<string>((resolve, reject) => {
+ const socket = net.connect(Number(port), "127.0.0.1", () => {
+ socket.write(`GET ${pathname} HTTP/1.0\r\n\r\n`);
+ });
+ let response = "";
+ socket.setEncoding("utf8");
+ socket.on("data", chunk => (response += chunk));
+ socket.on("end", () => resolve(response));
+ socket.on("error", reject);
+ });
+}
+
+describe("copilot MCP endpoint", () => {
+ let mcpServers: McpServer[];
+
+ beforeEach(() => {
+ mcpServers = [];
+ createMcpServerMock.mockReset();
+ createMcpServerMock.mockImplementation(() => {
+ const server = new McpServer({ name: "trilium-notes-spec", version: "1.2.3" });
+ vi.spyOn(server, "close");
+ mcpServers.push(server);
+ return server;
+ });
+ });
+
+ afterEach(async () => {
+ await resetCopilotMcpEndpointForTests();
+ vi.restoreAllMocks();
+ });
+
+ it("starts one loopback listener behind an unguessable path and memoizes it", async () => {
+ const createServerSpy = vi.spyOn(http, "createServer");
+
+ const url = await getCopilotMcpEndpointUrl();
+ expect(url).toMatch(ENDPOINT_URL);
+
+ await expect(getCopilotMcpEndpointUrl()).resolves.toBe(url);
+ expect(createServerSpy).toHaveBeenCalledTimes(1);
+ expect(infoLogMock).toHaveBeenCalledTimes(1);
+ });
+
+ it("logs a post-startup server error instead of taking the process down", async () => {
+ const createServerSpy = vi.spyOn(http, "createServer");
+ await getCopilotMcpEndpointUrl();
+
+ // An "error" event with no listener is re-thrown by EventEmitter, which
+ // would crash the server — the startup listener must have been replaced.
+ const server = createServerSpy.mock.results[0]?.value;
+ expect(() => server?.emit("error", new Error("late boom"))).not.toThrow();
+ expect(errorLogMock).toHaveBeenCalledWith(expect.stringContaining("late boom"));
+ });
+
+ it("does not cache a failed start, so a later call retries", async () => {
+ const failing = new UnstartableServer() as unknown as http.Server;
+ vi.spyOn(http, "createServer").mockReturnValueOnce(failing);
+
+ await expect(getCopilotMcpEndpointUrl()).rejects.toThrow(/EADDRINUSE/);
+ await expect(getCopilotMcpEndpointUrl()).resolves.toMatch(ENDPOINT_URL);
+ });
+
+ it("survives a reset issued while a start is still in flight", async () => {
+ const failing = new UnstartableServer() as unknown as http.Server;
+ vi.spyOn(http, "createServer").mockReturnValueOnce(failing);
+
+ const pending = getCopilotMcpEndpointUrl();
+ const reset = resetCopilotMcpEndpointForTests();
+
+ await expect(pending).rejects.toThrow(/EADDRINUSE/);
+ await expect(reset).resolves.toBeUndefined();
+ });
+
+ it("closes the listener on reset and hands out a fresh URL afterwards", async () => {
+ const first = await getCopilotMcpEndpointUrl();
+ await expect(request(first)).resolves.toMatchObject({ status: 406 });
+
+ await resetCopilotMcpEndpointForTests();
+ await expect(request(first)).rejects.toThrow(/ECONNREFUSED/);
+
+ await expect(getCopilotMcpEndpointUrl()).resolves.not.toBe(first);
+ });
+
+ it("404s every path but the secret one, without building an MCP server", async () => {
+ const url = await getCopilotMcpEndpointUrl();
+ const base = url.slice(0, url.lastIndexOf("/"));
+
+ await expect(request(`${base}/`)).resolves.toMatchObject({ status: 404 });
+ await expect(request(`${url}x`)).resolves.toMatchObject({ status: 404 });
+ expect(createMcpServerMock).not.toHaveBeenCalled();
+ });
+
+ it("answers an MCP handshake and disposes both peers on response close", async () => {
+ const transportClose = vi.spyOn(StreamableHTTPServerTransport.prototype, "close");
+ const url = await getCopilotMcpEndpointUrl();
+
+ const res = await request(url, {
+ method: "POST",
+ headers: MCP_HEADERS,
+ body: JSON.stringify({
+ jsonrpc: "2.0",
+ id: 1,
+ method: "initialize",
+ params: {
+ protocolVersion: "2025-06-18",
+ capabilities: {},
+ clientInfo: { name: "spec", version: "1.0.0" }
+ }
+ })
+ });
+
+ expect(res.status).toBe(200);
+ expect(res.body).toContain("trilium-notes-spec");
+
+ const mcpServer = mcpServers.at(-1);
+ await vi.waitFor(() => {
+ expect(transportClose).toHaveBeenCalled();
+ expect(mcpServer?.close).toHaveBeenCalled();
+ });
+ });
+
+ it("rejects a rebound Host and lets the bound one through", async () => {
+ const url = await getCopilotMcpEndpointUrl();
+
+ // The allowlist is pinned to the bound address, so a DNS-rebinding
+ // attempt is turned away before it reaches the transport. (Derived from
+ // req.headers.host it would filter to an empty list, which the SDK reads
+ // as "unrestricted" — the check has to be independent of the header.)
+ const rebound = await request(url, { headers: { host: "evil.example" } });
+ expect(rebound.status).toBe(403);
+ expect(rebound.body).toContain("Invalid Host header");
+
+ // Host absent entirely (HTTP/1.0) is also refused, though earlier: the
+ // transport cannot resolve a request URL without one, so it answers 400
+ // before the allowlist is consulted.
+ expect(await rawGetWithoutHost(url)).toContain("400 Bad Request");
+
+ // The address we actually handed the agent still reaches the transport,
+ // which turns a plain GET down for want of SSE.
+ expect((await request(url)).status).toBe(406);
+ });
+
+ it("answers 500 when the MCP server cannot be built", async () => {
+ const url = await getCopilotMcpEndpointUrl();
+ createMcpServerMock.mockImplementationOnce(() => {
+ throw new Error("becca unavailable");
+ });
+
+ const res = await request(url);
+ expect(res.status).toBe(500);
+ expect(JSON.parse(res.body)).toEqual({ error: "Internal MCP error" });
+ expect(errorLogMock).toHaveBeenCalledWith(expect.stringContaining("becca unavailable"));
+ });
+
+ it("leaves an already-sent response alone when the transport fails late", async () => {
+ const url = await getCopilotMcpEndpointUrl();
+ // A failure once the transport has started writing must only be logged:
+ // a second writeHead() would throw ERR_HTTP_HEADERS_SENT on top of it.
+ const handle = vi.spyOn(StreamableHTTPServerTransport.prototype, "handleRequest");
+ handle.mockImplementationOnce(async (_req, res) => {
+ res.writeHead(204).end();
+ throw new Error("late transport crash");
+ });
+
+ const res = await request(url);
+ expect(res.status).toBe(204);
+ expect(errorLogMock).toHaveBeenCalledWith(expect.stringContaining("late transport crash"));
+ });
+
+ it("treats an empty body as absent and refuses one over the 4 MB cap", async () => {
+ const url = await getCopilotMcpEndpointUrl();
+
+ // Nothing to parse: the transport is handed no body and reports the
+ // JSON-RPC parse error itself.
+ const empty = await request(url, { method: "POST", headers: MCP_HEADERS });
+ expect(empty.status).toBe(400);
+
+ // The oversized upload may be reset mid-flight, so assert on what the
+ // server logged rather than on what the client managed to read back.
+ const overCap = Buffer.alloc(4 * 1024 * 1024 + 1, 0x20);
+ await request(url, { method: "POST", headers: MCP_HEADERS, body: overCap })
+ .catch(() => undefined);
+ const overLimit = expect.stringContaining("4194304-byte limit");
+ await vi.waitFor(() => expect(errorLogMock).toHaveBeenCalledWith(overLimit));
+ });
+});
diff --git a/apps/server/src/services/llm/providers/copilot_mcp_endpoint.ts b/apps/server/src/services/llm/providers/copilot_mcp_endpoint.ts
index 22e69a8f04..66d54090c6 100644
--- a/apps/server/src/services/llm/providers/copilot_mcp_endpoint.ts
+++ b/apps/server/src/services/llm/providers/copilot_mcp_endpoint.ts
@@ -58,9 +58,12 @@ let listener: http.Server | undefined;
async function startEndpoint(): Promise<string> {
const secretPath = `/mcp-${randomBytes(16).toString("hex")}`;
+ // Filled in once the listener is bound. A request can only arrive after
+ // that, so handleRequest always observes the real address.
+ let boundHost = "";
const server = http.createServer((req, res) => {
- void handleRequest(req, res, secretPath);
+ void handleRequest(req, res, secretPath, boundHost);
});
listener = server;
@@ -83,12 +86,18 @@ async function startEndpoint(): Promise<string> {
throw new Error("Failed to determine the MCP endpoint's bound address.");
}
- const url = `http://127.0.0.1:${address.port}${secretPath}`;
- getLog().info(`Copilot Agent provider: note-tools MCP endpoint listening on 127.0.0.1:${address.port} (loopback only)`);
+ boundHost = `127.0.0.1:${address.port}`;
+ const url = `http://${boundHost}${secretPath}`;
+ getLog().info(`Copilot Agent provider: note-tools MCP endpoint listening on ${boundHost} (loopback only)`);
return url;
}
-async function handleRequest(req: http.IncomingMessage, res: http.ServerResponse, secretPath: string): Promise<void> {
+async function handleRequest(
+ req: http.IncomingMessage,
+ res: http.ServerResponse,
+ secretPath: string,
+ boundHost: string
+): Promise<void> {
try {
if (req.url !== secretPath) {
res.writeHead(404).end();
@@ -100,9 +109,11 @@ async function handleRequest(req: http.IncomingMessage, res: http.ServerResponse
const transport = new StreamableHTTPServerTransport({
sessionIdGenerator: undefined,
enableDnsRebindingProtection: true,
- // The agent connects via the URL we hand it, so the Host header is
- // always the bound loopback address.
- allowedHosts: [req.headers.host ?? ""].filter(h => /^127\.0\.0\.1:\d+$/.test(h))
+ // Pinned to the address we bound and handed to the agent. Deriving
+ // this from req.headers.host would be self-referential: a rebound
+ // Host filters down to an empty list, and the SDK skips the check
+ // entirely when the list is empty — so it could never reject.
+ allowedHosts: [boundHost]
});
res.on("close", () => {