From f7e2ab4076879fb00af2b1c464cd7c04ef328c5e Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Sun, 22 Nov 2026 04:01:42 +0700 Subject: [PATCH] Keep the full history when reopening a long Antigravity agent after a restart (#10428) * fix(acp): keep the whole history when an agent streams it after session/load Reopening a long Antigravity agent after a daemon restart lost the end of its timeline. When the client reads slowly, agy answers session/load part-way through the history and keeps streaming the rest, with no end marker. The replay window closed after a fixed five quiet periods (1 s), and every history update processed after that was discarded as stale. The window now closes only once a quiet period passes without a history update. Command, configuration, mode and usage updates no longer count as activity, so they cannot hold the session open. When the quiet period expires, the loop reads pending input once before the silence is trusted, because a stalled event loop reaches the timer with history still unread in the pipe. The wait has no upper bound: any bound is another way to truncate, and the agent goes silent once its history is sent. * fix(acp): stop waiting for history replay when the connection closes With the replay wait no longer capped, closing the provider connection while a session was still replaying waited for the whole history, so a daemon stop during a long reopen could run past its deadline. The connection marks itself closed and then awaits in-flight opens, but the replay wait only checked the runtime's own closing flag. The wait now also ends when the connection closes. * fix(acp): only extend replay on history updates and fail open on mid-replay crash * fix(server): bound shutdown flush so provider shutdown cancels in-flight reopens * fix(acp): keep load replay open while a multi-read wire record is in flight --- .../src/server/acp-internal/connection.ts | 123 +++++- packages/plugin/src/server/acp.test.ts | 372 ++++++++++++++++++ packages/plugin/src/server/acp.ts | 5 +- .../server/src/server/bootstrap.smoke.test.ts | 185 +++++++++ packages/server/src/server/bootstrap.ts | 20 +- public-docs/plugins/providers.md | 5 +- 6 files changed, 685 insertions(+), 25 deletions(-) diff --git a/packages/plugin/src/server/acp-internal/connection.ts b/packages/plugin/src/server/acp-internal/connection.ts index 2b5f2c362d..8de1053eed 100644 --- a/packages/plugin/src/server/acp-internal/connection.ts +++ b/packages/plugin/src/server/acp-internal/connection.ts @@ -334,7 +334,7 @@ async function openSession( onRetired: () => retireSession(state, input.sessionId), }); try { - const capabilities = await runtime.open(input, state.capabilities); + const capabilities = await runtime.open(input, state.capabilities, state.isClosed); if (state.isClosed()) { await runtime.closeSession(); return; @@ -454,12 +454,14 @@ class AcpRuntime { * Once ready, suppress late replay rows until the first prompt. */ private replayWindow: "replay" | "skip" | null = null; - private lastLoadUpdateAt = 0; + private lastLoadHistoryAt = 0; + private lastPartialWireAt = 0; private closing = false; private closePromise: Promise | null = null; private deferredRetirement: Promise | null = null; private deferredFinalized = false; private processFailed = false; + private processFailureMessage: string | null = null; private configTransaction = false; private stagedTransformerConfig: ProviderConfigState | null = null; private readonly closeConnector: (options?: { @@ -483,6 +485,7 @@ class AcpRuntime { timeoutMs?: number; }) => Promise = async () => {}; let whenConnectorClosed: () => Promise | null = () => null; + let onPartialWireRead: (() => void) | null = null; if (options.options.command) { // COMPAT(pluginProviderLaunch): added in v0.10.0, remove after 2027-03-29 once plugin host floor >= v0.10.0. // Standalone callers and older hosts do not send a daemon-resolved launch. @@ -499,7 +502,10 @@ class AcpRuntime { spawnFailure = new Promise((_resolve, reject) => child!.once("error", reject)); child.stderr.on("data", () => undefined); const output = Writable.toWeb(child.stdin) as unknown as Parameters[0]; - const input = Readable.toWeb(child.stdout) as unknown as Parameters[1]; + const rawInput = Readable.toWeb(child.stdout) as unknown as ReadableStream; + const input = observePartialWireReads(rawInput, () => onPartialWireRead?.()) as Parameters< + typeof ndJsonStream + >[1]; stream = ndJsonStream(output, input); } else { const owned = ownConnectorStream(await options.options.connector()); @@ -508,6 +514,7 @@ class AcpRuntime { whenConnectorClosed = owned.whenClosed; } const runtime = new AcpRuntime(stream, child, closeConnector, whenConnectorClosed, options); + onPartialWireRead = () => runtime.notePartialWireRead(); try { const initialize = withTimeout( runtime.call( @@ -562,6 +569,7 @@ class AcpRuntime { child?.on("error", (error) => { const message = describeError(error); this.processFailed = true; + this.processFailureMessage = message; this.settlePendingWork(message); if (this.closing || !this.nativeSessionId) return; this.emit({ @@ -574,6 +582,7 @@ class AcpRuntime { if (this.closing || this.processFailed || !this.nativeSessionId) return; const message = `ACP process exited (${signal ?? code ?? "unknown"})`; this.processFailed = true; + this.processFailureMessage = message; this.settlePendingWork(message); this.emit({ type: "session.runtime_failed", @@ -586,6 +595,7 @@ class AcpRuntime { async open( input: Extract, connectionCapabilities: readonly ProviderCapability[], + isConnectionClosed: () => boolean, ): Promise { const mcpServers = toAcpMcpServers(input.config); this.mcpServerNames = mcpServers.map((server) => server.name); @@ -656,15 +666,22 @@ class AcpRuntime { cwd: input.config.cwd, }); this.emitConfig(); + await this.finishSessionOpen(isConnectionClosed); + return sessionCapabilities; + } + + private async finishSessionOpen(isConnectionClosed: () => boolean): Promise { if (this.options.options.acpOptions?.waitForInitialCommands) { await this.waitForInitialCommands(); } const quietPeriod = this.options.options.acpOptions?.loadReplayQuietPeriodMs; if (this.replayWindow && quietPeriod && quietPeriod > 0) { - await this.waitForLoadReplay(quietPeriod); + await this.waitForLoadReplay(quietPeriod, isConnectionClosed); this.replayWindow = "skip"; } - return sessionCapabilities; + if (this.processFailed && !isConnectionClosed()) { + throw new Error(this.processFailureMessage ?? "ACP process exited during session open"); + } } async discover(cwd?: string): Promise { @@ -1282,16 +1299,12 @@ class AcpRuntime { private sessionUpdate(notification: SessionNotification, wireSeq: number): void { if (notification.sessionId !== this.nativeSessionId) return; - if (this.replayWindow) this.lastLoadUpdateAt = performance.now(); + if (this.replayWindow && isReplayHistoryUpdate(notification.update)) { + this.lastLoadHistoryAt = performance.now(); + } if (this.replayWindow === "skip") { - const update = notification.update; - if ( - update.sessionUpdate === "available_commands_update" || - update.sessionUpdate === "config_option_update" || - update.sessionUpdate === "current_mode_update" || - update.sessionUpdate === "usage_update" - ) { - this.reduceStateUpdate(update, wireSeq); + if (isSessionStateUpdate(notification.update)) { + this.reduceStateUpdate(notification.update, wireSeq); } return; } @@ -1634,6 +1647,7 @@ class AcpRuntime { if (this.closing || this.processFailed) return; const message = "ACP transport closed unexpectedly"; this.processFailed = true; + this.processFailureMessage = message; this.settlePendingWork(message); if (!this.nativeSessionId) return; this.emit({ @@ -1945,19 +1959,86 @@ class AcpRuntime { }); } - private async waitForLoadReplay(quietPeriod: number): Promise { + private notePartialWireRead(): void { + if (this.replayWindow) this.lastPartialWireAt = performance.now(); + } + + // An agent that streams history after its session/load response sends no end marker, + // so the history ends once a quiet period passes without a history update. + private async waitForLoadReplay( + quietPeriod: number, + isConnectionClosed: () => boolean, + ): Promise { const start = performance.now(); - const deadline = start + 5 * quietPeriod; - while (!this.closing && !this.processFailed) { - const idleAt = Math.max(start, this.lastLoadUpdateAt) + quietPeriod; - const remaining = Math.min(deadline, idleAt) - performance.now(); - if (remaining <= 0) return; - await new Promise((resolve) => setTimeout(resolve, remaining)); + while (!this.closing && !this.processFailed && !isConnectionClosed()) { + const lastActivityAt = Math.max(start, this.lastLoadHistoryAt, this.lastPartialWireAt); + const remaining = lastActivityAt + quietPeriod - performance.now(); + // A stalled event loop reaches the quiet period with history still unread in the pipe. + // setImmediate lets the loop read pending input once before the silence is trusted. + await new Promise((resolve) => { + if (remaining > 0) setTimeout(resolve, remaining); + else setImmediate(resolve); + }); await this.notificationLane; + if ( + remaining <= 0 && + Math.max(start, this.lastLoadHistoryAt, this.lastPartialWireAt) === lastActivityAt + ) { + return; + } } } } +function observePartialWireReads( + input: ReadableStream, + onPartialRead: () => void, +): ReadableStream { + let incompleteLine = false; + return input.pipeThrough( + new TransformStream({ + transform(chunk, controller) { + const wasIncomplete = incompleteLine; + incompleteLine = hasTrailingIncompleteLine(chunk, incompleteLine); + if (wasIncomplete || incompleteLine) onPartialRead(); + controller.enqueue(chunk); + }, + }), + ); +} + +function hasTrailingIncompleteLine(chunk: Uint8Array, incompleteLine: boolean): boolean { + const newline = chunk.lastIndexOf(0x0a); + const start = newline === -1 ? 0 : newline + 1; + if (newline !== -1) incompleteLine = false; + for (let index = start; index < chunk.length; index += 1) { + const byte = chunk[index]; + if (byte !== 0x20 && byte !== 0x09 && byte !== 0x0d) return true; + } + return incompleteLine; +} + +function isReplayHistoryUpdate(update: SessionUpdate): boolean { + return ( + update.sessionUpdate === "user_message_chunk" || + update.sessionUpdate === "agent_message_chunk" || + update.sessionUpdate === "agent_thought_chunk" || + update.sessionUpdate === "tool_call" || + update.sessionUpdate === "tool_call_update" || + update.sessionUpdate === "plan" || + update.sessionUpdate === "compaction_update" + ); +} + +function isSessionStateUpdate(update: SessionUpdate): boolean { + return ( + update.sessionUpdate === "available_commands_update" || + update.sessionUpdate === "config_option_update" || + update.sessionUpdate === "current_mode_update" || + update.sessionUpdate === "usage_update" + ); +} + function routeIncomingMessages( stream: Stream, receiveVendor: (method: string, params: unknown) => void, diff --git a/packages/plugin/src/server/acp.test.ts b/packages/plugin/src/server/acp.test.ts index 05f9a26481..a7e33e2d32 100644 --- a/packages/plugin/src/server/acp.test.ts +++ b/packages/plugin/src/server/acp.test.ts @@ -303,6 +303,378 @@ describe("runAcpProvider", () => { }, ); + it("keeps history that streams after session/load for longer than five quiet periods", async () => { + const sessionId = "connector-session"; + const historyLength = 40; + let stream: ReturnType | undefined; + const { connector } = connectorHarness({ + capabilities: { loadSession: true }, + handleRequest(runtime, request) { + if (request.method !== "session/load") return false; + runtime.respond(request, { configOptions: [] }); + let sent = 0; + stream = setInterval(() => { + runtime.notify("session/update", { + sessionId, + update: { + sessionUpdate: "agent_message_chunk", + messageId: `answer-${sent}`, + content: { type: "text", text: `previous answer ${sent}` }, + }, + }); + sent += 1; + if (sent === historyLength) clearInterval(stream); + }, 20); + return true; + }, + }); + const connection = await runAcpProvider({ + id: "load", + label: "Load", + connector, + acpOptions: { loadReplayQuietPeriodMs: 100 }, + }).connect({ versions: [1], capabilities: ["prompt.message", "session.persistence"] }); + const events: ProviderEvent[] = []; + connection.onEvent((event) => events.push(event)); + try { + await connection.send({ + ...openInput(), + history: "replay", + persistence: { version: 1, data: { sessionId } }, + }); + await waitForEvent(events, (event) => event.type === "session.ready"); + expect(events.filter((event) => event.type === "timeline.item")).toHaveLength(historyLength); + } finally { + clearInterval(stream); + await connection.close(); + } + }); + + it("closes without waiting for history that is still streaming after session/load", async () => { + const sessionId = "connector-session"; + let stream: ReturnType | undefined; + const { connector } = connectorHarness({ + capabilities: { loadSession: true }, + handleRequest(runtime, request) { + if (request.method !== "session/load") return false; + runtime.respond(request, { configOptions: [] }); + stream = setInterval(() => { + if (runtime.readsCanceled) return; + runtime.notify("session/update", { + sessionId, + update: { + sessionUpdate: "agent_message_chunk", + content: { type: "text", text: "previous answer" }, + }, + }); + }, 20); + return true; + }, + }); + const connection = await runAcpProvider({ + id: "load", + label: "Load", + connector, + acpOptions: { loadReplayQuietPeriodMs: 100 }, + }).connect({ versions: [1], capabilities: ["prompt.message", "session.persistence"] }); + const events: ProviderEvent[] = []; + connection.onEvent((event) => events.push(event)); + try { + await connection.send({ + ...openInput(), + history: "replay", + persistence: { version: 1, data: { sessionId } }, + }); + await waitForEvent(events, (event) => event.type === "timeline.item"); + const outcome = await Promise.race([ + connection.close().then(() => "closed"), + new Promise((resolve) => setTimeout(() => resolve("still replaying"), 1_000)), + ]); + expect(outcome).toBe("closed"); + } finally { + clearInterval(stream); + } + }); + + it("keeps history left unread while the event loop stalled past the quiet period", async () => { + const sessionId = "connector-session"; + const notifyAnswer = (runtime: ConnectorInstance, text: string) => + runtime.notify("session/update", { + sessionId, + update: { + sessionUpdate: "agent_message_chunk", + messageId: text, + content: { type: "text", text }, + }, + }); + const { connector } = connectorHarness({ + capabilities: { loadSession: true }, + handleRequest(runtime, request) { + if (request.method !== "session/load") return false; + runtime.respond(request, { configOptions: [] }); + notifyAnswer(runtime, "read before the stall"); + // Stall after the timers phase, so the overdue quiet timer runs before the next I/O poll. + const stall = () => { + // Like bytes waiting in the agent's pipe: readable only once the loop polls I/O again. + setImmediate(() => notifyAnswer(runtime, "unread during the stall")); + const stalledUntil = performance.now() + 250; + while (performance.now() < stalledUntil); + }; + setTimeout(() => setImmediate(stall), 30); + return true; + }, + }); + const connection = await runAcpProvider({ + id: "load", + label: "Load", + connector, + acpOptions: { loadReplayQuietPeriodMs: 100 }, + }).connect({ versions: [1], capabilities: ["prompt.message", "session.persistence"] }); + const events: ProviderEvent[] = []; + connection.onEvent((event) => events.push(event)); + try { + await connection.send({ + ...openInput(), + history: "replay", + persistence: { version: 1, data: { sessionId } }, + }); + await waitForEvent(events, (event) => event.type === "session.ready"); + expect( + events.filter((event) => event.type === "timeline.item").map((event) => event.item), + ).toEqual([ + expect.objectContaining({ text: "read before the stall" }), + expect.objectContaining({ text: "unread during the stall" }), + ]); + } finally { + await connection.close(); + } + }); + + it("does not extend the load replay wait for session_info_update notifications", async () => { + const sessionId = "connector-session"; + let stream: ReturnType | undefined; + const { connector } = connectorHarness({ + capabilities: { loadSession: true }, + handleRequest(runtime, request) { + if (request.method !== "session/load") return false; + runtime.respond(request, { configOptions: [] }); + runtime.notify("session/update", { + sessionId, + update: { + sessionUpdate: "agent_message_chunk", + messageId: "answer-1", + content: { type: "text", text: "previous answer" }, + }, + }); + stream = setInterval(() => { + if (runtime.readsCanceled) return; + runtime.notify("session/update", { + sessionId, + update: { + sessionUpdate: "session_info_update", + title: "Updated title", + }, + }); + }, 20); + return true; + }, + }); + const connection = await runAcpProvider({ + id: "load", + label: "Load", + connector, + acpOptions: { loadReplayQuietPeriodMs: 100 }, + }).connect({ versions: [1], capabilities: ["prompt.message", "session.persistence"] }); + const events: ProviderEvent[] = []; + connection.onEvent((event) => events.push(event)); + try { + await connection.send({ + ...openInput(), + history: "replay", + persistence: { version: 1, data: { sessionId } }, + }); + const outcome = await Promise.race([ + waitForEvent(events, (event) => event.type === "session.ready").then(() => "ready"), + new Promise((resolve) => setTimeout(() => resolve("still waiting"), 1_000)), + ]); + expect(outcome).toBe("ready"); + expect(events.filter((event) => event.type === "timeline.item")).toHaveLength(1); + } finally { + clearInterval(stream); + await connection.close(); + } + }); + + it("fails session open without emitting session.ready or leaking the session when the ACP process crashes mid-replay", async () => { + const dir = await mkdtemp(path.join(tmpdir(), "paseo-acp-crash-replay-")); + const script = path.join(dir, "crash-replay-agent.mjs"); + await writeFile( + script, + ` + import { createInterface } from "node:readline"; + const send = (msg) => process.stdout.write(JSON.stringify({ jsonrpc: "2.0", ...msg }) + "\\n"); + createInterface({ input: process.stdin }).on("line", (line) => { + if (!line.trim()) return; + const msg = JSON.parse(line); + if (msg.method === "initialize") { + send({ id: msg.id, result: { protocolVersion: 1, agentCapabilities: { loadSession: true } } }); + } else if (msg.method === "session/load") { + const sid = msg.params.sessionId; + send({ id: msg.id, result: { configOptions: [] } }); + send({ + method: "session/update", + params: { + sessionId: sid, + update: { + sessionUpdate: "agent_message_chunk", + messageId: "m-1", + content: { type: "text", text: "partial history" }, + }, + }, + }); + if (sid === "crash-session") { + setTimeout(() => process.exit(1), 20); + } + } else if (msg.method === "session/close") { + send({ id: msg.id, result: {} }); + } + }); + `, + ); + const connection = await runAcpProvider({ + id: "crash-replay", + label: "Crash Replay", + command: [process.execPath, script], + acpOptions: { loadReplayQuietPeriodMs: 100 }, + }).connect({ versions: [1], capabilities: ["prompt.message", "session.persistence"] }); + const events: ProviderEvent[] = []; + connection.onEvent((event) => events.push(event)); + try { + await connection.send({ + ...openInput(), + requestId: "req-crash", + sessionId: "session-1", + history: "replay", + persistence: { version: 1, data: { sessionId: "crash-session" } }, + }); + await waitForEvent( + events, + (event) => event.type === "request.failed" && event.requestId === "req-crash", + ); + expect(events.some((event) => event.type === "session.ready")).toBe(false); + + // The failed open must not leave a dead session registered under "session-1". + await connection.send({ + ...openInput(), + requestId: "req-retry", + sessionId: "session-1", + history: "replay", + persistence: { version: 1, data: { sessionId: "healthy-session" } }, + }); + await waitForEvent( + events, + (event) => event.type === "session.ready" && event.requestId === "req-retry", + ); + } finally { + await connection.close(); + await rm(dir, { recursive: true, force: true }); + } + }); + + it("keeps a multi-read tool result started during an event-loop stall past the quiet period", async () => { + const dir = await mkdtemp(path.join(tmpdir(), "paseo-acp-large-stall-replay-")); + const script = path.join(dir, "large-stall-agent.mjs"); + const outputBytes = 256 * 1024; + await writeFile( + script, + ` + import { createInterface } from "node:readline"; + const send = (msg) => process.stdout.write(JSON.stringify({ jsonrpc: "2.0", ...msg }) + "\\n"); + createInterface({ input: process.stdin }).on("line", (line) => { + if (!line.trim()) return; + const msg = JSON.parse(line); + if (msg.method === "initialize") { + send({ id: msg.id, result: { protocolVersion: 1, agentCapabilities: { loadSession: true } } }); + } else if (msg.method === "session/load") { + const sid = msg.params.sessionId; + send({ + method: "session/update", + params: { + sessionId: sid, + update: { + sessionUpdate: "agent_message_chunk", + messageId: "m-before", + content: { type: "text", text: "before the stall" }, + }, + }, + }); + send({ id: msg.id, result: { configOptions: [] } }); + setTimeout(() => { + send({ + method: "session/update", + params: { + sessionId: sid, + update: { + sessionUpdate: "tool_call", + toolCallId: "shell-large", + name: "run_command", + title: "Large output", + kind: "execute", + status: "completed", + rawInput: { CommandLine: "cat large.log" }, + rawOutput: { output: "x".repeat(${outputBytes}), exit_code: 0 }, + }, + }, + }); + }, 50); + } else if (msg.method === "session/close") { + send({ id: msg.id, result: {} }); + } + }); + `, + ); + const connection = await runAcpProvider({ + id: "large-stall", + label: "Large Stall", + command: [process.execPath, script], + acpOptions: { loadReplayQuietPeriodMs: 200 }, + }).connect({ versions: [1], capabilities: ["prompt.message", "session.persistence"] }); + const events: ProviderEvent[] = []; + let stalled = false; + const stallEventLoop = () => { + const until = performance.now() + 350; + while (performance.now() < until); + }; + const scheduleStall = () => setImmediate(stallEventLoop); + connection.onEvent((event) => { + events.push(event); + if (!stalled && event.type === "session.config") { + stalled = true; + // Stall after the timers phase so the overdue quiet timer runs before the next I/O poll; + // the 256 KiB tool result fills the pipe during the stall and spans multiple stdout reads. + setTimeout(scheduleStall, 20); + } + }); + try { + await connection.send({ + ...openInput(), + history: "replay", + persistence: { version: 1, data: { sessionId: "large-session" } }, + }); + await waitForEvent(events, (event) => event.type === "session.ready"); + const items = events + .filter((event) => event.type === "timeline.item") + .map((event) => event.item); + expect(items).toEqual([ + expect.objectContaining({ type: "assistant_message", text: "before the stall" }), + expect.objectContaining({ type: "tool_call", callId: "shell-large", status: "completed" }), + ]); + } finally { + await connection.close(); + await rm(dir, { recursive: true, force: true }); + } + }); + it("auto-accepts ordinary permissions only in the unattended mode and refuses to switch while busy", async () => { const modeConfig = { id: "mode", diff --git a/packages/plugin/src/server/acp.ts b/packages/plugin/src/server/acp.ts index 4cd4e5114f..68404471ce 100644 --- a/packages/plugin/src/server/acp.ts +++ b/packages/plugin/src/server/acp.ts @@ -51,7 +51,10 @@ export interface AcpOptions { workspaceOnlyCatalog?: boolean; waitForInitialCommands?: boolean; initialCommandsTimeoutMs?: number; - /** Allow delayed session/load updates before publishing the session as ready. */ + /** + * For an agent that streams history after its session/load response: publish the session + * as ready once this long passes without a history update. + */ loadReplayQuietPeriodMs?: number; /** * Keep a turn open after `end_turn` while qualifying tool calls are still running, diff --git a/packages/server/src/server/bootstrap.smoke.test.ts b/packages/server/src/server/bootstrap.smoke.test.ts index d7d41916ca..239ed28b01 100644 --- a/packages/server/src/server/bootstrap.smoke.test.ts +++ b/packages/server/src/server/bootstrap.smoke.test.ts @@ -1295,3 +1295,188 @@ test.each(["reject", "stall"] as const)( }, 30_000, ); + +test("shutdown finishes promptly when a persisted ACP plugin reopen is still streaming history replay", async () => { + const root = await mkdtemp(path.join(os.tmpdir(), "paseo-shutdown-acp-replay-")); + const pluginDirectory = path.join(root, "plugin"); + const agentScriptPath = path.join(root, "streaming-acp-agent.mjs"); + const replayStartedPath = path.join(root, "replay-started.pid"); + const workspace = path.join(root, "workspace"); + await mkdir(pluginDirectory, { recursive: true }); + await mkdir(workspace, { recursive: true }); + const pluginId = "streaming-replay-plugin"; + const providerId = "streaming-replay-acp"; + + await writeFile( + agentScriptPath, + ` +import { writeFileSync } from "node:fs"; +import { createInterface } from "node:readline"; +const send = (msg) => process.stdout.write(JSON.stringify({ jsonrpc: "2.0", ...msg }) + "\\n"); +let stream; +createInterface({ input: process.stdin }).on("line", (line) => { + if (!line.trim()) return; + const msg = JSON.parse(line); + if (msg.method === "initialize") { + send({ id: msg.id, result: { protocolVersion: 1, agentCapabilities: { loadSession: true } } }); + } else if (msg.method === "session/new") { + send({ id: msg.id, result: { sessionId: "new-session", configOptions: [] } }); + } else if (msg.method === "session/load") { + const sid = msg.params.sessionId; + send({ id: msg.id, result: { configOptions: [] } }); + writeFileSync(${JSON.stringify(replayStartedPath)}, String(process.pid)); + let count = 0; + stream = setInterval(() => { + count += 1; + send({ + method: "session/update", + params: { + sessionId: sid, + update: { + sessionUpdate: "agent_message_chunk", + messageId: "chunk-" + count, + content: { type: "text", text: "replayed message " + count }, + }, + }, + }); + }, 20); + } else if (msg.method === "session/close") { + clearInterval(stream); + send({ id: msg.id, result: {} }); + } +}); +process.on("SIGTERM", () => { + clearInterval(stream); + process.exit(0); +}); +`, + ); + await writeFile( + path.join(pluginDirectory, "paseo-plugin.json"), + JSON.stringify({ + id: pluginId, + requirements: { paseo: `>=${resolveDaemonVersion(import.meta.url)}` }, + }), + ); + await writeFile( + path.join(pluginDirectory, "index.server.ts"), + `import { runAcpProvider } from "@getpaseo/plugin/server/acp"; +import type { ProviderRegistration } from "@getpaseo/plugin/server/provider"; + +const provider: ProviderRegistration = runAcpProvider({ + id: ${JSON.stringify(providerId)}, + label: "Streaming replay ACP", + command: [${JSON.stringify(process.execPath)}, ${JSON.stringify(agentScriptPath)}], + acpOptions: { loadReplayQuietPeriodMs: 100 }, +}); + +export default function contribute(server: { registerProvider(p: ProviderRegistration): void }) { + server.registerProvider(provider); + return () => undefined; +} +`, + ); + + const paseoHomeRoot = path.join(root, "home"); + const paseoHome = path.join(paseoHomeRoot, ".paseo"); + const logger = pino({ level: "silent" }); + const storage = new AgentStorage(path.join(paseoHome, "agents"), logger); + const agentId = randomUUID(); + const persistence = { version: 1, data: { sessionId: "persisted-acp-session" } }; + await storage.upsert({ + id: agentId, + workspaceId: "workspace-1", + provider: providerId, + cwd: workspace, + createdAt: "2025-01-01T00:00:00.000Z", + updatedAt: "2025-01-02T00:00:00.000Z", + lastActivityAt: "2025-01-02T00:00:00.000Z", + lastStatus: "closed", + title: "Streaming replay agent", + labels: {}, + metadata: {}, + persistence: { + provider: providerId, + sessionId: `plugin:${JSON.stringify(persistence)}`, + metadata: { pluginProviderPersistence: persistence }, + }, + config: {}, + requiresAttention: false, + attentionReason: null, + attentionTimestamp: null, + archivedAt: null, + }); + + const handle = await createTestPaseoDaemon({ + paseoHomeRoot, + staticDir: path.join(root, "static"), + pluginsEnabled: true, + plugins: { + [pluginId]: { source: "directory", path: pluginDirectory, enabled: true }, + }, + }); + const client = new DaemonClient({ url: `ws://127.0.0.1:${handle.port}/ws` }); + let stopped = false; + let childPid: number | null = null; + try { + await client.connect(); + const timelineRequest = client + .fetchAgentTimeline(agentId, { direction: "tail", limit: 20 }) + .catch(() => "rejected"); + + await expect + .poll( + async () => { + try { + const raw = (await readFile(replayStartedPath, "utf8")).trim(); + const pid = Number(raw); + if (Number.isInteger(pid) && pid > 0) { + childPid = pid; + return pid; + } + return null; + } catch { + return null; + } + }, + { timeout: 10_000 }, + ) + .not.toBeNull(); + + const outcome = await Promise.race([ + handle.daemon.stop().then(() => { + stopped = true; + return "stopped"; + }), + new Promise((resolve) => setTimeout(() => resolve("timed_out"), 12_000)), + ]); + expect(outcome).toBe("stopped"); + await expect(timelineRequest).resolves.toBe("rejected"); + // The ACP child process must be terminated when provider shutdown cancels replay. + await expect + .poll( + () => { + if (!childPid) return false; + try { + process.kill(childPid, 0); + return true; + } catch { + return false; + } + }, + { timeout: 3_000 }, + ) + .toBe(false); + } finally { + await client.close().catch(() => undefined); + if (!stopped && childPid) { + try { + process.kill(childPid, "SIGKILL"); + } catch { + // already exited + } + } + if (!stopped) await handle.daemon.stop().catch(() => undefined); + await rm(root, { recursive: true, force: true }); + } +}, 30_000); diff --git a/packages/server/src/server/bootstrap.ts b/packages/server/src/server/bootstrap.ts index 5f4870b5f2..815774b0d4 100644 --- a/packages/server/src/server/bootstrap.ts +++ b/packages/server/src/server/bootstrap.ts @@ -2061,10 +2061,28 @@ export async function createPaseoDaemon( timeoutMs: AGENT_CLOSE_TIMEOUT_MS, label: "drain plugin lifecycle events", }).catch((error) => logger.warn({ err: error }, "Plugin lifecycle events did not finish")); - await agentManager.flushForShutdown().catch(() => undefined); + let shutdownFlushTimedOut = false; + await withTimeout({ + promise: agentManager.flushForShutdown(), + timeoutMs: AGENT_CLOSE_TIMEOUT_MS, + label: "flush agent shutdown tasks", + }).catch((error) => { + shutdownFlushTimedOut = true; + logger.warn({ err: error }, "Agent shutdown tasks did not finish before provider shutdown"); + }); detachAgentStoragePersistence(); await agentStorage.flush().catch(() => undefined); await agentProviderRuntime.shutdown(); + if (shutdownFlushTimedOut) { + await withTimeout({ + promise: agentManager.flushForShutdown(), + timeoutMs: AGENT_CLOSE_TIMEOUT_MS, + label: "flush agent shutdown tasks after provider shutdown", + }).catch((error) => + logger.warn({ err: error }, "Agent shutdown tasks did not finish after provider shutdown"), + ); + await agentStorage.flush().catch(() => undefined); + } await pluginRuntime.stopAllPlugins(); try { if (keepTerminals) { diff --git a/public-docs/plugins/providers.md b/public-docs/plugins/providers.md index de4c34cf1e..fca9d224ae 100644 --- a/public-docs/plugins/providers.md +++ b/public-docs/plugins/providers.md @@ -623,8 +623,9 @@ translated change to `apply(change)`. Applying a change this way uses the shared mapping and skips the transformers for that change. Set `acpOptions.loadReplayQuietPeriodMs` for an agent that streams history after its `session/load` -response. Paseo waits for that interval without session updates before it publishes the session as -ready. The wait is bounded at five times the interval. +response. Paseo publishes the session as ready once that interval passes without a history update. +Non-history state and metadata updates (such as commands, configuration, mode, usage, and session +info) do not extend the wait. Set `acpOptions.autoAcceptMode` to offer an unattended mode backed by a specific native mode. The adapter selects an unambiguous ACP `allow_once` action without opening a Paseo approval.