Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
fix(agent): give manual compaction its own deadline and a durable verdict (#795)
vastsa3f982b3b85ef
diff --git a/apps/desktop/electron/main/ipc/agent-ipc.ts b/apps/desktop/electron/main/ipc/agent-ipc.tsindex 809a24354..2da6385dd 100644--- a/apps/desktop/electron/main/ipc/agent-ipc.ts+++ b/apps/desktop/electron/main/ipc/agent-ipc.ts@@ -1,4 +1,4 @@-import { IPC, ErrorCodes, isGlobalPermissionMode, type AgentEventEnvelope, type AgentPromptRequest, type AgentSteerRequest, type UiMessage, type AgentQueuePushRequest, type AgentStopRequest, type AskToolResolution, type GlobalPermissionMode, type MessageUsage, type PlanExecutionFinishStatus, type PlanResolutionResult, type PlanResolveRequest, type PromptEnhancementRequest, type SessionSummarizeTitleRequest, canonicalThinkingLevel, type ThinkingLevel } from "@pi-desktop/shared";+import { IPC, ErrorCodes, compactionRecordId, isGlobalPermissionMode, isRpcTimeoutError, type AgentEventEnvelope, type AgentPromptRequest, type AgentSteerRequest, type UiMessage, type AgentQueuePushRequest, type AgentStopRequest, type AskToolResolution, type GlobalPermissionMode, type MessageUsage, type PlanExecutionFinishStatus, type PlanResolutionResult, type PlanResolveRequest, type PromptEnhancementRequest, type SessionSummarizeTitleRequest, canonicalThinkingLevel, type ThinkingLevel } from "@pi-desktop/shared";import type { FinishTurn } from "../runtime/plans";import { expandSlashInvocation, enhancePromptDraft, summarizeSessionTitle, visionFromModelConfig, type ComposerTemplate, type RuntimeProviderConfig } from "@pi-desktop/agent-runtime";import { OAUTH_AUTH_KIND, type VendorOAuth } from "../oauth";@@ -638,7 +638,26 @@ export function registerAgentIpc({settings,);sidecar.setProjectInstructionRoot(req.sessionId, launch.projectPath);- const result = await sidecar.call("agent.compact", launch.sidecarParams);+ // A lost reply is not the sidecar's verdict: the sidecar keeps summarizing+ // and persists the checkpoint through host-core, so the durable record+ // decides whether this manual compaction succeeded (issue #795).+ const startedWith = compactionRecordId(detail.session);+ let result: unknown;+ try {+ result = await sidecar.call("agent.compact", launch.sidecarParams);+ } catch (error) {+ if (!isRpcTimeoutError(error)) throw error;+ const settled = await host.call<{ session?: unknown }>("session.get", {+ id: req.sessionId,+ });+ const landed = compactionRecordId(settled.session);+ if (landed === startedWith) throw error;+ logger.app("session", "warn", "manual compaction outlived its transport deadline; the checkpoint landed", {+ sessionId: req.sessionId,+ data: { compactionId: landed },+ });+ return { accepted: true };+ }logger.app("session", "info", "context compacted manually", {sessionId: req.sessionId,data: { providerId: launch.providerId, modelId: launch.modelId },diff --git a/apps/desktop/test/plugin-timeout-budgets.test.mjs b/apps/desktop/test/plugin-timeout-budgets.test.mjsindex 7a3ddf0ce..670a29eda 100644--- a/apps/desktop/test/plugin-timeout-budgets.test.mjs+++ b/apps/desktop/test/plugin-timeout-budgets.test.mjs@@ -55,6 +55,30 @@ test("host-core dispatches through the shared dispatch deadline", () => {);});+test("the manual-compaction deadline outlasts the summary request it wraps", () => {+ // The mirrored constants are the drift risk: if the sidecar raises its stream+ // watchdog or its retry count, the shared deadline has to follow, otherwise+ // Electron times out a compaction the sidecar is still working on (#795).+ const providerRetry = source("packages/agent-runtime/src/provider-retry.ts");+ const summaryInput = source("packages/agent-runtime/src/compaction-summary-input.ts");+ const watchdog = constMs(providerRetry, "STREAM_IDLE_TIMEOUT_DEFAULT_MS");+ const retries = constMs(summaryInput, "COMPACTION_SUMMARY_MAX_RETRIES");+ const baseDelay = constMs(summaryInput, "COMPACTION_SUMMARY_RETRY_BASE_MS");+ assert.equal(constMs(sharedTimeouts, "STREAM_IDLE_TIMEOUT_MS"), watchdog);+ assert.equal(constMs(sharedTimeouts, "COMPACTION_SUMMARY_MAX_RETRIES"), retries);+ // Doubling waits after the first attempt: base + 2*base + 4*base + ...+ assert.equal(+ constMs(sharedTimeouts, "COMPACTION_SUMMARY_RETRY_BUDGET_MS"),+ baseDelay * (2 ** retries - 1),+ );+ // The constants can be right while the call site ignores them.+ assert.match(+ sharedTimeouts,+ /method === "agent\.compact"[\s\S]{0,60}?AGENT_COMPACT_RPC_TIMEOUT_MS/,+ "agent.compact must not fall back to the flat default deadline",+ );+});+test("host-core budgets match their TypeScript mirrors", () => {const hostDispatch = constMs(hostTools, "DESKTOP_TOOL_DISPATCH_TIMEOUT_MS");assert.equal(constMs(sharedTimeouts, "DESKTOP_TOOL_DISPATCH_TIMEOUT_MS"), hostDispatch);diff --git a/packages/host-runtime/src/runtime-service.test.ts b/packages/host-runtime/src/runtime-service.test.tsindex 40bd8985e..2c61ff7c8 100644--- a/packages/host-runtime/src/runtime-service.test.ts+++ b/packages/host-runtime/src/runtime-service.test.ts@@ -63,6 +63,10 @@ class FakeSidecar implements RuntimeSidecarLink {roots = new Map<string, string | undefined>();rejectPrompt = false;running = false;+ /** Error `agent.compact` answers with; `null` accepts the compaction. */+ compactError: Error | null = null;+ /** Runs inside a failing `agent.compact`, e.g. to persist a checkpoint. */+ beforeCompact: (() => void) | null = null;async call<T = unknown>(method: string, params: Record<string, unknown> = {}): Promise<T> {this.calls.push({ method, params });@@ -75,6 +79,10 @@ class FakeSidecar implements RuntimeSidecarLink {return { supportsVision: false } as T;case "agent.steer":return { accepted: true, turnId: params.expectedTurnId } as T;+ case "agent.compact":+ this.beforeCompact?.();+ if (this.compactError) throw this.compactError;+ return { accepted: true } as T;case "agent.abort":return { ok: true } as T;case "agent.stop":@@ -141,6 +149,57 @@ function build() {return { host, sidecar, service, events, ended, logs };}+describe("RuntimeService manual compaction against a lost reply (#795)", () => {+ const timeout = () => new Error("sidecar RPC timeout: agent.compact");+ const record = (id: string) => ({ id, summary: "s", throughMessageId: "m1", tokensBefore: 1, createdAt: "2026-09-18T00:00:00.000Z" });++ it("reports the durable outcome when the checkpoint landed after a transport timeout", async () => {+ const { host, sidecar, service, logs } = build();+ host.session = { ...host.session, compaction: record("c-old") };+ sidecar.compactError = timeout();+ // The sidecar keeps summarizing and persists through host-core, so the+ // host's own deadline is not evidence that the compaction failed.+ sidecar.beforeCompact = () => {+ host.session = { ...host.session, compaction: record("c-new") };+ };+ await expect(service.compact("s1")).resolves.toEqual({ accepted: true });+ expect(host.calls.filter((call) => call.method === "session.get")).toHaveLength(2);+ expect(logs).toContainEqual({+ level: "warn",+ message: "manual compaction outlived its transport deadline; the checkpoint landed",+ });+ });++ it("keeps reporting a timeout when no checkpoint landed", async () => {+ const { host, sidecar, service } = build();+ host.session = { ...host.session, compaction: record("c-old") };+ sidecar.compactError = timeout();+ await expect(service.compact("s1")).rejects.toThrow("sidecar RPC timeout: agent.compact");+ expect(host.calls.filter((call) => call.method === "session.get")).toHaveLength(2);+ });++ it("does not reconcile a sidecar verdict with a checkpoint from another attempt", async () => {+ const { host, sidecar, service } = build();+ host.session = { ...host.session, compaction: record("c-old") };+ // A real compaction failure is the sidecar's own verdict: an older or+ // unrelated durable checkpoint must not turn it into a success.+ sidecar.beforeCompact = () => {+ host.session = { ...host.session, compaction: record("c-new") };+ };+ sidecar.compactError = Object.assign(new Error("context compaction failed"), {+ errorCode: "CONTEXT_COMPACTION_FAILED",+ });+ await expect(service.compact("s1")).rejects.toThrow("context compaction failed");+ expect(host.calls.filter((call) => call.method === "session.get")).toHaveLength(1);+ });++ it("accepts an acknowledged compaction and never re-reads the session", async () => {+ const { host, service } = build();+ await expect(service.compact("s1")).resolves.toEqual({ accepted: true });+ expect(host.calls.filter((call) => call.method === "session.get")).toHaveLength(1);+ });+});+const owner = { subject: "desktop", roles: ["owner" as const], pairedDevice: true };async function settle(): Promise<void> {diff --git a/packages/host-runtime/src/runtime-service.ts b/packages/host-runtime/src/runtime-service.tsindex 1a0835baa..25d98c89d 100644--- a/packages/host-runtime/src/runtime-service.ts+++ b/packages/host-runtime/src/runtime-service.ts@@ -3,6 +3,8 @@ import { randomUUID } from "node:crypto";import type { RuntimePort, TurnStartRequest, TurnSteerRequest } from "@pi-desktop/agent-host";import {ErrorCodes,+ compactionRecordId,+ isRpcTimeoutError,type AgentEventEnvelope,type AgentStatus,type AskToolResolution,@@ -455,8 +457,26 @@ export class RuntimeService implements RuntimePort {if (!detail.session) throw typedError("Session not found", ErrorCodes.NOT_FOUND);const launch = await this.options.launch.resolve(sessionId, detail.session, settings ?? {});sidecar.setProjectInstructionRoot(sessionId, launch.projectPath);- const result = await sidecar.call<{ accepted?: boolean }>("agent.compact", launch.sidecarParams);- return { accepted: result?.accepted !== false };+ // A lost reply says nothing about the sidecar's own verdict: it keeps+ // summarizing and persists the checkpoint through host-core, so the durable+ // record decides whether this manual compaction succeeded (issue #795).+ const startedWith = compactionRecordId(detail.session);+ try {+ const result = await sidecar.call<{ accepted?: boolean }>("agent.compact", launch.sidecarParams);+ return { accepted: result?.accepted !== false };+ } catch (error) {+ if (!isRpcTimeoutError(error)) throw error;+ const settled = await host.call<{ session?: Record<string, unknown> | null }>("session.get", {+ id: sessionId,+ });+ const landed = compactionRecordId(settled.session);+ if (landed === startedWith) throw error;+ this.options.log("warn", "manual compaction outlived its transport deadline; the checkpoint landed", {+ sessionId,+ compactionId: landed,+ });+ return { accepted: true };+ }}async getStatus(sessionId: string): Promise<AgentStatus> {diff --git a/packages/shared/src/context-compaction.test.ts b/packages/shared/src/context-compaction.test.tsindex 7935083fa..63beb9c19 100644--- a/packages/shared/src/context-compaction.test.ts+++ b/packages/shared/src/context-compaction.test.ts@@ -3,6 +3,7 @@ import type { ContextCompactionRecord } from "./types.js";import {checkpointFallback,checkpointGeneration,+ compactionRecordId,checkpointSummarized,contextCompactionMark,estimateSummaryTokens,@@ -102,3 +103,25 @@ describe("estimateSummaryTokens", () => {expect(estimateSummaryTokens("abcde")).toBe(2);});});++describe("compactionRecordId", () => {+ it("identifies the checkpoint governing the next model request", () => {+ expect(compactionRecordId({ compaction: record({ id: "checkpoint-9" }) })).toBe(+ "checkpoint-9",+ );+ });++ it("reports no identity for a session that never compacted", () => {+ expect(compactionRecordId({ id: "s1" })).toBeNull();+ expect(compactionRecordId({ compaction: null })).toBeNull();+ expect(compactionRecordId(null)).toBeNull();+ expect(compactionRecordId(undefined)).toBeNull();+ expect(compactionRecordId("s1")).toBeNull();+ });++ it("ignores a malformed durable record instead of matching it", () => {+ expect(compactionRecordId({ compaction: {} })).toBeNull();+ expect(compactionRecordId({ compaction: { id: 7 } })).toBeNull();+ expect(compactionRecordId({ compaction: [] })).toBeNull();+ });+});diff --git a/packages/shared/src/context-compaction.ts b/packages/shared/src/context-compaction.tsindex 55c553566..5e81ecf8d 100644--- a/packages/shared/src/context-compaction.ts+++ b/packages/shared/src/context-compaction.ts@@ -4,6 +4,21 @@ import type {ContextCompactionRecord,} from "./types.js";+/**+ * Identity of the checkpoint governing a session's next model request, or+ * `null` when the session has never compacted. A host that lost the reply to a+ * manual compaction compares it before and after the call: the sidecar persists+ * its checkpoint through host-core regardless, so a missing reply is not+ * evidence that the compaction failed (issue #795).+ */+export function compactionRecordId(session: unknown): string | null {+ if (typeof session !== "object" || session === null) return null;+ const compaction = (session as { compaction?: unknown }).compaction;+ if (typeof compaction !== "object" || compaction === null) return null;+ const id = (compaction as { id?: unknown }).id;+ return typeof id === "string" ? id : null;+}+/*** The generation counter rides inside the checkpoint's opaque `details` value:* the host persists that field verbatim, so it survives the transcript rounddiff --git a/packages/shared/src/protocol.test.ts b/packages/shared/src/protocol.test.tsindex 47f7e6492..7f9175def 100644--- a/packages/shared/src/protocol.test.ts+++ b/packages/shared/src/protocol.test.ts@@ -14,6 +14,11 @@ import {isCommandShellOption,isGlobalPermissionMode,isToolsOutputParams,+ AGENT_COMPACT_RPC_TIMEOUT_MS,+ COMMAND_RPC_BUFFER_MS,+ COMPACTION_SUMMARY_MAX_RETRIES,+ COMPACTION_SUMMARY_RETRY_BUDGET_MS,+ STREAM_IDLE_TIMEOUT_MS,rpcTimeoutMs,type PlanExecution,type PlanArtifact,@@ -244,6 +249,28 @@ describe("Plan protocol contracts", () => {);});+ it("outlasts the whole model request a manual compaction spends (#795)", () => {+ // One summary prompt plus the sidecar's retry budget: every attempt that+ // stops producing events is cut by the stream watchdog, and each retry pays+ // its backoff wait. A flat 130s fired on a ~158s compaction, so Electron+ // reported a failure while the sidecar persisted the checkpoint anyway.+ expect(STREAM_IDLE_TIMEOUT_MS).toBe(180_000);+ expect(COMPACTION_SUMMARY_MAX_RETRIES).toBe(3);+ expect(COMPACTION_SUMMARY_RETRY_BUDGET_MS).toBe(14_000);+ expect(AGENT_COMPACT_RPC_TIMEOUT_MS).toBe(+ (1 + COMPACTION_SUMMARY_MAX_RETRIES) * STREAM_IDLE_TIMEOUT_MS ++ COMPACTION_SUMMARY_RETRY_BUDGET_MS ++ COMMAND_RPC_BUFFER_MS,+ );+ expect(AGENT_COMPACT_RPC_TIMEOUT_MS).toBe(744_000);+ expect(rpcTimeoutMs("agent.compact", { sessionId: "s" })).toBe(+ AGENT_COMPACT_RPC_TIMEOUT_MS,+ );+ // The deadline is per-method on purpose: widening the global default would+ // hide a genuinely lost reply on every other call.+ expect(rpcTimeoutMs("agent.getStatus", { sessionId: "s" })).toBe(130_000);+ });+it("covers the permission wait, the admission queue, and host-core dispatch", () => {// Permission (120s) + admission queue (30s) + host-core dispatch (150s) +// slack (10s). A flat 130s would cut off a prompted plugin tool that isdiff --git a/packages/shared/src/rpc-timeouts.ts b/packages/shared/src/rpc-timeouts.tsindex e84b754f6..20475b453 100644--- a/packages/shared/src/rpc-timeouts.ts+++ b/packages/shared/src/rpc-timeouts.ts@@ -27,6 +27,43 @@ export const DEFAULT_DESKTOP_TOOL_RPC_TIMEOUT_MS =TOOL_QUEUE_WAIT_MS +DESKTOP_TOOL_DISPATCH_TIMEOUT_MS +COMMAND_RPC_BUFFER_MS;+/**+ * The sidecar's zero-event stream watchdog. Mirrors+ * `STREAM_IDLE_TIMEOUT_DEFAULT_MS` in+ * `packages/agent-runtime/src/provider-retry.ts`: a provider stream that emits+ * nothing for this long is ended as a retriable failure instead of leaving the+ * caller hung on a connection the provider never closes.+ */+export const STREAM_IDLE_TIMEOUT_MS = 180_000;+/**+ * Retries the summary request may claim after its first failure. Mirrors+ * `COMPACTION_SUMMARY_MAX_RETRIES` in+ * `packages/agent-runtime/src/compaction-summary-input.ts`, whose waits are+ * 2s + 4s + 8s.+ */+export const COMPACTION_SUMMARY_MAX_RETRIES = 3;+export const COMPACTION_SUMMARY_RETRY_BUDGET_MS = 14_000;+/**+ * `agent.compact` is a blocking RPC that spends a whole model request inside+ * the sidecar: pi serializes the conversation into one summary prompt, streams+ * the summary, and may retry a transient failure. No part of that budget is a+ * wall clock the transport can read, so this deadline is derived from the+ * ceilings the sidecar does enforce — an attempt that stops producing events is+ * cut by its stream watchdog, and the retries add at most+ * `COMPACTION_SUMMARY_RETRY_BUDGET_MS` of backoff:+ *+ * (1 + retries) * stream watchdog + retry backoff + transport slack+ *+ * With the flat 130s default Electron gave up while the sidecar was still+ * summarizing a large context (~158s), reported a failed compaction, and the+ * sidecar persisted that checkpoint anyway (issue #795). Deliberately+ * per-method: a wider global default would also hide a genuinely lost reply on+ * every other call.+ */+export const AGENT_COMPACT_RPC_TIMEOUT_MS =+ (1 + COMPACTION_SUMMARY_MAX_RETRIES) * STREAM_IDLE_TIMEOUT_MS ++ COMPACTION_SUMMARY_RETRY_BUDGET_MS ++ COMMAND_RPC_BUFFER_MS;const MAX_TIMER_DELAY_MS = 2_147_483_647;function isRecord(value: unknown): value is Record<string, unknown> {@@ -40,18 +77,31 @@ function isDesktopDispatchedTool(toolName: unknown): boolean {);}+/**+ * Whether an error came from a transport deadline rather than from the peer.+ * `host-process`, `agent-sidecar`, and `parent host proxy` are the only+ * producers of these messages.+ */+export function isRpcTimeoutError(error: unknown): boolean {+ const message = error instanceof Error ? error.message : String(error);+ return /^(?:host|sidecar|parent host proxy) RPC timeout: /.test(message);+}+/*** Return the transport deadline for an RPC call. Bash and desktop-dispatched* (`plugin_*` / `mcp_*`) tools include the waits host-core can spend before it* reports an outcome — the permission gate, the admission queue, and the* effective execution timeout — plus transport slack, so the transport never- * gives up before host-core reports its own timeout. Every call has a finite- * deadline so a lost response cannot leave a pending promise forever.+ * gives up before host-core reports its own timeout. A manual context+ * checkpoint carries the same property against the sidecar's summary request+ * (`AGENT_COMPACT_RPC_TIMEOUT_MS`). Every call has a finite deadline so a lost+ * response cannot leave a pending promise forever.*/export function rpcTimeoutMs(method: string,params: unknown,): number {+ if (method === "agent.compact") return AGENT_COMPACT_RPC_TIMEOUT_MS;if (method !== "tools.execute") return DEFAULT_RPC_TIMEOUT_MS;const input = isRecord(params) ? params : undefined;