Skip to content

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

fix(desktop): keep ask answers from re-entering their own IPC handler

mingkun9686ee23ecf654c
diff --git a/apps/desktop/electron/main/agent-host-bridge.ts b/apps/desktop/electron/main/agent-host-bridge.ts
index 40f6b98aa..009dbe637 100644
--- a/apps/desktop/electron/main/agent-host-bridge.ts
+++ b/apps/desktop/electron/main/agent-host-bridge.ts
@@ -82,6 +82,19 @@ export function createAgentHostBridge(options: AgentHostBridgeOptions) {
const abortingSessions = new Set<string>();
const resolvingViaModule = new Set<string>();
+ /**
+ * Ask answers already travelling through the Host input path, keyed by
+ * `sessionId:requestId`. The Host's runtime port answers through this same
+ * registered IPC handler, so resolving an open input re-enters
+ * `resolveAskByRequestId` while the outer frame still holds the pending
+ * input (it is deleted only after `respondInput` returns). Without this
+ * guard the re-entrant frame matches that same input again and the two
+ * frames recurse until the stack overflows, leaving the question pending
+ * forever. The re-entrant frame returns `null`, so its caller takes the
+ * direct sidecar resolve instead.
+ */
+ const resolvingInputs = new Set<string>();
+
const requireHost = (): HostLike => {
const host = options.getHost();
if (!host) throw new RacpError("AGENT_UNAVAILABLE", "host is not running", { retriable: true });
@@ -372,24 +385,32 @@ export function createAgentHostBridge(options: AgentHostBridgeOptions) {
/**
* Resolve a Composer ask card through the Host-owned input path, matched
* by the runtime request id the card carries. Returns `null` when this
- * Host holds no matching open input so the caller falls back to the
- * direct sidecar resolve; otherwise the pending input is deleted before
- * the sidecar settles, so a later `pendingInteractiveRequests` read (for
- * example after switching windows back to the session) no longer
- * resurrects the already answered card.
+ * Host holds no matching open input — including the re-entrant call the
+ * Host's own runtime port makes while this frame is still in flight — so
+ * the caller falls back to the direct sidecar resolve; otherwise the
+ * pending input is deleted before the sidecar settles, so a later
+ * `pendingInteractiveRequests` read (for example after switching windows
+ * back to the session) no longer resurrects the already answered card.
*/
async resolveAskByRequestId(resolution: AskToolResolution): Promise<{ ok: boolean } | null> {
const sessionId = String(resolution?.sessionId ?? "").trim();
const requestId = String(resolution?.requestId ?? "").trim();
if (!sessionId || !requestId) return null;
+ const key = `${sessionId}:${requestId}`;
+ if (resolvingInputs.has(key)) return null;
const entry = agentHost.pendingInputRequests(sessionId)
.find((candidate) => candidate.original.requestId === requestId);
if (!entry) return null;
- await forIpc(() => agentHost.respondInput(DESKTOP_PRINCIPAL, {
- inputId: entry.input.id,
- answers: resolution.answers,
- context: { requestId },
- }));
+ resolvingInputs.add(key);
+ try {
+ await forIpc(() => agentHost.respondInput(DESKTOP_PRINCIPAL, {
+ inputId: entry.input.id,
+ answers: resolution.answers,
+ context: { requestId },
+ }));
+ } finally {
+ resolvingInputs.delete(key);
+ }
return { ok: true };
},
lookupWorkAdmission(request: {
diff --git a/apps/desktop/test/asktool-resolve-clears-host-input.test.mjs b/apps/desktop/test/asktool-resolve-clears-host-input.test.mjs
index f43589d01..8e384ceee 100644
--- a/apps/desktop/test/asktool-resolve-clears-host-input.test.mjs
+++ b/apps/desktop/test/asktool-resolve-clears-host-input.test.mjs
@@ -100,3 +100,108 @@ test("resolveAskByRequestId returns null for unknown requests", async (t) => {
);
assert.equal(invoked, 0);
});
+
+/**
+ * The Host answers an open input by calling back through this same registered
+ * handler: the bridge's runtime port wraps the `invokeIpc` dispatcher, so
+ * `resolveAskByRequestId` runs a second time while the outer frame still holds
+ * the pending input (it is deleted only after `respondInput` returns). Without
+ * the bridge's in-flight guard those two frames re-enter each other until the
+ * stack overflows — the answer never reaches the runtime, `pendingInputs` is
+ * never cleared, and the answered card comes back on the next session switch.
+ * The mocked `invoke` above cannot see that wiring, so this test assembles the
+ * real handler.
+ */
+test("a Host-owned answer does not re-enter its own IPC handler", async (t) => {
+ const server = await createServer({
+ root: dirname(here),
+ configFile: false,
+ server: { middlewareMode: true, hmr: false, ws: false },
+ appType: "custom",
+ optimizeDeps: { noDiscovery: true, include: [] },
+ });
+ t.after(() => server.close());
+ const { createAgentHostBridge } = await server.ssrLoadModule("/electron/main/agent-host-bridge.ts");
+ const { registerAgentIpc } = await server.ssrLoadModule("/electron/main/ipc/agent-ipc.ts");
+
+ // The handler table `invokeIpc` dispatches into (register.ts:502).
+ const handlers = new Map();
+ const registrar = {
+ ipcMain: { handle() {} },
+ handle(channel, handler) {
+ handlers.set(channel, handler);
+ },
+ handleWithEvent(channel, handler) {
+ handlers.set(channel, handler);
+ },
+ assertMainWindowSender() {},
+ };
+ const invoke = async (channel, args = []) => {
+ const handler = handlers.get(channel);
+ if (!handler) throw new Error(`handler not registered: ${channel}`);
+ return handler(...args);
+ };
+
+ const sidecarCalls = [];
+ const sidecar = {
+ async call(method, params) {
+ sidecarCalls.push({ method, params });
+ return { ok: true };
+ },
+ };
+ const bridge = createAgentHostBridge({
+ channels: IPC.invoke,
+ invoke,
+ getHost: () => null,
+ log: () => undefined,
+ });
+
+ const noop = () => undefined;
+ registerAgentIpc({
+ registrar,
+ getHost: () => null,
+ getSidecar: () => sidecar,
+ getAgentHostBridge: () => bridge,
+ logger: { app: noop },
+ vendorOAuth: {},
+ agentExtensions: {},
+ cancelSessionTools: noop,
+ persistenceOutbox: {},
+ dataDir: "",
+ activeTurns: new Map(),
+ isTurnDispatchable: () => true,
+ activeTurnUsages: new Map(),
+ approvedExecutionIdsBySession: new Map(),
+ claimedExecutionSessions: new Map(),
+ resolveAgentRuntimeLaunch: async () => ({}),
+ acquireSessionOperation: async () => noop,
+ finishTurn: async () => undefined,
+ lockAbortReason: noop,
+ finishApprovedExecution: async () => undefined,
+ dispatchApprovedPlan: async () => undefined,
+ dispatchExecutionForProposal: async () => undefined,
+ emitAgentEvent: noop,
+ setNotificationViewingSessionId: noop,
+ optionalWorkspaceRoot: async () => null,
+ composerCommandService: { buildComposerCommands: async () => [] },
+ loadComposerTemplatesCached: async () => [],
+ });
+
+ ingestAsk(bridge);
+ assert.equal((await bridge.pendingInteractiveRequests("s1")).asks.length, 1);
+
+ const settled = await handlers.get(IPC.invoke.askToolResolve)({
+ sessionId: "s1",
+ requestId: "ask_1",
+ answers: [["a"]],
+ });
+
+ assert.deepEqual(settled, { ok: true });
+ // The answer reaches the runtime exactly once, through the re-entrant frame's
+ // fallback, and the Host stops reporting the input afterwards.
+ assert.equal(sidecarCalls.length, 1);
+ assert.equal(sidecarCalls[0].method, "asktool.resolve");
+ assert.equal(sidecarCalls[0].params.requestId, "ask_1");
+ assert.deepEqual(sidecarCalls[0].params.answers, [["a"]]);
+ assert.deepEqual((await bridge.pendingInteractiveRequests("s1")).asks, []);
+});