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): harden the Copilot ACP client against crash and hang paths
Elian Dorand8602664b71f
diff --git a/apps/server/src/services/llm/providers/acp_client.spec.ts b/apps/server/src/services/llm/providers/acp_client.spec.tsindex b4a83c8e3b..2046932377 100644--- a/apps/server/src/services/llm/providers/acp_client.spec.ts+++ b/apps/server/src/services/llm/providers/acp_client.spec.ts@@ -143,13 +143,25 @@ describe("AcpClient", () => {await expect(client.request("initialize", {})).rejects.toThrow(/disposed/);});- it("ignores non-JSON lines on stdout", async () => {+ it("ignores lines that are not JSON objects", async () => {const onNotification = vi.fn();AcpClient.start("/bin/copilot", { cwd: "/tmp", onNotification });- proc.stdout.write("Welcome to Copilot!\n");+ proc.stdout.write("Welcome to Copilot!\n"); // not JSON at all+ proc.stdout.write("null\n"); // valid JSON, but no properties to read+ proc.stdout.write("42\n");proc.send({ jsonrpc: "2.0", method: "ping", params: {} });await vi.waitFor(() => expect(onNotification).toHaveBeenCalledWith("ping", {}));expect(onNotification).toHaveBeenCalledTimes(1);});++ it("survives an EPIPE on the subprocess's stdin", () => {+ AcpClient.start("/bin/copilot", { cwd: "/tmp" });++ // Node emits this when something writes to a subprocess that already+ // exited (a late session/cancel, or an agent-request reply resumed+ // after dispose()). An "error" event with no listener is re-thrown by+ // EventEmitter, which would take the server down.+ expect(() => proc.stdin.emit("error", new Error("write EPIPE"))).not.toThrow();+ });});diff --git a/apps/server/src/services/llm/providers/acp_client.ts b/apps/server/src/services/llm/providers/acp_client.tsindex 655d6ac31a..e6cf0e672e 100644--- a/apps/server/src/services/llm/providers/acp_client.ts+++ b/apps/server/src/services/llm/providers/acp_client.ts@@ -73,6 +73,13 @@ export class AcpClient {}});+ // Writing to a subprocess that already exited (a late session/cancel, or+ // an agent-request reply resumed after dispose()) emits EPIPE on stdin.+ // An unhandled stream "error" event would take the server down, and+ // failAll() has already rejected everything in flight — there is nothing+ // left to report.+ proc.stdin.on("error", () => {});+proc.on("error", err => this.failAll(new Error(`Failed to start the ACP agent: ${err.message}`)));proc.on("exit", (code, sig) => {// A deliberate dispose() kills the subprocess — that exit is expected@@ -118,7 +125,15 @@ export class AcpClient {reject(err);}});- this.send({ jsonrpc: "2.0", id, method, params });+ try {+ this.send({ jsonrpc: "2.0", id, method, params });+ } catch (err) {+ // A synchronous write failure would otherwise leave the timer+ // armed and the id stranded in `pending` until it elapses.+ clearTimeout(timer);+ this.pending.delete(id);+ reject(err instanceof Error ? err : new Error(String(err)));+ }});if (response.error) {throw new AcpError(response.error.code, response.error.message, response.error.data);@@ -151,7 +166,13 @@ export class AcpClient {}let message: JsonRpcMessage;try {- message = JSON.parse(line) as JsonRpcMessage;+ const parsed: unknown = JSON.parse(line);+ if (!parsed || typeof parsed !== "object") {+ // Valid JSON, but not a protocol message (a bare `null` would+ // otherwise blow up on the property reads below).+ return;+ }+ message = parsed as JsonRpcMessage;} catch {// Not part of the protocol stream (e.g. a stray banner) — ignore.return;diff --git a/apps/server/src/services/llm/providers/copilot_agent.spec.ts b/apps/server/src/services/llm/providers/copilot_agent.spec.tsindex 3db8e43363..73b71e1367 100644--- a/apps/server/src/services/llm/providers/copilot_agent.spec.ts+++ b/apps/server/src/services/llm/providers/copilot_agent.spec.ts@@ -234,6 +234,53 @@ describe("CopilotAgentProvider.chatChunks", () => {expect(FakeAcpClient.current?.notifications).toContainEqual({ method: "session/cancel", params: { sessionId: "sess-1" } });});+ it("ends the turn on abort even when the agent never answers the cancel", async () => {+ const controller = new AbortController();+ FakeAcpClient.promptScript = client => {+ client.update({ sessionUpdate: "agent_message_chunk", content: { type: "text", text: "partial" } });+ setTimeout(() => controller.abort(), 0);+ // Never settles: only the abort can end this turn.+ return new Promise<{ stopReason?: string }>(() => {});+ };++ const provider = new CopilotAgentProvider();+ const chunks = await collect(provider.chatChunks([userMessage("hi")], { chatNoteId: "chat-abort" }, controller.signal));++ expect(chunks).toEqual([{ type: "text", content: "partial" }, { type: "done" }]);+ expect(FakeAcpClient.current?.notifications).toContainEqual({ method: "session/cancel", params: { sessionId: "sess-1" } });+ expect(FakeAcpClient.current?.disposed).toBe(true);++ // The aborted session's real history is unknown, so the next turn must+ // reseed rather than resume it — even though the transcript lines up.+ FakeAcpClient.promptScript = async () => ({ stopReason: "end_turn" });+ await collect(provider.chatChunks(+ [userMessage("hi"), { role: "assistant", content: "partial" }, userMessage("more")],+ { chatNoteId: "chat-abort" }+ ));+ expect(FakeAcpClient.current?.requests.some(r => r.method === "session/load")).toBe(false);+ });++ it("flattens both wrapped and direct tool-result content blocks", async () => {+ FakeAcpClient.promptScript = async client => {+ client.update({ sessionUpdate: "tool_call", toolCallId: "t1", title: "search_notes" });+ client.update({+ sessionUpdate: "tool_call_update",+ toolCallId: "t1",+ status: "completed",+ content: [+ { type: "content", content: { type: "text", text: "wrapped" } },+ { type: "text", text: "direct" }+ ]+ });+ return { stopReason: "end_turn" };+ };++ const provider = new CopilotAgentProvider();+ const chunks = await collect(provider.chatChunks([userMessage("hi")], {}));++ expect(chunks).toContainEqual(expect.objectContaining({ type: "tool_result", result: "wrapped\ndirect" }));+ });+it("prepends the note-metadata hint to a fresh session's prompt", async () => {const provider = new CopilotAgentProvider();await collect(provider.chatChunks([userMessage("hi")], { contextNoteId: "note123" }));diff --git a/apps/server/src/services/llm/providers/copilot_agent.ts b/apps/server/src/services/llm/providers/copilot_agent.tsindex fa39022e25..bf5904de4c 100644--- a/apps/server/src/services/llm/providers/copilot_agent.ts+++ b/apps/server/src/services/llm/providers/copilot_agent.ts@@ -251,6 +251,10 @@ export class CopilotAgentProvider implements LlmProvider {if (sessionId) {client?.notify("session/cancel", { sessionId });}+ // Wake the drain loop below: an agent slow to honour the cancel+ // (or ignoring it) would otherwise keep this generator — and its+ // subprocess — suspended until PROMPT_TIMEOUT_MS elapses.+ wakeup?.();};signal?.addEventListener("abort", onAbort, { once: true });@@ -272,7 +276,9 @@ export class CopilotAgentProvider implements LlmProvider {let finished = false;void done.then(() => { finished = true; wakeup?.(); });- while (!finished || chunkQueue.length > 0) {+ // On abort, drain what already arrived and stop — nobody is+ // reading past this point, and `finally` disposes the client.+ while ((!finished && !signal?.aborted) || chunkQueue.length > 0) {if (chunkQueue.length === 0) {await new Promise<void>(resolve => { wakeup = resolve; });wakeup = undefined;@@ -298,7 +304,11 @@ export class CopilotAgentProvider implements LlmProvider {signal?.removeEventListener("abort", onAbort);}- if (config.chatNoteId && sessionId) {+ // An aborted turn stops draining before the agent settles, so the+ // session's real history is unknown — recording a hash here would+ // let a later turn resume a session that diverged from the+ // transcript. Forgetting it just reseeds a fresh one.+ if (config.chatNoteId && sessionId && !signal?.aborted) {rememberSession(config.chatNoteId, {sessionId,transcriptHash: hashTranscript([@@ -570,10 +580,14 @@ function flattenToolContent(content: unknown, rawOutput: unknown): string {if (Array.isArray(content)) {const texts = content.map(item => {- if (item && typeof item === "object" && "content" in item) {- return extractText((item as { content?: AcpContentBlock }).content);+ if (!item || typeof item !== "object") {+ return "";}- return "";+ // ACP wraps each block ({ type: "content", content: … }); some+ // agents pass the MCP result's blocks straight through instead.+ return "content" in item+ ? extractText((item as { content?: AcpContentBlock }).content)+ : extractText(item);}).filter(Boolean);if (texts.length > 0) {diff --git a/apps/server/src/services/llm/providers/copilot_mcp_endpoint.ts b/apps/server/src/services/llm/providers/copilot_mcp_endpoint.tsindex 15eb3202c7..22e69a8f04 100644--- a/apps/server/src/services/llm/providers/copilot_mcp_endpoint.ts+++ b/apps/server/src/services/llm/providers/copilot_mcp_endpoint.ts@@ -65,8 +65,16 @@ async function startEndpoint(): Promise<string> {listener = server;await new Promise<void>((resolve, reject) => {- server.once("error", reject);- server.listen(0, "127.0.0.1", () => resolve());+ const onStartupError = (err: Error) => reject(err);+ server.once("error", onStartupError);+ server.listen(0, "127.0.0.1", () => {+ // Past startup, rejecting a settled promise would drop the error+ // silently — log it instead (and keep a listener attached, since an+ // unhandled "error" event would crash the server).+ server.removeListener("error", onStartupError);+ server.on("error", err => getLog().error(`Copilot MCP endpoint server error: ${err}`));+ resolve();+ });});const address = server.address();@@ -113,9 +121,22 @@ async function handleRequest(req: http.IncomingMessage, res: http.ServerResponse}}+/**+ * Cap on the buffered request body. Only the agent subprocess we spawn should+ * ever reach this endpoint, but the public /mcp route is bounded by Express's+ * body parser and this raw listener bypasses it — keep the two comparable so a+ * local process that learned the secret path can't exhaust the heap.+ */+const MAX_BODY_BYTES = 4 * 1024 * 1024;+async function readJsonBody(req: http.IncomingMessage): Promise<unknown> {const chunks: Buffer[] = [];+ let totalBytes = 0;for await (const chunk of req) {+ totalBytes += (chunk as Buffer).length;+ if (totalBytes > MAX_BODY_BYTES) {+ throw new Error(`The MCP request body exceeds the ${MAX_BODY_BYTES}-byte limit.`);+ }chunks.push(chunk as Buffer);}const text = Buffer.concat(chunks).toString("utf8");