Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
feat(remote): coordinate router registration for a remote host
vastsacababa43f87d
diff --git a/apps/desktop/electron/main/remote/remote-host-connection.ts b/apps/desktop/electron/main/remote/remote-host-connection.tsnew file mode 100644index 000000000..174832f12--- /dev/null+++ b/apps/desktop/electron/main/remote/remote-host-connection.ts@@ -0,0 +1,152 @@+/**+ * A live remote host: one desktop-side coordinator per paired `pi-host`. Owns+ * the {@link BackendRouter} registrations for that host's sessions, subscribes+ * to the host's RACP event streams, and pipes them through the event bridge+ * onto the renderer's IPC events. Ownership of the transport itself stays+ * with the caller (Stage 3b builds it around a real {@link RacpClient}); this+ * layer only speaks the two interfaces {@link RemoteHostClient} exposes.+ *+ * Compatibility: while no connection has {@link open}ed, the router has no+ * remote backends registered, so every renderer call still hits the local+ * handler byte-for-byte. Failure of a remote host — network drop, protocol+ * mismatch — never escalates into a local regression: `close()` unregisters+ * every session and the fallback route resumes.+ */+import type { RacpEventEnvelope, RacpSession } from "@pi-desktop/shared";+import type { BackendRouter, RemoteBackend } from "./backend-router.js";+import { makeRemoteSessionId } from "./backend-router.js";+import { createRemoteBackend, type RemoteRacpClient } from "./remote-backend.js";+import {+ createRemoteEventBridge,+ type RemoteEventBridge,+ type RemoteLifecycleEvent,+} from "./remote-event-bridge.js";++/**+ * The transport surface this connection needs. {@link RemoteRacpClient} covers+ * the request half; {@link subscribe} bridges RACP's single-callback+ * {@link RacpClient.onEvent} into a multiple-listener seam for tests.+ */+export type RemoteHostClient = RemoteRacpClient & {+ /** Subscribe to raw RACP envelopes. The returned function detaches this listener. */+ subscribe(listener: (envelope: RacpEventEnvelope) => void): () => void;+};++export type RemoteHostConnectionOptions = {+ hostKey: string;+ client: RemoteHostClient;+ router: BackendRouter;+ /** Dispatch a local IPC event to the renderer. */+ emit: (channel: string, payload: unknown) => void;+ /** Optional deterministic request-id source; forwarded to the backend. */+ newRequestId?: () => string;+ /** Optional structured log; defaults to a no-op. */+ log?: (level: "warn" | "error", message: string, data?: unknown) => void;+};++export interface RemoteHostConnection {+ readonly hostKey: string;+ /**+ * List the host's sessions, register a backend for each, then subscribe to+ * host-scope and per-session RACP event streams. Idempotent: a second call+ * on an open connection is a no-op.+ */+ open(): Promise<void>;+ /**+ * Detach the event subscription, unregister every session, and drop internal+ * state. Idempotent: closing twice is a no-op. The underlying transport is+ * the caller's responsibility.+ */+ close(): Promise<void>;+}++type SessionListResponse = { sessions: RacpSession[] };++export function createRemoteHostConnection(+ options: RemoteHostConnectionOptions,+): RemoteHostConnection {+ const { hostKey, client, router, emit } = options;+ const log = options.log ?? (() => undefined);+ const backend: RemoteBackend = createRemoteBackend({+ hostKey,+ client,+ ...(options.newRequestId ? { newRequestId: options.newRequestId } : {}),+ });++ const registered = new Set<string>();+ let bridge: RemoteEventBridge | null = null;+ let unsubscribe: (() => void) | null = null;+ let opened = false;++ const registerSession = async (hostSessionId: string): Promise<void> => {+ const remoteSessionId = makeRemoteSessionId(hostKey, hostSessionId);+ if (registered.has(remoteSessionId)) return;+ router.registerBackend(remoteSessionId, backend);+ registered.add(remoteSessionId);+ try {+ await client.request("events/subscribe", { scope: "session", sessionId: hostSessionId });+ } catch (error) {+ // A session-scope subscribe failure keeps the backend registered; the+ // renderer can still fetch snapshot/history via request paths, and+ // Stage 3b's reconnect logic will retry the stream. Errors that must+ // surface to the user go through the RacpClient state channel instead.+ log("warn", `events/subscribe failed for session ${hostSessionId}`, error);+ }+ };++ const unregisterSession = (hostSessionId: string): void => {+ const remoteSessionId = makeRemoteSessionId(hostKey, hostSessionId);+ if (!registered.delete(remoteSessionId)) return;+ router.unregisterBackend(remoteSessionId);+ };++ const handleLifecycle = (event: RemoteLifecycleEvent): void => {+ if (event.kind === "session.created") {+ void registerSession(event.hostSessionId);+ return;+ }+ if (event.kind === "session.archived") {+ unregisterSession(event.hostSessionId);+ }+ };++ return {+ hostKey,+ async open() {+ if (opened) return;+ opened = true;+ bridge = createRemoteEventBridge({+ hostKey,+ emit,+ onLifecycle: handleLifecycle,+ log: (level, message, data) => log(level, message, data),+ });+ unsubscribe = client.subscribe((envelope) => bridge?.handle(envelope));+ // Subscribing to host scope BEFORE listing sessions closes the race: any+ // `session.created` a peer emits between the two calls arrives as an+ // event and is handled by the lifecycle path (idempotent register).+ try {+ await client.request("events/subscribe", { scope: "host" });+ } catch (error) {+ log("warn", "events/subscribe host scope failed", error);+ }+ let response: SessionListResponse;+ try {+ response = await client.request<SessionListResponse>("session/list");+ } catch (error) {+ log("error", "session/list failed; connection stays with no registered sessions", error);+ return;+ }+ await Promise.all(response.sessions.map((session) => registerSession(session.id)));+ },+ async close() {+ if (!opened) return;+ opened = false;+ unsubscribe?.();+ unsubscribe = null;+ bridge = null;+ for (const remoteSessionId of registered) router.unregisterBackend(remoteSessionId);+ registered.clear();+ },+ };+}diff --git a/apps/desktop/test/remote-host-connection.test.mjs b/apps/desktop/test/remote-host-connection.test.mjsnew file mode 100644index 000000000..f73254f99--- /dev/null+++ b/apps/desktop/test/remote-host-connection.test.mjs@@ -0,0 +1,188 @@+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 { createBackendRouter, makeRemoteSessionId } = await import(+ "../electron/main/remote/backend-router.ts"+);+const { createRemoteHostConnection } = await import(+ "../electron/main/remote/remote-host-connection.ts"+);++const HOST_KEY = "hostA";++/** A minimal RacpClient/subscribe double. Records requests and lets tests+ * push envelopes back to whichever listener attached last. */+function fakeClient({ sessions = [], requestFailures = {} } = {}) {+ const calls = [];+ let listener = null;+ return {+ calls,+ request: async (method, params) => {+ calls.push({ method, params });+ if (requestFailures[method]) throw requestFailures[method];+ if (method === "session/list") return { sessions };+ return { ok: true };+ },+ subscribe: (fn) => {+ listener = fn;+ return () => {+ if (listener === fn) listener = null;+ };+ },+ // Test-only escape hatch used to inject envelopes as if from the host.+ push(envelope) {+ if (!listener) throw new Error("no listener attached");+ listener(envelope);+ },+ hasListener: () => listener !== null,+ };+}++function makeSession(id, overrides = {}) {+ return {+ id,+ title: id,+ mode: "chat",+ status: "idle",+ planningState: "inactive",+ permissionMode: "default",+ queuedTurnIds: [],+ revision: 1,+ createdAt: "2026-09-18T10:00:00.000Z",+ updatedAt: "2026-09-18T10:00:00.000Z",+ ...overrides,+ };+}++function makeEnvelope(overrides = {}) {+ return {+ eventId: "e1",+ scope: "session",+ epoch: "epoch-1",+ revision: 1,+ kind: "item.started",+ occurredAt: "2026-09-18T10:00:00.000Z",+ payload: {},+ ...overrides,+ };+}++function setup({ sessions = [], requestFailures = {} } = {}) {+ const events = [];+ const router = createBackendRouter();+ const client = fakeClient({ sessions, requestFailures });+ const conn = createRemoteHostConnection({+ hostKey: HOST_KEY,+ client,+ router,+ emit: (channel, payload) => events.push({ channel, payload }),+ newRequestId: () => "req-const",+ });+ return { conn, router, client, events };+}++test("open subscribes host scope, lists sessions, and registers a backend per session", async () => {+ const { conn, router, client } = setup({ sessions: [makeSession("s1"), makeSession("s2")] });+ await conn.open();+ const methods = client.calls.map((entry) => entry.method);+ // Host-scope subscribe fires BEFORE list; the create-race window is closed.+ assert.deepEqual(methods.slice(0, 3), ["events/subscribe", "session/list", "events/subscribe"]);+ assert.deepEqual(client.calls[0].params, { scope: "host" });+ const perSessionSubscribeParams = client.calls+ .filter((entry) => entry.method === "events/subscribe" && entry.params.scope === "session")+ .map((entry) => entry.params.sessionId)+ .sort();+ assert.deepEqual(perSessionSubscribeParams, ["s1", "s2"]);+ // The router now resolves both session ids to the remote backend.+ const backend = router.resolveBackend(IPC.invoke.sessionGet, [+ { id: makeRemoteSessionId(HOST_KEY, "s1") },+ ]);+ assert.ok(backend, "router must have a backend for s1");+ assert.ok(+ router.resolveBackend(IPC.invoke.sessionGet, [{ id: makeRemoteSessionId(HOST_KEY, "s2") }]),+ );+});++test("open is idempotent — a second call does not re-subscribe or re-register", async () => {+ const { conn, client } = setup({ sessions: [makeSession("s1")] });+ await conn.open();+ const first = client.calls.length;+ await conn.open();+ assert.equal(client.calls.length, first);+});++test("a session.created event registers a fresh backend and refreshes the sidebar", async () => {+ const { conn, router, client, events } = setup({ sessions: [] });+ await conn.open();+ const newRemoteId = makeRemoteSessionId(HOST_KEY, "s-new");+ client.push(+ makeEnvelope({+ scope: "host",+ kind: "session.created",+ payload: { session: { id: "s-new", title: "new" } },+ }),+ );+ assert.ok(+ router.resolveBackend(IPC.invoke.sessionGet, [{ id: newRemoteId }]),+ "s-new must have a registered backend after session.created",+ );+ const sidebarNotice = events.find(+ (event) => event.channel === IPC.event.sessionsChanged && event.payload.selectSessionId === newRemoteId,+ );+ assert.ok(sidebarNotice, "session.created must emit a sessionsChanged notice for the sidebar");+});++test("a session.archived event unregisters the backend and lets the id fall through", async () => {+ const s1 = makeSession("s1");+ const { conn, router, client } = setup({ sessions: [s1] });+ await conn.open();+ const remoteId = makeRemoteSessionId(HOST_KEY, "s1");+ assert.ok(router.resolveBackend(IPC.invoke.sessionGet, [{ id: remoteId }]));+ client.push(+ makeEnvelope({+ scope: "host",+ kind: "session.archived",+ payload: { session: { id: "s1" } },+ }),+ );+ assert.equal(router.resolveBackend(IPC.invoke.sessionGet, [{ id: remoteId }]), null);+});++test("close detaches the listener and unregisters every session", async () => {+ const { conn, router, client } = setup({ sessions: [makeSession("s1"), makeSession("s2")] });+ await conn.open();+ await conn.close();+ assert.equal(client.hasListener(), false);+ assert.equal(+ router.resolveBackend(IPC.invoke.sessionGet, [{ id: makeRemoteSessionId(HOST_KEY, "s1") }]),+ null,+ );+});++test("close is idempotent and safe to call before open", async () => {+ const { conn } = setup();+ await conn.close();+ await conn.open();+ await conn.close();+ await conn.close();+});++test("session/list failure leaves the connection registered for nothing but does not throw", async () => {+ const { conn, router, client } = setup({+ sessions: [makeSession("s1")],+ requestFailures: { "session/list": new Error("no route to host") },+ });+ await conn.open();+ assert.equal(+ router.resolveBackend(IPC.invoke.sessionGet, [{ id: makeRemoteSessionId(HOST_KEY, "s1") }]),+ null,+ );+ assert.equal(client.hasListener(), true);+});