Skip to content

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

feat(remote): translate RACP events into renderer IPC events

vastsac3127b24af52
diff --git a/apps/desktop/electron/main/remote/remote-event-bridge.ts b/apps/desktop/electron/main/remote/remote-event-bridge.ts
new file mode 100644
index 000000000..421222409
--- /dev/null
+++ b/apps/desktop/electron/main/remote/remote-event-bridge.ts
@@ -0,0 +1,273 @@
+/**
+ * Event bridge: translate a paired host's RACP event stream into the local
+ * renderer IPC events already consumed for a local session. The renderer
+ * cannot tell the difference (spec §3.4); only the namespaced session id and
+ * the `source: "remote"` badge distinguish a remote row.
+ *
+ * The bridge is pure translation: it forwards to an injected `emit(channel,
+ * payload)` and calls an optional `onLifecycle` for host-scope `session.*`
+ * kinds. It never touches the router, the connection, or persistence — the
+ * connection layer (Stage 3) drives subscription and unsubscription.
+ */
+import { IPC } from "@pi-desktop/shared";
+import type {
+ AgentEvent,
+ AgentEventEnvelope,
+ AskToolRequest,
+ PlanningStateEvent,
+ RacpApprovalRequest,
+ RacpEventEnvelope,
+ RacpInputRequest,
+ ToolPermissionRequest,
+} from "@pi-desktop/shared";
+import { makeRemoteApprovalRequestId, makeRemoteSessionId } from "./backend-router.js";
+
+/** A minimal shape of the session field carried by host-scope session events.
+ * Both the RACP `RacpSession` and the host's smaller `SessionSummary` extend
+ * this — no field beyond these five is read by lifecycle handlers. */
+export type RemoteEventSessionRef = {
+ id: string;
+ title?: string;
+ createdAt?: string;
+ updatedAt?: string;
+};
+
+export type RemoteLifecycleEvent =
+ | { readonly kind: "session.created"; readonly hostSessionId: string; readonly remoteSessionId: string; readonly session: RemoteEventSessionRef }
+ | { readonly kind: "session.changed"; readonly hostSessionId: string; readonly remoteSessionId: string; readonly session: RemoteEventSessionRef }
+ | { readonly kind: "session.archived"; readonly hostSessionId: string; readonly remoteSessionId: string; readonly session?: RemoteEventSessionRef };
+
+export type RemoteEventBridgeOptions = {
+ /** Renderer-visible id prefix component. Fixed for one host. */
+ hostKey: string;
+ /** Dispatch a local IPC event to the renderer. */
+ emit: (channel: string, payload: unknown) => void;
+ /** Lifecycle callback for host-scope `session.*` kinds; drives the router. */
+ onLifecycle?: (event: RemoteLifecycleEvent) => void;
+ /** Optional structured warning log; defaults to a no-op. */
+ log?: (level: "warn", message: string, data?: unknown) => void;
+};
+
+export interface RemoteEventBridge {
+ /** Handle one RACP envelope. Unknown kinds are dropped. */
+ handle(envelope: RacpEventEnvelope): void;
+}
+
+const APPROVAL_KIND = { tool: "tool", plan: "plan", goal: "goal" } as const;
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === "object" && value !== null;
+}
+
+function extractSessionRef(payload: unknown): RemoteEventSessionRef | undefined {
+ if (!isRecord(payload)) return undefined;
+ const session = payload.session;
+ if (!isRecord(session) || typeof session.id !== "string") return undefined;
+ return {
+ id: session.id,
+ ...(typeof session.title === "string" ? { title: session.title } : {}),
+ ...(typeof session.createdAt === "string" ? { createdAt: session.createdAt } : {}),
+ ...(typeof session.updatedAt === "string" ? { updatedAt: session.updatedAt } : {}),
+ };
+}
+
+function extractAgentEvent(payload: unknown): AgentEvent | undefined {
+ if (!isRecord(payload)) return undefined;
+ const event = payload.event;
+ if (!isRecord(event) || typeof event.type !== "string") return undefined;
+ return event as unknown as AgentEvent;
+}
+
+function extractApprovalRequest(payload: unknown): RacpApprovalRequest | undefined {
+ if (!isRecord(payload)) return undefined;
+ // The RACP schema publishes the approval request as the payload's own body,
+ // not nested under `.approval`. Both agent-host emit sites and the fixture
+ // in packages/racp use that shape.
+ if (typeof payload.id !== "string" || typeof payload.kind !== "string") return undefined;
+ return payload as unknown as RacpApprovalRequest;
+}
+
+function extractInputRequest(payload: unknown): RacpInputRequest | undefined {
+ if (!isRecord(payload)) return undefined;
+ if (typeof payload.id !== "string" || !Array.isArray(payload.questions)) return undefined;
+ return payload as unknown as RacpInputRequest;
+}
+
+function toToolPermissionRequest(
+ remoteSessionId: string,
+ approval: RacpApprovalRequest,
+): ToolPermissionRequest {
+ return {
+ // Stateless approval id encoding — see backend-router.ts.
+ requestId: makeRemoteApprovalRequestId(remoteSessionId, approval.id),
+ sessionId: remoteSessionId,
+ // RACP approvals do not carry a toolCallId back; the permission card does
+ // not display it and only the resolution path needs the requestId.
+ toolCallId: "",
+ toolName: approval.toolName ?? "",
+ argsPreview: null,
+ risk: approval.risk ?? "medium",
+ reason: approval.summary,
+ ...(approval.agentName ? { agentName: approval.agentName } : {}),
+ ...(approval.parentToolCallId ? { parentToolCallId: approval.parentToolCallId } : {}),
+ };
+}
+
+function toAskToolRequest(
+ remoteSessionId: string,
+ input: RacpInputRequest,
+): AskToolRequest {
+ return {
+ requestId: input.id,
+ sessionId: remoteSessionId,
+ // Ask-tool needs a toolCallId to attach the answer to; the RACP schema
+ // supplies it as `parentToolCallId` when the input came from a subagent,
+ // and leaves it undefined for the top-level agent.
+ toolCallId: input.parentToolCallId ?? "",
+ questions: input.questions.map((question) => ({
+ question: question.question,
+ options: question.options,
+ multiSelect: question.multiSelect,
+ })),
+ };
+}
+
+function toPlanningStateAgentEvent(
+ remoteSessionId: string,
+ planning: PlanningStateEvent,
+): AgentEvent {
+ const { sessionId: _hostSessionId, ...rest } = planning;
+ return { type: "planning_state", ...rest };
+}
+
+export function createRemoteEventBridge(options: RemoteEventBridgeOptions): RemoteEventBridge {
+ const { hostKey, emit, onLifecycle } = options;
+ const log = options.log ?? (() => undefined);
+ const remoteIdOf = (hostSessionId: string) => makeRemoteSessionId(hostKey, hostSessionId);
+ const emitAgentEvent = (
+ envelope: RacpEventEnvelope,
+ remoteSessionId: string,
+ event: AgentEvent,
+ ): void => {
+ const local: AgentEventEnvelope = {
+ sessionId: remoteSessionId,
+ ...(envelope.turnId ? { turnId: envelope.turnId } : {}),
+ ts: Date.parse(envelope.occurredAt) || Date.now(),
+ event,
+ ...(envelope.parentToolCallId ? { parentToolCallId: envelope.parentToolCallId } : {}),
+ ...(envelope.agentName ? { agentName: envelope.agentName } : {}),
+ };
+ emit(IPC.event.agentMessage, local);
+ };
+
+ const handleHostSession = (envelope: RacpEventEnvelope): void => {
+ const session = extractSessionRef(envelope.payload);
+ if (!session) {
+ log("warn", `host-scope ${envelope.kind} carried no session`, envelope);
+ return;
+ }
+ const remoteSessionId = remoteIdOf(session.id);
+ if (envelope.kind === "session.created") {
+ onLifecycle?.({ kind: "session.created", hostSessionId: session.id, remoteSessionId, session });
+ emit(IPC.event.sessionsChanged, {
+ reason: "remote.session.created",
+ selectSessionId: remoteSessionId,
+ });
+ return;
+ }
+ if (envelope.kind === "session.changed") {
+ onLifecycle?.({ kind: "session.changed", hostSessionId: session.id, remoteSessionId, session });
+ emit(IPC.event.sessionsChanged, { reason: "remote.session.changed" });
+ return;
+ }
+ // "session.archived": pass through to the lifecycle handler for router
+ // cleanup, then refresh the renderer's session list.
+ onLifecycle?.({ kind: "session.archived", hostSessionId: session.id, remoteSessionId, session });
+ emit(IPC.event.sessionsChanged, { reason: "remote.session.archived" });
+ };
+
+ const handleSessionScope = (envelope: RacpEventEnvelope): void => {
+ if (typeof envelope.sessionId !== "string") return;
+ const remoteSessionId = remoteIdOf(envelope.sessionId);
+ switch (envelope.kind) {
+ case "item.started":
+ case "item.delta":
+ case "item.completed":
+ case "tool.progress":
+ case "turn.queued":
+ case "turn.started":
+ case "turn.completed":
+ case "turn.interrupted":
+ case "turn.failed":
+ case "turn.canceled":
+ case "turn.activity": {
+ const event = extractAgentEvent(envelope.payload);
+ if (!event) return;
+ emitAgentEvent(envelope, remoteSessionId, event);
+ return;
+ }
+ case "session.changed": {
+ // Two shapes ride this kind (agent-host):
+ // 1. `{ event: PlanningStateEvent }` — surface as a local planning
+ // event so the plan card behaves the same as local.
+ // 2. `{ sessionId, status, planningState }` — a periodic status
+ // refresh; the desktop derives its own status from turn events, so
+ // drop it and let the eventual snapshot refresh cover it.
+ const payload = envelope.payload;
+ if (isRecord(payload) && isRecord(payload.event) && payload.event.state !== undefined) {
+ const planning = payload.event as unknown as PlanningStateEvent;
+ emitAgentEvent(
+ envelope,
+ remoteSessionId,
+ toPlanningStateAgentEvent(remoteSessionId, planning),
+ );
+ }
+ return;
+ }
+ case "approval.requested": {
+ const approval = extractApprovalRequest(envelope.payload);
+ if (!approval) return;
+ // Plan / goal approvals ride the following `planning_state` event; the
+ // renderer's plan card is driven by that, not by a synthetic tool card.
+ if (approval.kind !== APPROVAL_KIND.tool) return;
+ emitAgentEvent(envelope, remoteSessionId, {
+ type: "tool_permission_request",
+ request: toToolPermissionRequest(remoteSessionId, approval),
+ });
+ return;
+ }
+ case "input.requested": {
+ const input = extractInputRequest(envelope.payload);
+ if (!input) return;
+ emitAgentEvent(envelope, remoteSessionId, {
+ type: "asktool_request",
+ request: toAskToolRequest(remoteSessionId, input),
+ });
+ return;
+ }
+ case "approval.resolved":
+ case "input.resolved":
+ case "terminal.changed":
+ case "terminal.output":
+ case "resync.required":
+ // Approvals settle through the renderer's own resolve call; the plan
+ // and status changes come as `session.changed` payloads. Terminal
+ // events belong to Stage 5. `resync.required` is Stage 3b — the
+ // connection layer must consume it, not the bridge.
+ return;
+ default:
+ return;
+ }
+ };
+
+ return {
+ handle(envelope) {
+ try {
+ if (envelope.scope === "host") return handleHostSession(envelope);
+ if (envelope.scope === "session") return handleSessionScope(envelope);
+ } catch (error) {
+ log("warn", `remote event bridge failed on ${envelope.kind}`, error);
+ }
+ },
+ };
+}
diff --git a/apps/desktop/test/remote-event-bridge.test.mjs b/apps/desktop/test/remote-event-bridge.test.mjs
new file mode 100644
index 000000000..9780472d5
--- /dev/null
+++ b/apps/desktop/test/remote-event-bridge.test.mjs
@@ -0,0 +1,248 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { register } from "node:module";
+import { dirname, join } from "node:path";
+import { fileURLToPath, pathToFileURL } from "node:url";
+
+const here = dirname(fileURLToPath(import.meta.url));
+register(pathToFileURL(join(here, "helpers/ts-import-hooks.mjs")));
+
+const { IPC } = await import("@pi-desktop/shared");
+const { makeRemoteApprovalRequestId, makeRemoteSessionId } = await import(
+ "../electron/main/remote/backend-router.ts"
+);
+const { createRemoteEventBridge } = await import(
+ "../electron/main/remote/remote-event-bridge.ts"
+);
+
+const HOST_KEY = "hostA";
+const HOST_SESSION_ID = "sess-1";
+const REMOTE_SESSION_ID = makeRemoteSessionId(HOST_KEY, HOST_SESSION_ID);
+
+function makeEnvelope(overrides = {}) {
+ return {
+ eventId: "e1",
+ scope: "session",
+ sessionId: HOST_SESSION_ID,
+ epoch: "epoch-1",
+ revision: 1,
+ kind: "item.started",
+ occurredAt: "2026-09-18T10:00:00.000Z",
+ payload: {},
+ ...overrides,
+ };
+}
+
+function collect() {
+ const events = [];
+ const lifecycle = [];
+ const warnings = [];
+ const bridge = createRemoteEventBridge({
+ hostKey: HOST_KEY,
+ emit: (channel, payload) => events.push({ channel, payload }),
+ onLifecycle: (event) => lifecycle.push(event),
+ log: (level, message, data) => warnings.push({ level, message, data }),
+ });
+ return { bridge, events, lifecycle, warnings };
+}
+
+test("host-scope session.created fires lifecycle and refreshes sessions with the new id", () => {
+ const { bridge, events, lifecycle } = collect();
+ bridge.handle(
+ makeEnvelope({
+ scope: "host",
+ kind: "session.created",
+ payload: {
+ session: {
+ id: HOST_SESSION_ID,
+ title: "Fresh remote",
+ createdAt: "2026-09-18T10:00:00.000Z",
+ updatedAt: "2026-09-18T10:00:00.000Z",
+ },
+ },
+ }),
+ );
+ assert.equal(lifecycle.length, 1);
+ assert.equal(lifecycle[0].kind, "session.created");
+ assert.equal(lifecycle[0].remoteSessionId, REMOTE_SESSION_ID);
+ assert.equal(events.length, 1);
+ assert.equal(events[0].channel, IPC.event.sessionsChanged);
+ assert.equal(events[0].payload.reason, "remote.session.created");
+ assert.equal(events[0].payload.selectSessionId, REMOTE_SESSION_ID);
+});
+
+test("host-scope session.archived tells the router to release the id without selecting it", () => {
+ const { bridge, events, lifecycle } = collect();
+ bridge.handle(
+ makeEnvelope({
+ scope: "host",
+ kind: "session.archived",
+ payload: { session: { id: HOST_SESSION_ID } },
+ }),
+ );
+ assert.equal(lifecycle[0].kind, "session.archived");
+ assert.equal(events[0].payload.reason, "remote.session.archived");
+ assert.equal(events[0].payload.selectSessionId, undefined);
+});
+
+test("host-scope events without a session payload log a warning and no emit fires", () => {
+ const { bridge, events, warnings } = collect();
+ bridge.handle(
+ makeEnvelope({ scope: "host", kind: "session.changed", payload: {} }),
+ );
+ assert.equal(events.length, 0);
+ assert.equal(warnings.length, 1);
+ assert.match(warnings[0].message, /carried no session/);
+});
+
+test("item.started forwards the AgentEvent verbatim under the remote session id", () => {
+ const { bridge, events } = collect();
+ const agentEvent = { type: "tool_start", toolCallId: "tc-1", toolName: "shell", args: {} };
+ bridge.handle(
+ makeEnvelope({
+ kind: "item.started",
+ turnId: "turn-1",
+ payload: { itemType: "tool", itemId: "i-1", event: agentEvent },
+ }),
+ );
+ assert.equal(events.length, 1);
+ assert.equal(events[0].channel, IPC.event.agentMessage);
+ assert.equal(events[0].payload.sessionId, REMOTE_SESSION_ID);
+ assert.equal(events[0].payload.turnId, "turn-1");
+ assert.deepEqual(events[0].payload.event, agentEvent);
+ assert.equal(events[0].payload.ts, Date.parse("2026-09-18T10:00:00.000Z"));
+});
+
+test("session.changed forwards a PlanningStateEvent as a local planning_state AgentEvent", () => {
+ const { bridge, events } = collect();
+ bridge.handle(
+ makeEnvelope({
+ kind: "session.changed",
+ payload: {
+ event: {
+ sessionId: HOST_SESSION_ID,
+ state: "awaiting_approval",
+ kind: "plan",
+ proposalId: "p-1",
+ title: "Do a thing",
+ },
+ },
+ }),
+ );
+ assert.equal(events.length, 1);
+ assert.equal(events[0].channel, IPC.event.agentMessage);
+ const forwarded = events[0].payload.event;
+ assert.equal(forwarded.type, "planning_state");
+ assert.equal(forwarded.state, "awaiting_approval");
+ assert.equal(forwarded.proposalId, "p-1");
+ // The host session id is stripped — the AgentEventEnvelope carries the
+ // (remote) session id already.
+ assert.equal(forwarded.sessionId, undefined);
+});
+
+test("session.changed status-only payloads are dropped", () => {
+ const { bridge, events } = collect();
+ bridge.handle(
+ makeEnvelope({
+ kind: "session.changed",
+ payload: { sessionId: HOST_SESSION_ID, status: "idle", planningState: "inactive" },
+ }),
+ );
+ assert.equal(events.length, 0);
+});
+
+test("approval.requested kind:tool synthesizes a local tool_permission_request with an encoded requestId", () => {
+ const { bridge, events } = collect();
+ const approval = {
+ id: "appr-9",
+ sessionId: HOST_SESSION_ID,
+ turnId: "turn-1",
+ kind: "tool",
+ summary: "run rm -rf",
+ expiresAt: "2026-09-18T10:05:00.000Z",
+ revision: 3,
+ toolName: "shell",
+ risk: "high",
+ allowedDecisions: ["allow-once", "deny"],
+ };
+ bridge.handle(
+ makeEnvelope({ kind: "approval.requested", turnId: "turn-1", payload: approval }),
+ );
+ assert.equal(events.length, 1);
+ const request = events[0].payload.event.request;
+ assert.equal(events[0].payload.event.type, "tool_permission_request");
+ assert.equal(request.requestId, makeRemoteApprovalRequestId(REMOTE_SESSION_ID, "appr-9"));
+ assert.equal(request.sessionId, REMOTE_SESSION_ID);
+ assert.equal(request.toolName, "shell");
+ assert.equal(request.risk, "high");
+ assert.equal(request.reason, "run rm -rf");
+});
+
+test("approval.requested kind:plan and kind:goal are dropped — the plan card rides planning_state", () => {
+ const { bridge, events } = collect();
+ const base = {
+ sessionId: HOST_SESSION_ID,
+ turnId: "turn-1",
+ summary: "approve plan",
+ expiresAt: "2026-09-18T10:05:00.000Z",
+ revision: 3,
+ allowedDecisions: ["approve", "reject"],
+ allowedPermissionModes: ["default"],
+ };
+ bridge.handle(makeEnvelope({ kind: "approval.requested", payload: { ...base, id: "p-1", kind: "plan" } }));
+ bridge.handle(makeEnvelope({ kind: "approval.requested", payload: { ...base, id: "g-1", kind: "goal" } }));
+ assert.equal(events.length, 0);
+});
+
+test("input.requested synthesizes an asktool_request keyed by the RACP input id", () => {
+ const { bridge, events } = collect();
+ bridge.handle(
+ makeEnvelope({
+ kind: "input.requested",
+ payload: {
+ id: "input-42",
+ sessionId: HOST_SESSION_ID,
+ turnId: "turn-1",
+ expiresAt: "2026-09-18T10:05:00.000Z",
+ agentName: "codex",
+ parentToolCallId: "tc-parent",
+ questions: [
+ { id: "q1", question: "which?", options: ["a", "b"], multiSelect: false },
+ ],
+ },
+ }),
+ );
+ const request = events[0].payload.event.request;
+ assert.equal(events[0].payload.event.type, "asktool_request");
+ assert.equal(request.requestId, "input-42");
+ assert.equal(request.sessionId, REMOTE_SESSION_ID);
+ assert.equal(request.toolCallId, "tc-parent");
+ assert.equal(request.questions.length, 1);
+ assert.equal(request.questions[0].multiSelect, false);
+});
+
+test("terminal and resync kinds are silently dropped in Stage 2 — later stages own them", () => {
+ const { bridge, events } = collect();
+ bridge.handle(makeEnvelope({ kind: "terminal.output", payload: {} }));
+ bridge.handle(makeEnvelope({ kind: "terminal.changed", payload: {} }));
+ bridge.handle(makeEnvelope({ kind: "resync.required", payload: {} }));
+ bridge.handle(makeEnvelope({ kind: "approval.resolved", payload: {} }));
+ bridge.handle(makeEnvelope({ kind: "input.resolved", payload: {} }));
+ assert.equal(events.length, 0);
+});
+
+test("host.changed does not emit — the desktop has no host status surface yet", () => {
+ const { bridge, events, lifecycle } = collect();
+ bridge.handle(
+ makeEnvelope({ scope: "host", kind: "host.changed", payload: { host: { id: "h" } } }),
+ );
+ assert.equal(events.length, 0);
+ assert.equal(lifecycle.length, 0);
+});
+
+test("an unknown kind stays quiet — the bridge never throws on unfamiliar events", () => {
+ const { bridge, events, warnings } = collect();
+ bridge.handle(makeEnvelope({ kind: "made.up.kind", payload: {} }));
+ assert.equal(events.length, 0);
+ assert.equal(warnings.length, 0);
+});