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): keep ACP agents from outliving the server
Elian Doran297adc4bf1e1
diff --git a/apps/server/src/services/llm/providers/acp_client.spec.ts b/apps/server/src/services/llm/providers/acp_client.spec.tsindex 6ed0da7e72..449623729e 100644--- a/apps/server/src/services/llm/providers/acp_client.spec.ts+++ b/apps/server/src/services/llm/providers/acp_client.spec.ts@@ -3,7 +3,7 @@ import fs from "fs";import os from "os";import path from "path";import { PassThrough } from "stream";-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { afterEach, beforeEach, describe, expect, it, type MockInstance, vi } from "vitest";const infoLogMock = vi.hoisted(() => vi.fn());vi.mock("@triliumnext/core", () => ({ getLog: () => ({ info: infoLogMock, error: vi.fn() }) }));@@ -14,7 +14,6 @@ class FakeProc extends EventEmitter {stdin = new PassThrough();stdout = new PassThrough();stderr = new PassThrough();- killed = false;pid = 4242;written: string[] = [];@@ -23,11 +22,6 @@ class FakeProc extends EventEmitter {this.stdin.on("data", (chunk: Buffer) => this.written.push(chunk.toString()));}- kill() {- this.killed = true;- this.emit("exit", 0, null);- }-/** Simulate the agent writing a line to stdout. */send(obj: unknown) {this.stdout.write(`${JSON.stringify(obj)}\n`);@@ -37,7 +31,7 @@ class FakeProc extends EventEmitter {const spawnMock = vi.hoisted(() => vi.fn());vi.mock("child_process", () => ({ spawn: spawnMock }));-const { AcpClient, AcpError } = await import("./acp_client.js");+const { AcpClient, AcpError, killLiveAgents } = await import("./acp_client.js");function lastWritten(proc: FakeProc): Record<string, unknown> {return JSON.parse(proc.written[proc.written.length - 1]);@@ -51,15 +45,18 @@ function stubPlatform(platform: NodeJS.Platform) {describe("AcpClient", () => {let proc: FakeProc;+ let killSpy: MockInstance<typeof process.kill>;beforeEach(() => {proc = new FakeProc();spawnMock.mockReset();spawnMock.mockReturnValue(proc);infoLogMock.mockReset();+ killSpy = vi.spyOn(process, "kill").mockImplementation(() => true);});afterEach(() => {+ killSpy.mockRestore();vi.useRealTimers();if (originalPlatform) {Object.defineProperty(process, "platform", originalPlatform);@@ -78,6 +75,16 @@ describe("AcpClient", () => {expect(spawnMock).toHaveBeenLastCalledWith("/opt/agy/agy_acp_server.par", [], expect.anything());});+ it("starts the agent in its own process group except on Windows", () => {+ stubPlatform("linux");+ AcpClient.start("/opt/agy/agy_acp_server.par", { cwd: "/tmp" });+ expect(spawnMock).toHaveBeenLastCalledWith(expect.anything(), [], expect.objectContaining({ detached: true }));++ stubPlatform("win32");+ AcpClient.start("C:\\agy\\agy_acp_server.exe", { cwd: "C:\\tmp" });+ expect(spawnMock).toHaveBeenLastCalledWith(expect.anything(), [], expect.objectContaining({ detached: false }));+ });+it("layers extra environment variables over the process environment", () => {AcpClient.start("/opt/agy/agy_acp_server.par", { cwd: "/tmp", env: { GEMINI_HOME: "/data/home" } });const env = spawnMock.mock.lastCall?.[2]?.env as NodeJS.ProcessEnv | undefined;@@ -267,21 +274,49 @@ describe("AcpClient", () => {// An agent that exits on end of input is never signalled.proc.emit("exit", 0, null);vi.advanceTimersByTime(60_000);- expect(proc.killed).toBe(false);+ expect(killSpy).not.toHaveBeenCalled();// A request after disposal fails with the disposal error, not a crash.await expect(client.request("initialize", {})).rejects.toThrow(/disposed/);});- it("kills an agent that is still running after the grace period", () => {+ it("kills the process group of an agent that is still running after the grace period", () => {stubPlatform("linux");vi.useFakeTimers();const client = AcpClient.start("/bin/copilot", { cwd: "/tmp" });client.dispose();vi.advanceTimersByTime(4_999);- expect(proc.killed).toBe(false);+ expect(killSpy).not.toHaveBeenCalled();vi.advanceTimersByTime(1);- expect(proc.killed).toBe(true);+ expect(killSpy).toHaveBeenCalledExactlyOnceWith(-4242, "SIGKILL");+ });++ it("tolerates a process group that is already gone", () => {+ stubPlatform("linux");+ vi.useFakeTimers();+ killSpy.mockImplementation(() => {+ throw Object.assign(new Error("kill ESRCH"), { code: "ESRCH" });+ });+ AcpClient.start("/bin/copilot", { cwd: "/tmp" }).dispose();+ expect(() => vi.advanceTimersByTime(5_000)).not.toThrow();+ expect(killSpy).toHaveBeenCalledWith(-4242, "SIGKILL");+ });++ it("kills every agent still running when the server exits", () => {+ stubPlatform("linux");+ const exited = new FakeProc();+ exited.pid = 1001;+ const running = new FakeProc();+ running.pid = 1002;+ spawnMock.mockReturnValueOnce(exited).mockReturnValueOnce(running);+ AcpClient.start("/bin/copilot", { cwd: "/tmp" });+ AcpClient.start("/opt/agy/agy_acp_server.par", { cwd: "/tmp" });+ exited.emit("exit", 0, null);++ expect(process.listeners("exit")).toContain(killLiveAgents);+ killLiveAgents();+ expect(killSpy).toHaveBeenCalledWith(-1002, "SIGKILL");+ expect(killSpy).not.toHaveBeenCalledWith(-1001, "SIGKILL");});it("kills the agent's whole process tree on Windows, where it runs in a child of the spawned process", () => {@@ -291,19 +326,21 @@ describe("AcpClient", () => {client.dispose();vi.advanceTimersByTime(5_000);expect(spawnMock).toHaveBeenLastCalledWith("taskkill", [ "/pid", "4242", "/T", "/F" ], expect.objectContaining({ windowsHide: true }));- expect(proc.killed).toBe(false);+ expect(killSpy).not.toHaveBeenCalled();});it("rejects in-flight requests on dispose and ignores a second dispose", async () => {+ stubPlatform("linux");+ vi.useFakeTimers();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);+ vi.advanceTimersByTime(5_000);+ expect(killSpy).toHaveBeenCalledOnce();});it("ignores lines that are not JSON objects", async () => {diff --git a/apps/server/src/services/llm/providers/acp_client.ts b/apps/server/src/services/llm/providers/acp_client.tsindex bbfc761304..d878059cab 100644--- a/apps/server/src/services/llm/providers/acp_client.ts+++ b/apps/server/src/services/llm/providers/acp_client.ts@@ -122,6 +122,12 @@ export class AcpClient {});}+ /**+ * Run the agent as a subprocess. Outside Windows it leads its own process+ * group, so a Ctrl+C in the server's terminal does not reach it: the server+ * ends it through {@link dispose} or {@link killLiveAgents}, which kill the+ * whole group, including the processes the agent started.+ */static start(binary: string, options: AcpClientOptions): AcpClient {const proc = spawn(options.shell ? `"${binary}"` : binary,@@ -129,10 +135,12 @@ export class AcpClient {{cwd: options.cwd,shell: options.shell ?? false,+ detached: process.platform !== "win32",stdio: ["pipe", "pipe", "pipe"],env: options.env ? { ...process.env, ...options.env } : process.env});+ trackLiveAgent(proc);return new AcpClient({stdin: proc.stdin,stdout: proc.stdout,@@ -217,8 +225,8 @@ export class AcpClient {/*** Reject anything still in flight and end the subprocess: close its stdin so* it can exit on its own, and kill it only if it is still running after- * {@link DISPOSE_GRACE_MS}. `agy_acp_server` writes a crash report to stderr- * when it is killed, and stderr goes to the log.+ * {@link DISPOSE_GRACE_MS}. The kill is a SIGKILL, because an agent that is+ * still running after the grace period might not act on a SIGTERM.*/dispose(): void {if (this.disposed) {@@ -312,17 +320,47 @@ export class AcpClient {}}+/** Subprocess agents that have not exited yet, killed by {@link killLiveAgents} when the server exits. */+const liveAgents = new Set<ChildProcessWithoutNullStreams>();++function trackLiveAgent(proc: ChildProcessWithoutNullStreams): void {+ if (!process.listeners("exit").includes(killLiveAgents)) {+ process.on("exit", killLiveAgents);+ }+ liveAgents.add(proc);+ proc.on("exit", () => liveAgents.delete(proc));+}++/**+ * Kill every subprocess agent that is still running. The server's `exit`+ * handler calls it, so an agent cannot outlive the server.+ */+export function killLiveAgents(): void {+ for (const proc of liveAgents) {+ killProcessTree(proc);+ }+}+/*** End the agent and every process it started. On Windows `proc.kill()`* ends only the spawned process, while the agent can run in a child of it:* the PyInstaller build of `agy_acp_server` starts its server that way, and* a `.cmd` shim runs the CLI under `cmd.exe`. `taskkill /T` ends the tree.+ * Elsewhere the agent leads its own process group, and the negative PID+ * signals the whole group.*/function killProcessTree(proc: ChildProcessWithoutNullStreams): void {- if (process.platform === "win32" && proc.pid !== undefined) {+ if (proc.pid === undefined) {+ return;+ }+ if (process.platform === "win32") {const taskkill = spawn("taskkill", [ "/pid", String(proc.pid), "/T", "/F" ], { stdio: "ignore", windowsHide: true });taskkill.on("error", err => getLog().error(`Failed to end the ACP agent's process tree: ${err.message}`));return;}- proc.kill();+ try {+ process.kill(-proc.pid, "SIGKILL");+ } catch {+ // ESRCH: the group exited between the check and the signal.+ }}