Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

fix(agent-ipc): guard compaction admission without blocking Stop

liuzixiangbf22dbf3f0de
diff --git a/apps/desktop/electron/main/ipc/agent-ipc.ts b/apps/desktop/electron/main/ipc/agent-ipc.ts
index 1a3054a09..4256c0d5d 100644
--- a/apps/desktop/electron/main/ipc/agent-ipc.ts
+++ b/apps/desktop/electron/main/ipc/agent-ipc.ts
@@ -113,6 +113,11 @@ export function registerAgentIpc({
loadComposerTemplatesCached,
modeRuns,
}: AgentIpcDependencies): void {
+ // Sessions with a manual compaction request in flight. The session
+ // operation is released before the sidecar call so Stop stays live; this
+ // mark is what keeps a queued prompt from starting against a compacting
+ // runtime (issue #2289).
+ const compactingSessions = new Set<string>();
let host: HostProcess | null = null;
let sidecar: AgentSidecar | null = null;
let agentHostBridge: AgentHostBridge | null = null;
@@ -234,6 +239,15 @@ export function registerAgentIpc({
}
const releaseSessionOperation = await acquireSessionOperation(req.sessionId);
try {
+ // The mark is added while the compaction still holds the operation and
+ // cleared only when the sidecar call settles, so a prompt that acquires
+ // the operation after a compaction started always sees it here — checking
+ // before the acquire would race the compaction's own setup window.
+ if (compactingSessions.has(req.sessionId)) {
+ throw Object.assign(new Error("Session is compacting"), {
+ errorCode: ErrorCodes.AGENT_BUSY,
+ });
+ }
const sessionMessage = await resolveSessionMessageInput(host, req);
// Install the renderer's prompt-time snapshot before any asynchronous
// setup. This closes the gap where a fast completion could beat the
@@ -673,51 +687,70 @@ export function registerAgentIpc({
handle(IPC.invoke.agentCompact, async (req: { sessionId: string }) => {
rejectNativeAgentOperation(req.sessionId);
if (!host || !sidecar) throw new Error("backend unavailable");
- if (activeTurns.has(req.sessionId)) {
- throw Object.assign(new Error("Session already has an active turn"), {
- errorCode: ErrorCodes.AGENT_BUSY,
- });
- }
- const settings = await host.call<any>("settings.get");
- const detail = await host.call<{ session?: any }>("session.get", {
- id: req.sessionId,
- });
- if (!detail.session) {
- throw Object.assign(new Error("Session not found"), {
- errorCode: ErrorCodes.NOT_FOUND,
+ // Hold the session operation across admission (busy check, settings,
+ // session read, launch resolution) so a prompt submitted during setup
+ // queues behind it instead of starting a turn the compaction would run
+ // against mid-stream (issue #2289).
+ const releaseSessionOperation = await acquireSessionOperation(req.sessionId);
+ let detail: { session?: any };
+ let launch: any;
+ try {
+ if (activeTurns.has(req.sessionId)) {
+ throw Object.assign(new Error("Session already has an active turn"), {
+ errorCode: ErrorCodes.AGENT_BUSY,
+ });
+ }
+ const settings = await host.call<any>("settings.get");
+ detail = await host.call<{ session?: any }>("session.get", {
+ id: req.sessionId,
});
+ if (!detail.session) {
+ throw Object.assign(new Error("Session not found"), {
+ errorCode: ErrorCodes.NOT_FOUND,
+ });
+ }
+ launch = await resolveAgentRuntimeLaunch(
+ req.sessionId,
+ detail.session,
+ settings,
+ );
+ sidecar.setProjectInstructionRoot(req.sessionId, launch.workspaceRoot ?? launch.projectPath);
+ // Mark before releasing: the mark is what admission sees, while the
+ // released operation is what keeps Stop live — agentAbort acquires the
+ // same operation and must not wait for the summarization to finish.
+ compactingSessions.add(req.sessionId);
+ } finally {
+ releaseSessionOperation();
}
- const launch = await resolveAgentRuntimeLaunch(
- req.sessionId,
- detail.session,
- settings,
- );
- sidecar.setProjectInstructionRoot(req.sessionId, launch.workspaceRoot ?? launch.projectPath);
// 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", {
+ 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: { compactionId: landed },
+ data: { providerId: launch.providerId, modelId: launch.modelId },
});
- return { accepted: true };
+ return result;
+ } finally {
+ compactingSessions.delete(req.sessionId);
}
- logger.app("session", "info", "context compacted manually", {
- sessionId: req.sessionId,
- data: { providerId: launch.providerId, modelId: launch.modelId },
- });
- return result;
});
handle(IPC.invoke.agentAbort, async (req: { sessionId: string; turnId?: string }) => {
diff --git a/apps/desktop/test/agent-compact-session-operation.test.mjs b/apps/desktop/test/agent-compact-session-operation.test.mjs
new file mode 100644
index 000000000..79b843f2f
--- /dev/null
+++ b/apps/desktop/test/agent-compact-session-operation.test.mjs
@@ -0,0 +1,218 @@
+import assert from "node:assert/strict";
+import * as fs from "node:fs";
+import * as path from "node:path";
+import test from "node:test";
+import ts from "typescript";
+import { ErrorCodes } from "../../../packages/shared/src/errors.ts";
+import { IPC } from "../../../packages/shared/src/protocol.ts";
+
+function load(relative, imports) {
+ const file = new URL(relative, import.meta.url);
+ const { outputText } = transpile(file);
+ const module = { exports: {} };
+ new Function("require", "exports", "module", outputText)((id) => {
+ assert.ok(Object.hasOwn(imports, id), `unexpected dependency: ${id}`);
+ return imports[id];
+ }, module.exports, module);
+ return module.exports;
+}
+
+function transpile(file) {
+ return ts.transpileModule(fs.readFileSync(file, "utf8"), {
+ compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS },
+ fileName: path.resolve(file.pathname),
+ });
+}
+
+/** The production promise-tail session operation, same semantics. */
+function createSessionOperations() {
+ const tails = new Map();
+ return async function acquireSessionOperation(sessionId) {
+ const id = sessionId.trim();
+ const previous = tails.get(id) ?? Promise.resolve();
+ let resolveCurrent;
+ const current = new Promise((resolve) => { resolveCurrent = resolve; });
+ const tail = previous.then(() => current);
+ tails.set(id, tail);
+ await previous;
+ let released = false;
+ return () => {
+ if (released) return;
+ released = true;
+ resolveCurrent();
+ if (tails.get(id) === tail) tails.delete(id);
+ };
+ };
+}
+
+function buildHarness({ hostCall, sidecarCall, resolveSessionMessageInput }) {
+ const admissionTail =
+ resolveSessionMessageInput ??
+ (async () => { throw new Error("sentinel: prompt admission tail"); });
+ const handlers = new Map();
+ const acquireSessionOperation = createSessionOperations();
+ const activeTurns = new Map();
+ const host = { call: (method, input) => hostCall(method, input) };
+ const sidecar = {
+ call: (method, input) => sidecarCall(method, input),
+ setProjectInstructionRoot() {},
+ };
+ const agentIpc = load("../electron/main/ipc/agent-ipc.ts", {
+ "@pi-desktop/shared": {
+ IPC,
+ ErrorCodes,
+ compactionRecordId: (session) => session?.compactionRecordId ?? null,
+ composeMentionPrompt: (parts) => parts?.prompt ?? "",
+ findSkillMentions: () => [],
+ isGlobalPermissionMode: () => false,
+ isRpcTimeoutError: () => false,
+ },
+ "../composer-mcp": { expandMcpInvocation: () => null },
+ "../runtime/mode-runs": { modeContinuationOrigin: () => undefined },
+ "../runtime/goal-start": { goalPromptMode: () => null, goalStartRequested: () => false },
+ "@pi-desktop/agent-runtime": { expandSlashInvocation: () => null, visionFromModelConfig: () => null },
+ "../prompt-attachments": {
+ appendPromptFallbackPaths: () => [],
+ durableUserMessageId: () => "user-message",
+ preparePromptAttachments: async () => [],
+ },
+ "../session-references": { resolveSessionReferences: async () => [] },
+ "../agent-mentions": { resolvePromptAgentMentions: async () => [] },
+ "@pi-desktop/host-runtime": {
+ executionFromResponse: () => null,
+ resolveSessionMessageInput: admissionTail,
+ },
+ });
+ agentIpc.registerAgentIpc({
+ registrar: { handle: (channel, handler) => handlers.set(channel, handler) },
+ getHost: () => host,
+ getSidecar: () => sidecar,
+ getAgentHostBridge: () => ({ markAborting() {} }),
+ logger: { app() {} },
+ agentExtensions: { cancelPrompts() {} },
+ cancelSessionTools() {},
+ persistenceOutbox: { dropSession: async () => undefined },
+ dataDir: "data-dir",
+ activeTurns,
+ completionNoticeTurns: new Set(),
+ recordTurnStart() {},
+ isTurnDispatchable: () => true,
+ activeTurnUsages: new Map(),
+ approvedExecutionIdsBySession: new Map(),
+ claimedExecutionSessions: new Map(),
+ resolveAgentRuntimeLaunch: async () => ({
+ sidecarParams: {},
+ providerId: "provider",
+ modelId: "model",
+ workspaceRoot: null,
+ projectPath: null,
+ }),
+ acquireSessionOperation,
+ finishTurn: async () => undefined,
+ lockAbortReason() {},
+ finishApprovedExecution: async () => undefined,
+ dispatchApprovedPlan() {},
+ dispatchExecutionForProposal() {},
+ emitAgentEvent() {},
+ setNotificationViewingSessionId() {},
+ optionalWorkspaceRoot: async () => null,
+ composerCommandService: { buildComposerCommands: async () => [] },
+ loadComposerTemplatesCached: async () => [],
+ modeRuns: {},
+ });
+ return { handlers, activeTurns };
+}
+
+const compact = (h, req) => h.handlers.get(IPC.invoke.agentCompact)(req);
+const prompt = (h, req) => h.handlers.get(IPC.invoke.agentPrompt)(req);
+const abort = (h, req) => h.handlers.get(IPC.invoke.agentAbort)(req);
+
+test("a prompt that queues behind compaction setup is refused by the compacting mark", async () => {
+ let releaseSettings;
+ let releaseCompact;
+ let turnHostCalls = 0;
+ const h = buildHarness({
+ hostCall: async (method) => {
+ if (method === "settings.get") {
+ await new Promise((resolve) => { releaseSettings = resolve; });
+ return {};
+ }
+ if (method === "session.get") return { session: { id: "s1", compactionRecordId: "c0" } };
+ turnHostCalls += 1;
+ return {};
+ },
+ sidecarCall: async (method) => {
+ if (method === "agent.compact") {
+ await new Promise((resolve) => { releaseCompact = resolve; });
+ return { ok: true };
+ }
+ throw new Error(`unexpected sidecar call: ${method}`);
+ },
+ });
+
+ const compacting = compact(h, { sessionId: "s1" });
+ // The prompt is issued while compaction still holds the operation: its
+ // acquire must wait through the setup window, and the mark it then sees
+ // must refuse it — the compaction's own admission stays exclusive.
+ const submitted = prompt(h, { sessionId: "s1", content: "hello" }).catch(
+ (error) => error,
+ );
+ await new Promise((resolve) => setImmediate(resolve));
+ releaseSettings();
+ const rejection = await submitted;
+ assert.equal(typeof releaseCompact, "function",
+ "the compaction is still awaiting the sidecar while the prompt settles");
+ assert.equal(rejection.errorCode, ErrorCodes.AGENT_BUSY);
+ assert.match(rejection.message, /compacting/);
+ assert.equal(turnHostCalls, 0, "no turn began behind the compaction");
+ releaseCompact();
+ await compacting;
+});
+
+test("abort does not wait for the in-flight compaction, and the mark clears when it settles", async () => {
+ let releaseCompact;
+ const h = buildHarness({
+ hostCall: async (method) => {
+ if (method === "session.get") return { session: { id: "s1", compactionRecordId: "c0" } };
+ return {};
+ },
+ sidecarCall: async (method) => {
+ if (method === "agent.compact") {
+ await new Promise((resolve) => { releaseCompact = resolve; });
+ return { ok: true };
+ }
+ if (method === "agent.abort") return { ok: true };
+ throw new Error(`unexpected sidecar call: ${method}`);
+ },
+ });
+
+ const compacting = compact(h, { sessionId: "s1" });
+ await new Promise((resolve) => setImmediate(resolve));
+ // Stop must acquire the released operation while agent.compact is still in
+ // flight — that is exactly what releasing before the sidecar call buys.
+ const stopped = await abort(h, { sessionId: "s1" });
+ assert.deepEqual(stopped, { ok: true });
+ assert.equal(typeof releaseCompact, "function", "compaction is still awaiting the sidecar");
+
+ releaseCompact();
+ await compacting;
+
+ // With the mark cleared, a prompt passes admission again (sentinel proves
+ // it got past the compacting check).
+ const admitted = await prompt(h, { sessionId: "s1", content: "hello" }).catch(
+ (error) => error,
+ );
+ assert.match(admitted.message, /sentinel/);
+});
+
+test("an idle compaction still refuses a session with an active turn", async () => {
+ const h = buildHarness({
+ hostCall: async () => ({}),
+ sidecarCall: async () => ({}),
+ });
+ h.activeTurns.set("s1", "turn-1");
+ await assert.rejects(
+ compact(h, { sessionId: "s1" }),
+ (error) => error.errorCode === ErrorCodes.AGENT_BUSY,
+ );
+});