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
perf(llm): keep the ACP agent process alive across chat turns
Elian Doran6d734f34b448
diff --git a/apps/server/src/services/llm/providers/acp_agent.ts b/apps/server/src/services/llm/providers/acp_agent.tsindex cf52588b01..384376e6c2 100644--- a/apps/server/src/services/llm/providers/acp_agent.ts+++ b/apps/server/src/services/llm/providers/acp_agent.ts@@ -5,8 +5,10 @@* account's authentication, runs its own agentic loop and keeps conversation* history in host-side sessions. So every ACP provider:* - implements `chatChunks()` (chunk-native streaming) instead of `chat()`,+ * - keeps its agent process running between turns (see acp_client_pool.ts),* - maps chat notes to ACP sessions and sends only the newest user message- * when the transcript still matches (`session/load`), falling back to+ * when the transcript still matches, prompting the session directly while+ * its process runs and through `session/load` after that, and falls back to* seeding a fresh session from the transcript when it diverged or was lost,* - exposes note tools by pointing the agent at a private loopback MCP* endpoint (see acp_mcp_endpoint.ts), and answers the ACP permission@@ -28,6 +30,7 @@ import path from "path";import dataDirs from "../../data_dir.js";import { AcpClient } from "./acp_client.js";+import { AcpClientPool, type AcpLease, type AcpPoolConnection } from "./acp_client_pool.js";import { getAcpMcpEndpointUrl } from "./acp_mcp_endpoint.js";import { attachmentPlaceholder, buildHistoryReplay, hashTranscript } from "./transcript.js";@@ -114,6 +117,15 @@ interface SessionEntry {sessionId: string;/** Hash of the transcript as it stood when the session last responded. */transcriptHash: string;+ /** The {@link AcpLease.generation} of the process that holds the session. */+ generation: number;+ /**+ * Whether the session has the note-tools MCP server. MCP servers are fixed+ * at `session/new`, so a chat whose note access changed needs a new session.+ */+ noteToolsEnabled: boolean;+ /** The model state `session/new` or `session/load` reported, for the chat footer. */+ models?: AcpSessionModelState;}/**@@ -133,12 +145,17 @@ interface ProviderState {modelCatalogCache?: { models: ModelInfo[]; fetchedAt: number };modelCatalogInFlight?: Promise<ModelInfo[]>;agentCwd?: string;+ /** The agent process shared by chat turns and titles. */+ pool: AcpClientPool;}const stateByProvider = new Map<string, ProviderState>();-/** For tests: forget every provider's sessions, catalog and agent cwd. */+/** For tests: stop every pooled agent and forget every provider's sessions, catalog and agent cwd. */export function resetAcpAgentStateForTests(): void {+ for (const state of stateByProvider.values()) {+ state.pool.dispose();+ }stateByProvider.clear();}@@ -345,40 +362,53 @@ export abstract class AcpAgentProvider implements LlmProvider {};const collector = createUpdateCollector(emit, update => this.isInternalToolCall(update), update => this.describeBuiltInTool(update));- let client: AcpClient | undefined;- let sessionId: string | undefined;- let sessionModels: AcpSessionModelState | undefined;+ const pool = this.state().pool;+ let lease: AcpLease | undefined;+ let attachedSession: string | undefined;let assistantText = "";try {- client = await this.startClient(collector.onNotification, config);-- const mcpServers = noteToolsEnabled ? await buildMcpServersConfig() : [];-- // Resume the existing session only when the transcript still- // matches what it last saw; any divergence (edited history, lost- // mapping, server restart) reseeds a fresh session. session/load- // replays the session's history as notifications — the collector- // suppresses everything until the load completes.- if (resume) {- collector.muted = true;+ const acquired = await pool.acquire(connection => this.connect(connection));+ lease = acquired;+ const client = acquired.client;++ // Resume the mapped session only when the transcript still matches+ // what it last saw and it has the note access this turn asks for;+ // anything else (edited history, lost mapping, toggled note access)+ // reseeds a fresh session.+ const resumable = stored?.noteToolsEnabled === noteToolsEnabled ? resume : undefined;+ let sessionId: string | undefined;+ let sessionModels: AcpSessionModelState | undefined;+ if (resumable && stored?.generation === acquired.generation) {+ // The session is still loaded in this process, so the turn+ // prompts it directly. The CLIs reject `session/load` for it.+ sessionId = resumable;+ sessionModels = stored.models;+ } else if (resumable) {+ // The process that held the session ended. `session/load`+ // replays its history as notifications, which the pool drops+ // because no turn is attached to the session yet.try {- const loaded = await client.request<{ models?: AcpSessionModelState } | null>("session/load", { sessionId: resume, cwd: this.agentCwd(), mcpServers }, SESSION_TIMEOUT_MS);- sessionId = resume;+ const loaded = await client.request<{ models?: AcpSessionModelState } | null>(+ "session/load",+ { sessionId: resumable, cwd: this.agentCwd(), mcpServers: await buildMcpServersConfig(noteToolsEnabled) },+ SESSION_TIMEOUT_MS+ );+ sessionId = resumable;sessionModels = loaded?.models;} catch (err) {getLog().info(`${this.logLabel}: session/load failed (${describeError(err)}); reseeding a fresh session.`);- } finally {- collector.muted = false;}}if (!sessionId) {- const created = await this.createSession(client, { cwd: this.agentCwd(), mcpServers }, false, SESSION_TIMEOUT_MS);+ const created = await this.createSession(client, { cwd: this.agentCwd(), mcpServers: await buildMcpServersConfig(noteToolsEnabled) }, false, SESSION_TIMEOUT_MS);sessionId = created.sessionId;sessionModels = created.models;}collector.sessionId = sessionId;+ attachedSession = sessionId;+ pool.attach(sessionId, { onUpdate: params => collector.onNotification("session/update", params), config });// The catalog id the turn runs on, and the agent's own id for it when known.let runningModel = this.defaultModelId;@@ -400,7 +430,7 @@ export abstract class AcpAgentProvider implements LlmProvider {// instructions and replayed transcript when the session is fresh,// then the volatile current-note metadata hint (kept out of the// transcript hash so a later turn can still resume).- const isFreshSession = sessionId !== resume;+ const isFreshSession = sessionId !== resumable;const hasAttachments = Array.isArray(lastMessage.content) && lastMessage.content.some(p => p.type !== "text");const noteHint = config.contextNoteId ? buildNoteHint(config.contextNoteId, hasAttachments) : null;const prefix = [@@ -411,10 +441,12 @@ export abstract class AcpAgentProvider implements LlmProvider {const promptSessionId = sessionId;const onAbort = () => {- client?.notify("session/cancel", { sessionId: promptSessionId });+ // Cancel in-band: other chats share the process, so the turn+ // cannot end it.+ client.notify("session/cancel", { sessionId: promptSessionId });// 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.+ // (or ignoring it) would otherwise keep this generator suspended+ // until PROMPT_TIMEOUT_MS elapses.wakeup?.();};signal?.addEventListener("abort", onAbort, { once: true });@@ -438,7 +470,7 @@ export abstract class AcpAgentProvider implements LlmProvider {let finished = false;void done.then(() => { finished = true; wakeup?.(); });// On abort, drain what already arrived and stop — nobody is- // reading past this point, and `finally` disposes the client.+ // reading past this point.while ((!finished && !signal?.aborted) || chunkQueue.length > 0) {if (chunkQueue.length === 0) {await new Promise<void>(resolve => { wakeup = resolve; });@@ -470,13 +502,16 @@ export abstract class AcpAgentProvider implements LlmProvider {// 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) {+ if (config.chatNoteId && !signal?.aborted) {rememberSession(sessionsByChatNote, config.chatNoteId, {sessionId,transcriptHash: hashTranscript([...conversation,{ role: "assistant", content: assistantText }- ])+ ]),+ generation: acquired.generation,+ noteToolsEnabled,+ models: sessionModels});}@@ -484,25 +519,34 @@ export abstract class AcpAgentProvider implements LlmProvider {} catch (error) {yield { type: "error", error: this.describeFailure(error) };} finally {- client?.dispose();+ if (attachedSession) {+ pool.detach(attachedSession);+ }+ if (lease) {+ pool.release();+ }}}async generateTitle(firstMessage: string): Promise<string> {- let client: AcpClient | undefined;+ const pool = this.state().pool;+ let lease: AcpLease | undefined;+ let attachedSession: string | undefined;try {let title = "";- client = await this.startClient((method, params) => {- if (method !== "session/update") {- return;- }- const update = (params as AcpSessionUpdate).update;- if (update?.sessionUpdate === "agent_message_chunk" && update.content && "text" in update.content && update.content.type === "text") {- title += update.content.text;- }- });+ lease = await pool.acquire(connection => this.connect(connection));+ const client = lease.client;const { sessionId } = await this.createSession(client, { cwd: this.agentCwd(), mcpServers: [] }, false, SESSION_TIMEOUT_MS);+ attachedSession = sessionId;+ pool.attach(sessionId, {+ onUpdate: params => {+ const update = (params as AcpSessionUpdate).update;+ if (update?.sessionUpdate === "agent_message_chunk" && update.content && "text" in update.content && update.content.type === "text") {+ title += update.content.text;+ }+ }+ });const titleModel = this.titleModelId();if (titleModel) {try {@@ -527,15 +571,35 @@ export abstract class AcpAgentProvider implements LlmProvider {getLog().error(`${this.logLabel} title generation failed: ${this.describeFailure(error)}`);return "";} finally {- client?.dispose();+ if (attachedSession) {+ pool.detach(attachedSession);+ }+ if (lease) {+ pool.release();+ }}}+ /** Start the pooled agent, answering each permission request with its turn's configuration. */+ private connect(connection: AcpPoolConnection): Promise<AcpClient> {+ return this.startClient(connection.onNotification, {+ turnConfig: connection.turnConfig,+ onExit: connection.onExit+ });+ }+/**- * Spawn the agent and run the ACP initialize handshake. `config` is the chat- * turn's configuration, which the permission policy reads.+ * Spawn the agent and run the ACP initialize handshake. `turnConfig` gives+ * the configuration of the chat turn a permission request belongs to, which+ * the permission policy reads.*/- protected async startClient(onNotification: (method: string, params: unknown) => void, config?: LlmProviderConfig): Promise<AcpClient> {+ protected async startClient(+ onNotification: (method: string, params: unknown) => void,+ options: {+ turnConfig?: (sessionId: string | undefined) => LlmProviderConfig | undefined;+ onExit?: (error: Error) => void;+ } = {}+ ): Promise<AcpClient> {const launch = await this.launchSpec();const client = AcpClient.start(launch.binary, {cwd: this.agentCwd(),@@ -543,7 +607,12 @@ export abstract class AcpAgentProvider implements LlmProvider {args: launch.args,env: launch.env,onNotification,- onAgentRequest: (method, params) => this.handleAgentRequest(method, params, config)+ onAgentRequest: (method, params) => this.handleAgentRequest(+ method,+ params,+ options.turnConfig?.((params as { sessionId?: string } | undefined)?.sessionId)+ ),+ onExit: options.onExit});try {await client.request(@@ -607,7 +676,7 @@ export abstract class AcpAgentProvider implements LlmProvider {private state(): ProviderState {let state = stateByProvider.get(this.name);if (!state) {- state = { sessionsByChatNote: new Map() };+ state = { sessionsByChatNote: new Map(), pool: new AcpClientPool(this.logLabel) };stateByProvider.set(this.name, state);}return state;@@ -632,8 +701,8 @@ export function denyPermission(request: AcpPermissionRequest, logLabel: string):/*** Create the session/update collector: maps ACP updates to LlmStreamChunks and- * pushes them through `emit`. `muted` suppresses the replay flood during- * session/load; `sessionId` filters stray updates from other sessions.+ * pushes them through `emit`. `sessionId` filters stray updates from other+ * sessions.* `isHidden` keeps a tool call, and with it every update for that call, out* of the chat. `describeBuiltIn` names a built-in tool call the chat has a* label for; a call it leaves undescribed shows its title.@@ -648,10 +717,9 @@ export function createUpdateCollector(const toolNamesById = new Map<string, string>();const collector = {- muted: false,sessionId: undefined as string | undefined,onNotification(method: string, params: unknown): void {- if (method !== "session/update" || collector.muted) {+ if (method !== "session/update") {return;}const { sessionId, update } = params as AcpSessionUpdate;@@ -793,8 +861,11 @@ function rememberSession(sessionsByChatNote: Map<string, SessionEntry>, chatNote}}-/** The MCP server list for `session/new`/`session/load`, pointing at the private loopback endpoint. */-async function buildMcpServersConfig(): Promise<AcpMcpServer[]> {+/** The MCP server list for `session/new`/`session/load`: the private loopback endpoint, or none. */+async function buildMcpServersConfig(noteToolsEnabled: boolean): Promise<AcpMcpServer[]> {+ if (!noteToolsEnabled) {+ return [];+ }const url = await getAcpMcpEndpointUrl();return [{ name: NOTE_TOOLS_MCP_SERVER_NAME, type: "http", url, headers: [] }];}diff --git a/apps/server/src/services/llm/providers/acp_client.spec.ts b/apps/server/src/services/llm/providers/acp_client.spec.tsindex 8bb53b0e2c..d94c48add8 100644--- a/apps/server/src/services/llm/providers/acp_client.spec.ts+++ b/apps/server/src/services/llm/providers/acp_client.spec.ts@@ -225,6 +225,25 @@ describe("AcpClient", () => {await expect(promise).rejects.toThrow(/exited unexpectedly/);});+ it("reports its own death to onExit once, but not a dispose", () => {+ const onExit = vi.fn();+ const client = AcpClient.start("/bin/copilot", { cwd: "/tmp", onExit });+ expect(client.alive).toBe(true);++ proc.emit("error", new Error("spawn ENOENT"));+ proc.emit("exit", 1, null);+ expect(client.alive).toBe(false);+ expect(onExit).toHaveBeenCalledTimes(1);+ expect(onExit).toHaveBeenCalledWith(new Error("Failed to start the ACP agent: spawn ENOENT"));++ const disposedExit = vi.fn();+ const disposed = AcpClient.start("/bin/copilot", { cwd: "/tmp", onExit: disposedExit });+ disposed.dispose();+ proc.emit("exit", 0, null);+ expect(disposed.alive).toBe(false);+ expect(disposedExit).not.toHaveBeenCalled();+ });+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", {});diff --git a/apps/server/src/services/llm/providers/acp_client.ts b/apps/server/src/services/llm/providers/acp_client.tsindex 1c47c1fb74..6837df7c2c 100644--- a/apps/server/src/services/llm/providers/acp_client.ts+++ b/apps/server/src/services/llm/providers/acp_client.ts@@ -59,6 +59,13 @@ export interface AcpClientOptions {* When no handler is set, requests are answered with "method not found".*/onAgentRequest?: (method: string, params: unknown) => Promise<unknown> | unknown;+ /**+ * Called once when the subprocess dies on its own (crash, kill, agent+ * exit) — never for a deliberate {@link AcpClient.dispose}. A pooled+ * client uses this to evict itself so the next turn starts a fresh agent+ * instead of handing out a corpse.+ */+ onExit?: (error: Error) => void;}export class AcpClient {@@ -89,13 +96,13 @@ export class AcpClient {// 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("error", err => this.die(new Error(`Failed to start the ACP agent: ${err.message}`)));proc.on("exit", (code, sig) => {this.exited = true;// A deliberate dispose() ends the subprocess — that exit is expected// and must not surface as an error for in-flight (cancelled) requests.if (!this.disposed) {- this.failAll(new Error(`The ACP agent exited unexpectedly (${sig ?? `code ${code}`}).`));+ this.die(new Error(`The ACP agent exited unexpectedly (${sig ?? `code ${code}`}).`));}});}@@ -243,6 +250,23 @@ export class AcpClient {}}+ /** Whether the subprocess is still usable (not disposed, not exited). */+ get alive(): boolean {+ return !this.disposed && this.exitError === undefined;+ }++ /**+ * The subprocess died on its own. Fails everything in flight, then tells+ * the owner exactly once so a pooled client can evict itself.+ */+ private die(error: Error): void {+ const alreadyDead = this.exitError !== undefined;+ this.failAll(error);+ if (!alreadyDead) {+ this.options.onExit?.(error);+ }+ }+private failAll(error: Error): void {this.exitError = error;for (const entry of this.pending.values()) {diff --git a/apps/server/src/services/llm/providers/acp_client_pool.ts b/apps/server/src/services/llm/providers/acp_client_pool.tsnew file mode 100644index 0000000000..4b6f3920f7--- /dev/null+++ b/apps/server/src/services/llm/providers/acp_client_pool.ts@@ -0,0 +1,179 @@+/**+ * Keeps one ACP agent subprocess per provider alive across chat turns.+ *+ * Starting an agent and opening a session is expensive: a cold Copilot turn+ * pays ~785 ms to spawn and run `initialize` plus ~2.4 s for the first+ * `session/new`, and Antigravity's server takes ~15 s to start on Windows. None+ * of that is model latency, and all of it repeats on every message when the+ * client is disposed at the end of each turn.+ *+ * ACP is built for sharing: one connection hosts many sessions, each addressed+ * by `sessionId`. So the pool hands every turn the same client, routes each+ * `session/update` and permission request to the turn that owns its session,+ * and reaps the subprocess after {@link IDLE_TIMEOUT_MS} without a turn. A+ * client that dies on its own evicts itself, so the next turn starts a new one.+ */++import { getLog } from "@triliumnext/core";+import type { LlmProviderConfig } from "@triliumnext/core/src/services/llm/types.js";++import type { AcpClient } from "./acp_client.js";++/**+ * How long a client with no active turns is kept warm: long enough to cover a+ * user reading a reply and following up, short enough that a Trilium left open+ * overnight does not hold a subprocess.+ */+export const IDLE_TIMEOUT_MS = 5 * 60_000;++/** What a turn registers for its session on the shared connection. */+export interface AcpSessionTurn {+ /** Receives the session's `session/update` notifications. */+ onUpdate: (params: unknown) => void;+ /** The chat turn's configuration, which the permission policy reads. */+ config?: LlmProviderConfig;+}++/** The callbacks a pooled client is started with. */+export interface AcpPoolConnection {+ onNotification: (method: string, params: unknown) => void;+ /** The configuration of the turn that owns `sessionId`, if one is attached. */+ turnConfig: (sessionId: string | undefined) => LlmProviderConfig | undefined;+ onExit: (error: Error) => void;+}++export interface AcpLease {+ readonly client: AcpClient;+ /**+ * Identifies the subprocess the lease belongs to. A session exists only in+ * the process that created or loaded it, so a caller compares generations+ * before prompting a session it mapped earlier.+ */+ readonly generation: number;+}++interface PooledClient {+ client: AcpClient;+ generation: number;+ turns: Map<string, AcpSessionTurn>;+}++export class AcpClientPool {+ private pooled?: PooledClient;+ /** The in-flight start, so concurrent first turns share one spawn. */+ private starting?: Promise<PooledClient>;+ private generationCounter = 0;+ private activeTurns = 0;+ private idleTimer?: NodeJS.Timeout;++ constructor(private readonly logLabel: string) {}++ /**+ * Borrow the shared client for one turn, starting it with `connect` if no+ * live one exists. Every successful call must be paired with+ * {@link release}: the count keeps a turn's subprocess from being reaped.+ */+ async acquire(connect: (connection: AcpPoolConnection) => Promise<AcpClient>): Promise<AcpLease> {+ // Count the turn before any await, so an idle reap cannot run between+ // the client being handed out and the caller using it.+ this.activeTurns++;+ this.cancelIdleTimer();+ try {+ const entry = await this.startOrReuse(connect);+ return { client: entry.client, generation: entry.generation };+ } catch (err) {+ this.release();+ throw err;+ }+ }++ /** Return a lease. The client is reaped once no turn has used it for {@link IDLE_TIMEOUT_MS}. */+ release(): void {+ this.activeTurns = Math.max(0, this.activeTurns - 1);+ if (this.activeTurns === 0 && this.pooled) {+ this.armIdleTimer();+ }+ }++ /**+ * Route a session's updates and permission requests to a turn. Updates for+ * a session without a turn are dropped, which keeps one chat's output out of+ * another and a `session/load` replay out of the chat.+ */+ attach(sessionId: string, turn: AcpSessionTurn): void {+ this.pooled?.turns.set(sessionId, turn);+ }++ detach(sessionId: string): void {+ this.pooled?.turns.delete(sessionId);+ }++ /** Stop the pooled subprocess now. */+ dispose(): void {+ this.cancelIdleTimer();+ const entry = this.pooled;+ this.pooled = undefined;+ this.starting = undefined;+ this.activeTurns = 0;+ entry?.turns.clear();+ entry?.client.dispose();+ }++ private async startOrReuse(connect: (connection: AcpPoolConnection) => Promise<AcpClient>): Promise<PooledClient> {+ if (this.pooled?.client.alive) {+ return this.pooled;+ }+ this.pooled = undefined;+ if (!this.starting) {+ this.starting = this.start(connect).finally(() => {+ this.starting = undefined;+ });+ }+ return this.starting;+ }++ private async start(connect: (connection: AcpPoolConnection) => Promise<AcpClient>): Promise<PooledClient> {+ const generation = ++this.generationCounter;+ const turns = new Map<string, AcpSessionTurn>();+ const client = await connect({+ onNotification: (method, params) => {+ const sessionId = (params as { sessionId?: string } | undefined)?.sessionId;+ if (method === "session/update" && sessionId) {+ turns.get(sessionId)?.onUpdate(params);+ }+ },+ turnConfig: sessionId => (sessionId ? turns.get(sessionId)?.config : undefined),+ onExit: error => {+ // Evict only this generation: a later one can already be running.+ if (this.pooled?.generation === generation) {+ this.pooled = undefined;+ }+ turns.clear();+ getLog().info(`${this.logLabel}: agent process #${generation} ended (${error.message}); the next turn starts a new one.`);+ }+ });+ const entry: PooledClient = { client, generation, turns };+ this.pooled = entry;+ return entry;+ }++ private armIdleTimer(): void {+ this.cancelIdleTimer();+ this.idleTimer = setTimeout(() => {+ this.idleTimer = undefined;+ if (this.activeTurns === 0 && this.pooled) {+ getLog().info(`${this.logLabel}: reaping the idle agent process after ${Math.round(IDLE_TIMEOUT_MS / 1000)} s.`);+ this.dispose();+ }+ }, IDLE_TIMEOUT_MS);+ // An idle reap does not keep the server running.+ this.idleTimer.unref?.();+ }++ private cancelIdleTimer(): void {+ if (this.idleTimer) {+ clearTimeout(this.idleTimer);+ this.idleTimer = undefined;+ }+ }+}diff --git a/apps/server/src/services/llm/providers/antigravity_agent.spec.ts b/apps/server/src/services/llm/providers/antigravity_agent.spec.tsindex 33ac930b91..c0d9c542b8 100644--- a/apps/server/src/services/llm/providers/antigravity_agent.spec.ts+++ b/apps/server/src/services/llm/providers/antigravity_agent.spec.ts@@ -50,6 +50,8 @@ class FakeAcpClient {static sessionFailure: Error | undefined;/** The session/update payloads the agent streams while answering session/prompt. */static promptUpdates: Record<string, unknown>[] = [];+ /** Runs while session/prompt is answered, as the agent's own requests do. */+ static onPrompt: ((client: FakeAcpClient) => Promise<void>) | undefined;requests: { method: string; params: unknown }[] = [];onAgentRequest?: (method: string, params: unknown) => unknown;@@ -78,6 +80,7 @@ class FakeAcpClient {for (const update of FakeAcpClient.promptUpdates) {this.onNotification?.("session/update", { sessionId: "sess-1", update });}+ await FakeAcpClient.onPrompt?.(this);return { stopReason: "end_turn" } as T;}return {} as T;@@ -85,6 +88,9 @@ class FakeAcpClient {notify(): void {}dispose(): void {}+ get alive(): boolean {+ return true;+ }methods(): string[] {return this.requests.map(r => r.method);@@ -130,8 +136,22 @@ beforeEach(() => {FakeAcpClient.availableModels = REMOTE_MODELS;FakeAcpClient.sessionFailure = undefined;FakeAcpClient.promptUpdates = [];+ FakeAcpClient.onPrompt = undefined;});+/** Answer permission requests the way the agent asks them: during a chat turn, on its session. */+async function decideDuringTurn(config: Record<string, unknown>, requests: Record<string, unknown>[]): Promise<unknown[]> {+ const answers: unknown[] = [];+ FakeAcpClient.onPrompt = async client => {+ for (const request of requests) {+ answers.push(await client.onAgentRequest?.("session/request_permission", { sessionId: "sess-1", ...request }));+ }+ };+ await collect(new AntigravityAgentProvider().chatChunks([{ role: "user", content: "hi" }], config));+ FakeAcpClient.onPrompt = undefined;+ return answers;+}+describe("decideAntigravityPermission", () => {// Shapes captured from agy_acp_server 1.1.1.it("approves once a call to Trilium's note-tools MCP server", () => {@@ -233,12 +253,13 @@ describe("AntigravityAgentProvider", () => {it("lets the agent search the web only when the chat allows it", async () => {const request = { toolCall: { kind: "search", title: "Run search_web?", rawInput: { query: "x" } }, options: PERMISSION_OPTIONS };- await collect(new AntigravityAgentProvider().chatChunks([{ role: "user", content: "hi" }], { enableWebSearch: true }));- expect(FakeAcpClient.current?.onAgentRequest?.("session/request_permission", request))- .toEqual({ outcome: { outcome: "selected", optionId: "allow" } });-- await collect(new AntigravityAgentProvider().chatChunks([{ role: "user", content: "hi" }], {}));- expect(FakeAcpClient.current?.onAgentRequest?.("session/request_permission", request))+ expect(await decideDuringTurn({ enableWebSearch: true }, [request]))+ .toEqual([{ outcome: { outcome: "selected", optionId: "allow" } }]);+ expect(await decideDuringTurn({}, [request]))+ .toEqual([{ outcome: { outcome: "selected", optionId: "deny" } }]);+ // The chats share one agent process, so a request from a session no+ // turn owns gets no chat's settings.+ expect(FakeAcpClient.current?.onAgentRequest?.("session/request_permission", { sessionId: "sess-1", ...request })).toEqual({ outcome: { outcome: "selected", optionId: "deny" } });});@@ -251,20 +272,17 @@ describe("AntigravityAgentProvider", () => {const allowed = { outcome: { outcome: "selected", optionId: "allow" } };const denied = { outcome: { outcome: "selected", optionId: "deny" } };- await collect(new AntigravityAgentProvider().chatChunks([{ role: "user", content: "hi" }], { enableWebSearch: true }));- const decide = (request: unknown) => FakeAcpClient.current?.onAgentRequest?.("session/request_permission", request);- expect(await decide(readUrl("https://93.184.215.14/"))).toEqual(allowed);- expect(await decide(readUrl("http://127.0.0.1:8080/"))).toEqual(denied);- expect(await decide(readUrl("file:///C:/antigravity-acp/acp_token.json"))).toEqual(denied);- // A shell command the model titled like a page read.- expect(await decide({ ...readUrl("https://93.184.215.14/"), toolCall: { kind: "execute", title: "Run read_url_content?", rawInput: { Url: "https://93.184.215.14/" } } }))- .toEqual(denied);-- // A page read that names no URL.- expect(await decide({ ...readUrl(""), toolCall: { kind: "fetch", title: "Run read_url_content?", rawInput: {} } })).toEqual(denied);-- await collect(new AntigravityAgentProvider().chatChunks([{ role: "user", content: "hi" }], {}));- expect(await FakeAcpClient.current?.onAgentRequest?.("session/request_permission", readUrl("https://93.184.215.14/"))).toEqual(denied);+ expect(await decideDuringTurn({ enableWebSearch: true }, [+ readUrl("https://93.184.215.14/"),+ readUrl("http://127.0.0.1:8080/"),+ readUrl("file:///C:/antigravity-acp/acp_token.json"),+ // A shell command the model titled like a page read.+ { ...readUrl("https://93.184.215.14/"), toolCall: { kind: "execute", title: "Run read_url_content?", rawInput: { Url: "https://93.184.215.14/" } } },+ // A page read that names no URL.+ { ...readUrl(""), toolCall: { kind: "fetch", title: "Run read_url_content?", rawInput: {} } }+ ])).toEqual([allowed, denied, denied, denied, denied]);++ expect(await decideDuringTurn({}, [readUrl("https://93.184.215.14/")])).toEqual([denied]);});it("explains a failure to start, sign in or answer in words the user can act on", async () => {@@ -282,6 +300,8 @@ describe("AntigravityAgentProvider", () => {const originalPlatform = Object.getOwnPropertyDescriptor(process, "platform");const argsOn = async (platform: NodeJS.Platform) => {Object.defineProperty(process, "platform", { ...originalPlatform, value: platform });+ // Each platform launches its own process.+ resetAcpAgentStateForTests();await collect(new AntigravityAgentProvider().chatChunks([{ role: "user", content: "hi" }], {}));return FakeAcpClient.lastStart?.opts.args;};@@ -330,11 +350,13 @@ describe("AntigravityAgentProvider", () => {expect(FakeAcpClient.current?.methods()).not.toContain("session/set_model");await collect(provider.chatChunks([{ role: "user", content: "hi" }], { model: "gemini-pro-agent" }));- expect(FakeAcpClient.current?.requests.find(r => r.method === "session/set_model")?.params).toEqual({ sessionId: "sess-1", modelId: "gemini-pro-agent" });+ expect(FakeAcpClient.current?.requests.filter(r => r.method === "session/set_model").at(-1)?.params).toEqual({ sessionId: "sess-1", modelId: "gemini-pro-agent" });+ // The probe runs on a client of its own; the title runs on the chats' process.+ const pooled = FakeAcpClient.current;await provider.listModels();await provider.generateTitle("plan my week");- expect(FakeAcpClient.current?.requests.find(r => r.method === "session/set_model")?.params).toEqual({ sessionId: "sess-1", modelId: "gemini-3.8-flash-low" });+ expect(pooled?.requests.filter(r => r.method === "session/set_model").at(-1)?.params).toEqual({ sessionId: "sess-1", modelId: "gemini-3.8-flash-low" });});it("pre-selects the newest version of each family", () => {@@ -352,7 +374,7 @@ describe("AntigravityAgentProvider", () => {const provider = new AntigravityAgentProvider();const modelSetFor = async (config: Record<string, unknown>) => {await collect(provider.chatChunks([{ role: "user", content: "hi" }], config));- return (FakeAcpClient.current?.requests.find(r => r.method === "session/set_model")?.params as { modelId?: string } | undefined)?.modelId;+ return (FakeAcpClient.current?.requests.filter(r => r.method === "session/set_model").at(-1)?.params as { modelId?: string } | undefined)?.modelId;};expect(await modelSetFor({ model: "gemini-3.8-flash", reasoningEffort: "medium" })).toBe("gemini-3.8-flash-medium");diff --git a/apps/server/src/services/llm/providers/copilot_agent.live.spec.ts b/apps/server/src/services/llm/providers/copilot_agent.live.spec.tsnew file mode 100644index 0000000000..952c4448b3--- /dev/null+++ b/apps/server/src/services/llm/providers/copilot_agent.live.spec.ts@@ -0,0 +1,77 @@+/**+ * Live integration test for the Copilot Agent keep-alive: drives the user's+ * real `copilot` CLI and asserts that a second turn skips the spawn and the+ * session handshake the first one paid for.+ *+ * Opt-in — it spawns a subprocess, needs `copilot login`, and spends the+ * subscription's premium-request budget, so it never runs in CI:+ *+ * TRILIUM_COPILOT_LIVE_TEST=1 pnpm --filter server test copilot_agent.live+ */++import type { LlmStreamChunk } from "@triliumnext/commons";+import { describe, expect, it, vi } from "vitest";++import { AcpClient } from "./acp_client.js";+import { CopilotAgentProvider, resetModelCatalogCacheForTests } from "./copilot_agent.js";++const live = process.env.TRILIUM_COPILOT_LIVE_TEST === "1";++/** The cheapest model on the subscription (0x premium multiplier). */+const MODEL = "gpt-5-mini";++describe.runIf(live)("CopilotAgentProvider keep-alive (live CLI)", () => {+ it("answers a second turn without re-paying the spawn and session handshake", async () => {+ const provider = new CopilotAgentProvider();+ const chatNoteId = "live-keep-alive";+ resetModelCatalogCacheForTests();++ // Record the ACP methods each turn issues, so the assertions describe+ // the protocol traffic rather than inferring it from wall-clock time.+ let methods: string[] = [];+ const originalRequest = AcpClient.prototype.request;+ vi.spyOn(AcpClient.prototype, "request").mockImplementation(function (this: AcpClient, method: string, params: unknown, timeoutMs?: number) {+ methods.push(method);+ return originalRequest.call(this, method, params, timeoutMs);+ } as never);++ async function turn(messages: { role: "user" | "assistant"; content: string }[]) {+ methods = [];+ const startedAt = Date.now();+ let firstTokenMs: number | undefined;+ let text = "";+ for await (const chunk of provider.chatChunks(messages, { chatNoteId, model: MODEL, enableNoteTools: false })) {+ const typed = chunk as LlmStreamChunk;+ if (typed.type === "text") {+ firstTokenMs ??= Date.now() - startedAt;+ text += typed.content;+ } else if (typed.type === "error") {+ throw new Error(`Live agent turn failed: ${typed.error}`);+ }+ }+ return { firstTokenMs, text, methods: [...methods] };+ }++ const cold = await turn([{ role: "user", content: "Reply with exactly the word: alpha" }]);+ const warm = await turn([+ { role: "user", content: "Reply with exactly the word: alpha" },+ { role: "assistant", content: cold.text },+ { role: "user", content: "Reply with exactly the word: beta" }+ ]);++ console.log(+ `live keep-alive: cold ${cold.firstTokenMs} ms [${cold.methods.join(", ")}]`+ + ` | warm ${warm.firstTokenMs} ms [${warm.methods.join(", ")}]`+ + ` | cold reply ${JSON.stringify(cold.text)} | warm reply ${JSON.stringify(warm.text)}`+ );++ expect(cold.text.toLowerCase()).toContain("alpha");+ expect(warm.text.toLowerCase()).toContain("beta");+ // The warm turn talks to a session that is already loaded.+ expect(warm.methods).toEqual(["session/set_model", "session/prompt"]);+ // The warm turn skips the spawn (~0.8 s) plus the cold session/new+ // (~2.4 s). Assert a conservative fraction of that so the test tracks+ // the behaviour rather than this machine's exact numbers.+ expect(warm.firstTokenMs).toBeLessThan((cold.firstTokenMs ?? 0) - 1000);+ }, 180_000);+});diff --git a/apps/server/src/services/llm/providers/copilot_agent.spec.ts b/apps/server/src/services/llm/providers/copilot_agent.spec.tsindex 9465fe2648..fcf81a4756 100644--- a/apps/server/src/services/llm/providers/copilot_agent.spec.ts+++ b/apps/server/src/services/llm/providers/copilot_agent.spec.ts@@ -44,6 +44,7 @@ vi.mock("@triliumnext/core/src/services/llm/attachment_content.js", () => ({ resclass FakeAcpClient {onNotification: (method: string, params: unknown) => void;onAgentRequest?: (method: string, params: unknown) => unknown;+ onExit?: (error: Error) => void;requests: { method: string; params: unknown }[] = [];notifications: { method: string; params: unknown }[] = [];disposed = false;@@ -63,12 +64,13 @@ class FakeAcpClient {*/static sessionModels: unknown = undefined;- constructor(opts: { onNotification: (m: string, p: unknown) => void; onAgentRequest?: (m: string, p: unknown) => unknown }) {+ constructor(opts: { onNotification: (m: string, p: unknown) => void; onAgentRequest?: (m: string, p: unknown) => unknown; onExit?: (e: Error) => void }) {this.onNotification = opts.onNotification;this.onAgentRequest = opts.onAgentRequest;+ this.onExit = opts.onExit;}- static start(_binary: string, opts: { args?: string[]; onNotification: (m: string, p: unknown) => void; onAgentRequest?: (m: string, p: unknown) => unknown }) {+ static start(_binary: string, opts: { args?: string[]; onNotification: (m: string, p: unknown) => void; onAgentRequest?: (m: string, p: unknown) => unknown; onExit?: (e: Error) => void }) {FakeAcpClient.current = new FakeAcpClient(opts);return FakeAcpClient.current;}@@ -105,6 +107,22 @@ class FakeAcpClient {this.disposed = true;}+ /** Like the real client, the pool reuses only a live subprocess. */+ get alive(): boolean {+ return !this.disposed;+ }++ /** Simulate the subprocess dying on its own, as the real client reports it. */+ die(message = "The ACP agent exited unexpectedly (SIGKILL)."): void {+ this.disposed = true;+ this.onExit?.(new Error(message));+ }++ /** Forget the recorded requests, so a test spanning several turns asserts on one. */+ clearRequests(): void {+ this.requests = [];+ }+/** Fire a session/update notification as the agent would. */update(update: Record<string, unknown>, sessionId = "sess-1"): void {this.onNotification("session/update", { sessionId, update });@@ -120,6 +138,7 @@ class FakeAcpError extends Error {vi.mock("./acp_client.js", () => ({ AcpClient: FakeAcpClient, AcpError: FakeAcpError }));const { buildPromptBlocks, createUpdateCollector, denyPermission } = await import("./acp_agent.js");+const { IDLE_TIMEOUT_MS } = await import("./acp_client_pool.js");const { buildCopilotModelList, CopilotAgentProvider, resetModelCatalogCacheForTests } = await import("./copilot_agent.js");const decidePermission = (request: Parameters<typeof denyPermission>[0]) => denyPermission(request, "Copilot Agent provider");@@ -309,7 +328,8 @@ describe("CopilotAgentProvider.chatChunks", () => {AUTO_USAGE,{ type: "done" }]);- expect(FakeAcpClient.current?.disposed).toBe(true);+ // The agent process stays running for the next turn.+ expect(FakeAcpClient.current?.disposed).toBe(false);});it("wires the loopback MCP server into session/new when note tools are enabled", async () => {@@ -406,7 +426,8 @@ describe("CopilotAgentProvider.chatChunks", () => {const chunks = await collect(provider.chatChunks([userMessage("hi")], {}));expect(chunks).toEqual([{ type: "error", error: expect.stringContaining("copilot login") }]);- expect(FakeAcpClient.current?.disposed).toBe(true);+ // A failed session leaves the process running, so the turn after `copilot login` needs no respawn.+ expect(FakeAcpClient.current?.disposed).toBe(false);});it("rejects a transcript whose last message is not from the user", async () => {@@ -455,16 +476,18 @@ describe("CopilotAgentProvider.chatChunks", () => {expect(chunks).toEqual([{ type: "text", content: "partial" }, AUTO_USAGE, { type: "done" }]);expect(FakeAcpClient.current?.notifications).toContainEqual({ method: "session/cancel", params: { sessionId: "sess-1" } });- expect(FakeAcpClient.current?.disposed).toBe(true);+ // Other chats share the process, so cancelling one turn leaves it running.+ expect(FakeAcpClient.current?.disposed).toBe(false);// 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.current?.clearRequests();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);+ expect(FakeAcpClient.current?.requests.map(r => r.method)).toEqual(["session/new", "session/prompt"]);});it("flattens both wrapped and direct tool-result content blocks", async () => {@@ -516,7 +539,7 @@ describe("CopilotAgentProvider.chatChunks", () => {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 () => {+ it("prompts a session its process still holds, 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" } });@@ -524,17 +547,16 @@ describe("CopilotAgentProvider.chatChunks", () => {};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.+ // Same transcript, and the pooled process still holds the session: the+ // turn is a bare session/prompt, without instructions or history replay.+ FakeAcpClient.current?.clearRequests();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(FakeAcpClient.current?.requests.map(r => r.method)).toEqual(["session/prompt"]);expect(resumed).toEqual([AUTO_USAGE, { type: "done" }]);const prompt = FakeAcpClient.current?.requests.find(r => r.method === "session/prompt");const blocks = (prompt?.params as { prompt: { type: string; text: string }[] }).prompt;@@ -542,6 +564,7 @@ describe("CopilotAgentProvider.chatChunks", () => {// An edited history no longer hashes to the mapped session, so the next// turn must reseed rather than resume.+ FakeAcpClient.current?.clearRequests();await collect(provider.chatChunks([userMessage("rewritten"), assistantMessage("answer"), userMessage("more")],{ chatNoteId: "chat-resume" }@@ -550,10 +573,37 @@ describe("CopilotAgentProvider.chatChunks", () => {expect(FakeAcpClient.current?.requests.some(r => r.method === "session/new")).toBe(true);});+ it("loads a mapped session into a new process, dropping the replay", 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-reload" }));++ // The session exists only in the process that created it.+ FakeAcpClient.current?.die();+ FakeAcpClient.promptScript = async () => ({ stopReason: "end_turn" });+ const resumed = await collect(provider.chatChunks(+ [userMessage("hi"), assistantMessage("answer"), userMessage("more")],+ { chatNoteId: "chat-reload" }+ ));++ expect(FakeAcpClient.current?.requests.map(r => r.method)).toEqual(["initialize", "session/load", "session/prompt"]);+ expect(FakeAcpClient.current?.requests.find(r => r.method === "session/load")?.params)+ .toMatchObject({ sessionId: "sess-1", cwd: AGENT_CWD });+ // The fake load replays "REPLAY", which must not reach the chat.+ expect(resumed).toEqual([AUTO_USAGE, { 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");+ });+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.current?.die();FakeAcpClient.sessionLoadError = new Error("unknown session");FakeAcpClient.newSessionId = "sess-2";const chunks = await collect(provider.chatChunks(@@ -660,11 +710,115 @@ describe("CopilotAgentProvider.chatChunks", () => {}const followUp = [userMessage("hi"), assistantMessage(""), userMessage("more")];+ FakeAcpClient.current?.clearRequests();await collect(provider.chatChunks(followUp, { chatNoteId: "lru-0" }));- expect(FakeAcpClient.current?.requests.some(r => r.method === "session/load")).toBe(false);+ expect(FakeAcpClient.current?.requests.map(r => r.method)).toEqual(["session/new", "session/prompt"]);+ FakeAcpClient.current?.clearRequests();await collect(provider.chatChunks(followUp, { chatNoteId: "lru-200" }));- expect(FakeAcpClient.current?.requests.some(r => r.method === "session/load")).toBe(true);+ expect(FakeAcpClient.current?.requests.map(r => r.method)).toEqual(["session/prompt"]);+ });+});++describe("CopilotAgentProvider keep-alive", () => {+ beforeEach(resetFakes);++ it("reuses one agent process across turns, chats and titles, starting it once", async () => {+ const startSpy = vi.spyOn(FakeAcpClient, "start").mockClear();+ const provider = new CopilotAgentProvider();++ await collect(provider.chatChunks([userMessage("hi")], { chatNoteId: "chat-a" }));+ const first = FakeAcpClient.current;+ FakeAcpClient.newSessionId = "sess-b";+ await collect(provider.chatChunks([userMessage("hi")], { chatNoteId: "chat-b" }));+ await provider.generateTitle("hi");++ expect(FakeAcpClient.current).toBe(first);+ expect(startSpy).toHaveBeenCalledTimes(1);+ const methods = FakeAcpClient.current?.requests.map(r => r.method) ?? [];+ expect(methods.filter(m => m === "initialize")).toHaveLength(1);+ expect(methods.filter(m => m === "session/new")).toHaveLength(3);+ startSpy.mockRestore();+ });++ it("shares a single spawn between turns that start concurrently", async () => {+ const startSpy = vi.spyOn(FakeAcpClient, "start").mockClear();+ FakeAcpClient.promptScript = async () => {+ await new Promise(resolve => setTimeout(resolve, 5));+ return { stopReason: "end_turn" };+ };+ const provider = new CopilotAgentProvider();++ await Promise.all([+ collect(provider.chatChunks([userMessage("one")], { chatNoteId: "chat-1" })),+ collect(provider.chatChunks([userMessage("two")], { chatNoteId: "chat-2" }))+ ]);++ expect(startSpy).toHaveBeenCalledTimes(1);+ startSpy.mockRestore();+ });++ it("keeps each turn's updates to its own session", async () => {+ FakeAcpClient.promptScript = async client => {+ client.update({ sessionUpdate: "agent_message_chunk", content: { type: "text", text: "mine" } }, "sess-1");+ client.update({ sessionUpdate: "agent_message_chunk", content: { type: "text", text: "theirs" } }, "sess-other");+ client.onNotification("session/update", {});+ return { stopReason: "end_turn" };+ };++ const chunks = await collect(new CopilotAgentProvider().chatChunks([userMessage("hi")], {}));++ expect(chunks).toEqual([{ type: "text", content: "mine" }, AUTO_USAGE, { type: "done" }]);+ });++ it("starts a replacement process after the pooled one dies", async () => {+ const provider = new CopilotAgentProvider();+ await collect(provider.chatChunks([userMessage("hi")], {}));++ const dead = FakeAcpClient.current;+ dead?.die();+ const chunks = await collect(provider.chatChunks([userMessage("hi again")], {}));++ expect(FakeAcpClient.current).not.toBe(dead);+ expect(FakeAcpClient.current?.requests.map(r => r.method)).toEqual(["initialize", "session/new", "session/prompt"]);+ expect(chunks).toEqual([AUTO_USAGE, { type: "done" }]);+ expect(infoLogMock).toHaveBeenCalledWith(expect.stringContaining("agent process #1 ended"));+ });++ it("starts a new session when the chat's note access changes", async () => {+ const provider = new CopilotAgentProvider();+ await collect(provider.chatChunks([userMessage("hi")], { chatNoteId: "chat-tools", enableNoteTools: true }));++ FakeAcpClient.current?.clearRequests();+ FakeAcpClient.newSessionId = "sess-2";+ await collect(provider.chatChunks(+ [userMessage("hi"), assistantMessage(""), userMessage("more")],+ { chatNoteId: "chat-tools", enableNoteTools: false }+ ));++ expect(FakeAcpClient.current?.requests.find(r => r.method === "session/new")?.params).toMatchObject({ mcpServers: [] });+ });++ it("stops the process once no turn has used it for the idle timeout", async () => {+ vi.useFakeTimers();+ try {+ const provider = new CopilotAgentProvider();+ await collect(provider.chatChunks([userMessage("hi")], {}));+ const client = FakeAcpClient.current;++ vi.advanceTimersByTime(IDLE_TIMEOUT_MS - 1);+ expect(client?.disposed).toBe(false);+ // A turn in between restarts the wait.+ await collect(provider.chatChunks([userMessage("hi")], {}));+ vi.advanceTimersByTime(IDLE_TIMEOUT_MS - 1);+ expect(client?.disposed).toBe(false);++ vi.advanceTimersByTime(1);+ expect(client?.disposed).toBe(true);+ expect(infoLogMock).toHaveBeenCalledWith(expect.stringContaining("reaping the idle agent process"));+ } finally {+ vi.useRealTimers();+ }});});@@ -689,7 +843,7 @@ describe("CopilotAgentProvider.generateTitle", () => {.toMatchObject({ modelId: "gpt-5-mini" });expect(FakeAcpClient.current?.requests.find(r => r.method === "session/new")?.params).toMatchObject({ mcpServers: [] });- expect(FakeAcpClient.current?.disposed).toBe(true);+ expect(FakeAcpClient.current?.disposed).toBe(false);});it("still produces a title when the cheap model cannot be selected", async () => {@@ -707,6 +861,12 @@ describe("CopilotAgentProvider.generateTitle", () => {expect(await new CopilotAgentProvider().generateTitle("hi")).toBe("");expect(errorLogMock).toHaveBeenCalledWith(expect.stringContaining("Failed to start the GitHub Copilot CLI"));+ expect(FakeAcpClient.current?.disposed).toBe(false);++ // A process that fails its handshake is not kept.+ resetModelCatalogCacheForTests();+ FakeAcpClient.initializeError = new Error("handshake rejected");+ expect(await new CopilotAgentProvider().generateTitle("hi")).toBe("");expect(FakeAcpClient.current?.disposed).toBe(true);});});@@ -762,15 +922,12 @@ describe("createUpdateCollector", () => {return { collector, chunks };}- it("ignores other methods, muted replay, empty updates, and stray sessions", () => {+ it("ignores other methods, 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");