Skip to content

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

feat(remote): add the backend-router seam for remote-host sessions

vastsa78decd490a4c
diff --git a/apps/desktop/electron/main/bootstrap/startup.ts b/apps/desktop/electron/main/bootstrap/startup.ts
index 004348e73..c7de5085d 100644
--- a/apps/desktop/electron/main/bootstrap/startup.ts
+++ b/apps/desktop/electron/main/bootstrap/startup.ts
@@ -17,6 +17,7 @@ import {
import { applyNetworkProxyFromAppSettings } from "../network-proxy";
import { readCloseBehavior } from "../window-preferences";
import { createAgentHostBridge, type AgentHostBridge } from "../agent-host-bridge";
+import { createBackendRouter, type BackendRouter } from "../remote/backend-router";
import {
createMcpControlController,
McpControlServer,
@@ -40,6 +41,7 @@ export type StartupState = {
applicationBooted: boolean;
closeBehavior: CloseBehavior;
agentHostBridge: AgentHostBridge | null;
+ backendRouter: BackendRouter | null;
desktopControl: McpControlController | null;
mcpControl: McpControlServer | null;
};
@@ -158,6 +160,15 @@ export function registerApplicationStartup(deps: StartupDependencies): void {
// not race the renderer allocation just because backend startup was slow.
prewarmPluginLauncher();
const invokeIpc = registerIpc();
+ // The backend router is the single seam that forwards a renderer IPC call
+ // to a paired remote host; with no remote session registered it returns
+ // ROUTE_LOCAL and the local handler runs unchanged. Assigned before the
+ // first window can issue IPC. Remote host connections register their
+ // sessions here once paired (later stages).
+ state.backendRouter = createBackendRouter({
+ log: (level, message, data) =>
+ logger.app("runtime", level, message, { data: data === undefined ? undefined : String(data) }),
+ });
state.agentHostBridge = createAgentHostBridge({
invoke: invokeIpc,
channels: IPC.invoke,
diff --git a/apps/desktop/electron/main/index.ts b/apps/desktop/electron/main/index.ts
index 480fbeec7..8b06e0ad9 100644
--- a/apps/desktop/electron/main/index.ts
+++ b/apps/desktop/electron/main/index.ts
@@ -1255,6 +1255,7 @@ function registerIpc() {
getHost: () => host,
getSidecar: () => sidecar,
getAgentHostBridge: () => agentHostBridge,
+ getBackendRouter: () => startupState.backendRouter,
getNotificationViewingSessionId: () => notificationViewingSessionId,
setNotificationViewingSessionId: (sessionId: string | null) => {
notificationViewingSessionId = sessionId;
@@ -1369,6 +1370,7 @@ const startupState: StartupState = {
set agentHostBridge(value) {
agentHostBridge = value;
},
+ backendRouter: null,
get desktopControl() {
return desktopControl;
},
diff --git a/apps/desktop/electron/main/ipc/register.ts b/apps/desktop/electron/main/ipc/register.ts
index 99fd44992..ea326fb24 100644
--- a/apps/desktop/electron/main/ipc/register.ts
+++ b/apps/desktop/electron/main/ipc/register.ts
@@ -4,6 +4,7 @@ import { err, ErrorCodes, IPC, ok, type Result } from "@pi-desktop/shared";
import type { AgentHostBridge } from "../agent-host-bridge";
import type { AgentSidecar } from "../agent-sidecar";
import type { HostProcess } from "../host-process";
+import { ROUTE_LOCAL, type BackendRouter } from "../remote/backend-router";
import { registerAgentExtensionIpc } from "../agent-extensions-ipc";
import { registerAgentIpc } from "./agent-ipc";
import { registerAppIpc } from "./app-ipc";
@@ -33,6 +34,13 @@ export type RegisterIpcDependencies = {
getHost: () => HostProcess | null;
getSidecar: () => AgentSidecar | null;
getAgentHostBridge: () => AgentHostBridge | null;
+ /**
+ * Resolves the remote backend router once it exists. Renderer IPC calls whose
+ * session is owned by a paired remote host are forwarded through it; every
+ * other call — including all internal invokes — runs the local handler
+ * unchanged. Null until the router is wired (and in tests).
+ */
+ getBackendRouter?: () => BackendRouter | null;
getNotificationViewingSessionId: () => string | null;
setNotificationViewingSessionId: (sessionId: string | null) => void;
activeUserSubagentDocuments: (...args: any[]) => Promise<any>;
@@ -59,6 +67,7 @@ export function registerIpcHandlers(dependencies: RegisterIpcDependencies) {
getHost,
getSidecar,
getAgentHostBridge,
+ getBackendRouter,
getNotificationViewingSessionId,
setNotificationViewingSessionId,
getPluginLauncherWindow,
@@ -140,7 +149,20 @@ export function registerIpcHandlers(dependencies: RegisterIpcDependencies) {
const ipcHandlers = new Map<string, (...args: any[]) => Promise<any>>();
const handle = (channel: string, fn: (...args: any[]) => Promise<any>) => {
ipcHandlers.set(channel, fn);
- ipcMain.handle(channel, async (_event, ...args) => wrap(() => fn(...args)));
+ // The interception seam for remote-host routing: a renderer call whose
+ // session is owned by a paired remote host is served over RACP-WS; every
+ // other call (and every internal invoke, which never reaches this wrapper)
+ // runs the existing local handler byte-for-byte unchanged.
+ ipcMain.handle(channel, async (_event, ...args) =>
+ wrap(async () => {
+ const router = getBackendRouter?.();
+ if (router) {
+ const outcome = await router.route(channel, args);
+ if (outcome !== ROUTE_LOCAL) return outcome.value;
+ }
+ return fn(...args);
+ }),
+ );
};
const handleWithEvent = (
channel: string,
diff --git a/apps/desktop/electron/main/remote/backend-router.ts b/apps/desktop/electron/main/remote/backend-router.ts
new file mode 100644
index 000000000..3f76bccba
--- /dev/null
+++ b/apps/desktop/electron/main/remote/backend-router.ts
@@ -0,0 +1,131 @@
+/**
+ * Backend router: the single seam that decides whether a renderer IPC call is
+ * served by this desktop's local host-core (the default, byte-for-byte
+ * unchanged) or forwarded to a paired remote `pi-host` over RACP-WS.
+ *
+ * The frozen architecture keeps this out of the per-domain IPC handlers and out
+ * of the God-modules: `register.ts` consults `route()` from inside its `handle`
+ * wrapper, and everything remote lives under `electron/main/remote/*`. A
+ * session becomes remote only once a {@link RemoteBackend} is registered for its
+ * id; until then — and for every local or `native-pi:` session — the router
+ * returns {@link ROUTE_LOCAL} and the existing local handler runs.
+ *
+ * Renderer-visible session ids for remote sessions are namespaced
+ * `remote:<hostKey>:<hostSessionId>`, mirroring the proven `native-pi:` prefix
+ * (session-ipc.ts). The renderer never parses the prefix; it is resolved here.
+ */
+
+/** Sentinel telling the caller to run the existing local handler unchanged. */
+export const ROUTE_LOCAL = Symbol("pi-desktop.route-local");
+
+/** Namespaced-id prefix for sessions owned by a remote host. */
+const REMOTE_PREFIX = "remote:";
+
+/** A registered remote host's session, addressed by its renderer-visible id. */
+export interface RemoteBackend {
+ /**
+ * Whether this backend can serve `channel`. A channel the remote profile does
+ * not cover (e.g. a desktop-only setting) falls back to the local handler so
+ * the renderer keeps working while the session's transcript stays remote.
+ */
+ handles(channel: string): boolean;
+ /** Serve the call remotely, returning the value the renderer expects. */
+ invoke(channel: string, args: readonly unknown[]): Promise<unknown>;
+}
+
+/** Result of {@link BackendRouter.route}: run locally, or a served remote value. */
+export type RouteOutcome =
+ | typeof ROUTE_LOCAL
+ | { readonly remote: true; readonly value: unknown };
+
+export interface BackendRouter {
+ /** Bind a renderer-visible session id to the backend that owns it. */
+ registerBackend(sessionId: string, backend: RemoteBackend): void;
+ /** Release a session id (host disconnect, session delete, kill switch). */
+ unregisterBackend(sessionId: string): void;
+ /** The backend that should serve `(channel, args)`, or null for local. */
+ resolveBackend(channel: string, args: readonly unknown[]): RemoteBackend | null;
+ /** Route a renderer IPC call. */
+ route(channel: string, args: readonly unknown[]): Promise<RouteOutcome>;
+}
+
+export type BackendRouterOptions = {
+ /** Optional structured log for routing faults; defaults to a no-op. */
+ log?: (level: "warn" | "error", message: string, data?: unknown) => void;
+};
+
+/** Build the namespaced id the renderer sees for a remote session. */
+export function makeRemoteSessionId(hostKey: string, hostSessionId: string): string {
+ if (hostKey.includes(":")) {
+ throw Object.assign(new Error("remote hostKey must not contain ':'"), {
+ errorCode: "INVALID_ARGUMENT",
+ });
+ }
+ return `${REMOTE_PREFIX}${hostKey}:${hostSessionId}`;
+}
+
+export function isRemoteSessionId(sessionId: unknown): sessionId is string {
+ return typeof sessionId === "string" && sessionId.startsWith(REMOTE_PREFIX);
+}
+
+/** Split a `remote:<hostKey>:<hostSessionId>` id back into its parts. */
+export function parseRemoteSessionId(
+ sessionId: string,
+): { hostKey: string; hostSessionId: string } | null {
+ if (!sessionId.startsWith(REMOTE_PREFIX)) return null;
+ const rest = sessionId.slice(REMOTE_PREFIX.length);
+ const sep = rest.indexOf(":");
+ if (sep <= 0 || sep === rest.length - 1) return null;
+ return { hostKey: rest.slice(0, sep), hostSessionId: rest.slice(sep + 1) };
+}
+
+/**
+ * Best-effort session id for a renderer IPC call. Desktop channels pass the
+ * session id either as the first positional argument or as `sessionId` on the
+ * first argument object; anything else has no session and is always local.
+ */
+export function sessionIdForCall(args: readonly unknown[]): string | null {
+ const first = args[0];
+ if (typeof first === "string") return isRemoteSessionId(first) ? first : null;
+ if (first && typeof first === "object") {
+ const id = (first as { sessionId?: unknown }).sessionId;
+ if (typeof id === "string" && isRemoteSessionId(id)) return id;
+ }
+ return null;
+}
+
+export function createBackendRouter(options: BackendRouterOptions = {}): BackendRouter {
+ const log = options.log ?? (() => undefined);
+ const sessionBackends = new Map<string, RemoteBackend>();
+
+ const resolveBackend = (
+ channel: string,
+ args: readonly unknown[],
+ ): RemoteBackend | null => {
+ const sessionId = sessionIdForCall(args);
+ if (!sessionId) return null;
+ const backend = sessionBackends.get(sessionId);
+ if (!backend) return null;
+ return backend.handles(channel) ? backend : null;
+ };
+
+ return {
+ registerBackend(sessionId, backend) {
+ sessionBackends.set(sessionId, backend);
+ },
+ unregisterBackend(sessionId) {
+ sessionBackends.delete(sessionId);
+ },
+ resolveBackend,
+ async route(channel, args) {
+ const backend = resolveBackend(channel, args);
+ if (!backend) return ROUTE_LOCAL;
+ try {
+ return { remote: true, value: await backend.invoke(channel, args) };
+ } catch (error) {
+ log("warn", `remote route failed for ${channel}`, error);
+ throw error;
+ }
+ },
+ };
+}
diff --git a/apps/desktop/test/remote-backend-router.test.mjs b/apps/desktop/test/remote-backend-router.test.mjs
new file mode 100644
index 000000000..a0b4754a5
--- /dev/null
+++ b/apps/desktop/test/remote-backend-router.test.mjs
@@ -0,0 +1,87 @@
+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 {
+ ROUTE_LOCAL,
+ createBackendRouter,
+ makeRemoteSessionId,
+ parseRemoteSessionId,
+ isRemoteSessionId,
+ sessionIdForCall,
+} = await import("../electron/main/remote/backend-router.ts");
+
+test("namespaces and parses remote session ids", () => {
+ const id = makeRemoteSessionId("hostA", "sess_1");
+ assert.equal(id, "remote:hostA:sess_1");
+ assert.ok(isRemoteSessionId(id));
+ assert.ok(!isRemoteSessionId("sess_1"));
+ assert.ok(!isRemoteSessionId("native-pi:codex:abc"));
+ assert.deepEqual(parseRemoteSessionId(id), { hostKey: "hostA", hostSessionId: "sess_1" });
+ // A host session id may itself contain ':'; only the first separator splits.
+ assert.deepEqual(parseRemoteSessionId("remote:hostA:a:b"), {
+ hostKey: "hostA",
+ hostSessionId: "a:b",
+ });
+ assert.equal(parseRemoteSessionId("remote:onlyhost"), null);
+ assert.equal(parseRemoteSessionId("desktop-session"), null);
+});
+
+test("rejects a hostKey containing the separator", () => {
+ assert.throws(() => makeRemoteSessionId("host:bad", "s"), /hostKey must not contain/);
+});
+
+test("sessionIdForCall reads positional and object session ids", () => {
+ const remote = makeRemoteSessionId("h", "s");
+ assert.equal(sessionIdForCall([remote]), remote);
+ assert.equal(sessionIdForCall([{ sessionId: remote }]), remote);
+ assert.equal(sessionIdForCall(["local-session"]), null);
+ assert.equal(sessionIdForCall([{ sessionId: "local-session" }]), null);
+ assert.equal(sessionIdForCall([]), null);
+ assert.equal(sessionIdForCall([42]), null);
+});
+
+test("routes locally until a backend is registered for the session", async () => {
+ const router = createBackendRouter();
+ const remote = makeRemoteSessionId("h", "s");
+ assert.equal(await router.route("session.get", [{ sessionId: remote }]), ROUTE_LOCAL);
+
+ const calls = [];
+ router.registerBackend(remote, {
+ handles: (channel) => channel === "session.get",
+ invoke: async (channel, args) => {
+ calls.push([channel, args]);
+ return { id: remote, source: "remote" };
+ },
+ });
+
+ const outcome = await router.route("session.get", [{ sessionId: remote }]);
+ assert.notEqual(outcome, ROUTE_LOCAL);
+ assert.deepEqual(outcome, { remote: true, value: { id: remote, source: "remote" } });
+ assert.equal(calls.length, 1);
+
+ // A channel the backend does not cover falls back to local.
+ assert.equal(await router.route("settings.get", [{ sessionId: remote }]), ROUTE_LOCAL);
+ // A local session id is never routed even after a remote backend exists.
+ assert.equal(await router.route("session.get", [{ sessionId: "local" }]), ROUTE_LOCAL);
+
+ router.unregisterBackend(remote);
+ assert.equal(await router.route("session.get", [{ sessionId: remote }]), ROUTE_LOCAL);
+});
+
+test("route surfaces a backend failure to the caller", async () => {
+ const router = createBackendRouter();
+ const remote = makeRemoteSessionId("h", "s");
+ router.registerBackend(remote, {
+ handles: () => true,
+ invoke: async () => {
+ throw Object.assign(new Error("host gone"), { errorCode: "HOST_DISCONNECTED" });
+ },
+ });
+ await assert.rejects(() => router.route("session.get", [remote]), /host gone/);
+});
diff --git a/docs/spec/03-runtime/08-error-codes.md b/docs/spec/03-runtime/08-error-codes.md
index b74a86e98..f2af47e88 100644
--- a/docs/spec/03-runtime/08-error-codes.md
+++ b/docs/spec/03-runtime/08-error-codes.md
@@ -274,6 +274,29 @@ carries a marker naming which end survived and where the rest is, or reports
the bounded window in sibling result fields
(see [16-tool-result-limits](16-tool-result-limits.md)).
+### 3.8 Remote control (RACP-WS / SSH bootstrap)
+
+Emitted by the desktop's remote-host client and the `pi-host` server when a
+session lives on a paired remote machine driven over `RACP-WS`
+(see [19-remote-agent-control-protocol](19-remote-agent-control-protocol.md),
+[../05-security/02-remote-control-security](../05-security/02-remote-control-security.md),
+ADR 0284). The renderer never sees the local/remote split beyond a badge; these
+codes surface through the same error object as any other call.
+
+| code | retriable | meaning |
+|---|---|---|
+| `HOST_DISCONNECTED` | yes | the remote host connection dropped; in-flight calls are rejected and the client reconnects and resubscribes by cursor |
+| `HOST_BOOTSTRAP_FAILED` | no | provisioning the remote `pi-host` over SSH failed (download, checksum mismatch, or `install.sh`); `details.reason` names the stage |
+| `HOST_VERSION_MISMATCH` | no | the remote `pi-host` version does not match the desktop; the desktop refuses to drive an incompatible host |
+| `REMOTE_AUTH_FAILED` | no | the device or pairing token was rejected on the RACP-WS upgrade |
+| `REMOTE_CONNECTION_FAILED` | yes | the RACP-WS transport could not connect (non-loopback URL, refused socket) |
+| `REMOTE_FORWARD_FAILED` | yes | the SSH loopback port forward could not be established |
+| `REMOTE_PATH_NOT_FOUND` | no | a remote project/workspace path does not exist on the host |
+| `REMOTE_PATH_FORBIDDEN` | no | a remote path is outside the host's permitted roots |
+| `PAIRING_FAILED` | no | `connection/pair` could not mint a device credential |
+| `PAIRING_TOKEN_EXPIRED` | no | the single-use pairing token expired before pairing completed |
+| `CAPABILITY_UNAVAILABLE` | no | an operation was requested for a capability the host advertised as unavailable (e.g. attachments, tool relay) |
+
## 4. Mapping rules
### Host RPC numeric → AppError.code
diff --git a/docs/zh-CN/spec/03-runtime/08-error-codes.md b/docs/zh-CN/spec/03-runtime/08-error-codes.md
index cfaeacf51..f8b264d92 100644
--- a/docs/zh-CN/spec/03-runtime/08-error-codes.md
+++ b/docs/zh-CN/spec/03-runtime/08-error-codes.md
@@ -270,6 +270,29 @@ reveal 不并入任何行,必须重新读取。
同级结果字段中的有界窗口
(请参阅 [16-工具-结果-限制](/zh-CN/spec/03-runtime/16-tool-result-limits))。
+### 3.8 远程控制(RACP-WS / SSH 引导)
+
+当会话位于经 `RACP-WS` 驱动的已配对远程主机上时,由桌面端的远程主机客户端与
+`pi-host` 服务端发出(参见
+[19-远程代理控制协议](/zh-CN/spec/03-runtime/19-remote-agent-control-protocol)、
+[../05-security/02-remote-control-security](/zh-CN/spec/05-security/02-remote-control-security)、
+ADR 0284)。渲染进程除了一个标识徽章外看不到本地/远程之分;这些码通过与其他调用
+相同的错误对象浮现。
+
+| 码 | 可重试 | 含义 |
+|---|---|---|
+| `HOST_DISCONNECTED` | 是 | 远程主机连接断开;进行中的调用被拒绝,客户端按游标重连并重新订阅 |
+| `HOST_BOOTSTRAP_FAILED` | 否 | 经 SSH 配置远程 `pi-host` 失败(下载、校验和不匹配或 `install.sh`);`details.reason` 指明阶段 |
+| `HOST_VERSION_MISMATCH` | 否 | 远程 `pi-host` 版本与桌面不匹配;桌面拒绝驱动不兼容的主机 |
+| `REMOTE_AUTH_FAILED` | 否 | 设备或配对令牌在 RACP-WS 升级时被拒 |
+| `REMOTE_CONNECTION_FAILED` | 是 | RACP-WS 传输无法连接(非回环 URL、套接字被拒) |
+| `REMOTE_FORWARD_FAILED` | 是 | 无法建立 SSH 回环端口转发 |
+| `REMOTE_PATH_NOT_FOUND` | 否 | 远程项目/工作区路径在主机上不存在 |
+| `REMOTE_PATH_FORBIDDEN` | 否 | 远程路径在主机允许的根之外 |
+| `PAIRING_FAILED` | 否 | `connection/pair` 无法铸造设备凭据 |
+| `PAIRING_TOKEN_EXPIRED` | 否 | 一次性配对令牌在配对完成前已过期 |
+| `CAPABILITY_UNAVAILABLE` | 否 | 请求的操作对应主机声明为不可用的能力(如附件、工具中继) |
+
## 4. 映射规则
### 主机 RPC 数字 → AppError.code
diff --git a/packages/shared/src/types/sessions.ts b/packages/shared/src/types/sessions.ts
index 812eb9f98..bb7f24724 100644
--- a/packages/shared/src/types/sessions.ts
+++ b/packages/shared/src/types/sessions.ts
@@ -5,7 +5,17 @@ import type { PermissionMode } from "./permissions.js";
import type { UiMessage } from "./messages.js";
import type { PlanningState } from "./plans.js";
-export type SessionSource = "desktop" | "pi-native";
+/**
+ * Which authority owns a session's transcript.
+ *
+ * - `desktop`: this desktop's own host-core (the default; older hosts omit the
+ * field and it is normalized to `desktop`).
+ * - `pi-native`: an imported Pi CLI session, read-mostly.
+ * - `remote`: a session that lives on a paired remote `pi-host` and is driven
+ * over RACP-WS. The renderer treats it exactly like a `desktop` session apart
+ * from a display badge; the local/remote split is resolved in Electron main.
+ */
+export type SessionSource = "desktop" | "pi-native" | "remote";
export type SessionCapabilities = {
canPrompt: boolean;