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): add RACP client adapter and encrypted host registry
vastsa35dbd1998be6
diff --git a/apps/desktop/electron/main/remote/racp-remote-host-client.ts b/apps/desktop/electron/main/remote/racp-remote-host-client.tsnew file mode 100644index 000000000..704f22b6a--- /dev/null+++ b/apps/desktop/electron/main/remote/racp-remote-host-client.ts@@ -0,0 +1,91 @@+/**+ * RACP-WS-backed {@link RemoteHostClient}: adapts the single-callback+ * `RacpClient.onEvent` seam into the multi-listener `subscribe()` shape+ * `RemoteHostConnection` consumes. This is the only file in+ * `electron/main/remote/` that speaks the `@pi-desktop/racp` protocol+ * package; everything above it is transport-agnostic.+ *+ * Ownership stays inside Electron Main. The transport factory is injected —+ * production wires it to {@link wsClientTransport} against a paired host, and+ * tests wire it to the in-memory `MemoryLink` from+ * `packages/racp/src/test-harness.ts` so the adapter exercises the real+ * `RacpClient` state machine without a socket.+ */+import { RacpClient, type ClientTransportFactory, type RacpClientState } from "@pi-desktop/racp";+import type { RacpEventEnvelope } from "@pi-desktop/shared";+import type { RemoteHostClient } from "./remote-host-connection.js";++export type RacpRemoteHostClientOptions = {+ transport: ClientTransportFactory;+ /** Identity sent in `connection/initialize`; the host records it as the device label. */+ clientInfo: { name: string; version: string };+ /** Deadline for a single request; the RACP default of 15s is used when omitted. */+ requestTimeoutMs?: number;+ /** Reconnect policy; the RACP client stays disconnected when omitted. */+ reconnect?: {+ enabled: boolean;+ baseDelayMs?: number;+ maxDelayMs?: number;+ maxAttempts?: number;+ };+ /** Optional structured log; defaults to a no-op. */+ log?: (level: "info" | "warn", message: string, data?: Record<string, unknown>) => void;+};++export type RacpRemoteHostClient = {+ /** The multi-listener {@link RemoteHostClient} the connection module consumes. */+ readonly client: RemoteHostClient;+ /** Underlying RACP client state, for boot diagnostics and the future host card. */+ readonly state: () => RacpClientState;+ /** Open the transport and initialize the RACP session. */+ connect(): Promise<void>;+ /** Close the transport; safe to call before {@link connect} and after failure. */+ close(): Promise<void>;+};++/**+ * The adapter multiplexes {@link RacpClient.onEvent} — a single-slot callback+ * — into the `subscribe()` API {@link RemoteHostConnection} expects. Fan-out+ * is intentional: Stage 5 (terminal) and Stage 3b (resync watchdog) will+ * attach their own listeners on the same client.+ */+export function createRacpRemoteHostClient(+ options: RacpRemoteHostClientOptions,+): RacpRemoteHostClient {+ const listeners = new Set<(envelope: RacpEventEnvelope) => void>();+ const racp = new RacpClient({+ transport: options.transport,+ client: options.clientInfo,+ onEvent: (envelope) => {+ for (const listener of listeners) {+ try {+ listener(envelope);+ } catch (error) {+ options.log?.("warn", "remote event listener threw", { error: String(error) });+ }+ }+ },+ ...(options.requestTimeoutMs !== undefined ? { requestTimeoutMs: options.requestTimeoutMs } : {}),+ ...(options.reconnect ? { reconnect: options.reconnect } : {}),+ ...(options.log ? { log: options.log } : {}),+ });+ const client: RemoteHostClient = {+ request: (method, params) => racp.request(method, params),+ subscribe(listener) {+ listeners.add(listener);+ return () => {+ listeners.delete(listener);+ };+ },+ };+ return {+ client,+ state: () => racp.state,+ async connect() {+ await racp.connect();+ },+ async close() {+ await racp.close();+ },+ };+}diff --git a/apps/desktop/electron/main/remote/remote-host-registry.ts b/apps/desktop/electron/main/remote/remote-host-registry.tsnew file mode 100644index 000000000..67f175016--- /dev/null+++ b/apps/desktop/electron/main/remote/remote-host-registry.ts@@ -0,0 +1,177 @@+/**+ * Persisted list of paired remote hosts. Each record binds one host key to+ * the URL of its RACP-WS endpoint and the encrypted device token the host+ * issued during pairing. The file lives at `<dataDir>/remote-hosts.json` and+ * the token bytes are encrypted with Electron's `safeStorage` before write;+ * on read they decrypt back through the same interface, so a stolen file+ * without OS keychain access reveals only the URL and label.+ *+ * The registry is injected with an {@link EncryptionPort} rather than+ * imported from `electron` so it stays unit-testable in `node --test`; the+ * boot layer wires the real `safeStorage.encryptString` /+ * `safeStorage.decryptString` pair.+ */+import { readFile, rename, unlink, writeFile } from "node:fs/promises";+import { join } from "node:path";++/**+ * Byte-in, byte-out encryption. `encryptString` returns a Buffer of+ * ciphertext; `decryptString` recovers the plaintext from the same bytes.+ * Both throw when the underlying keychain is unavailable — the registry+ * surfaces the failure to the caller.+ */+export interface EncryptionPort {+ isAvailable(): boolean;+ encryptString(plaintext: string): Buffer;+ decryptString(ciphertext: Buffer): string;+}++/** One paired host as it lives on disk (token stays encrypted at rest). */+export type RemoteHostRecord = {+ /** Stable id used in `remote:<hostKey>:<...>` renderer session ids. */+ hostKey: string;+ /** Human label; shown in a future host list. */+ label: string;+ /** `ws://…` or `wss://…` URL for the RACP endpoint. */+ url: string;+ /** Device token issued at pairing, presented on every reconnect. */+ deviceToken: string;+ /** Room for later fields (roles, protocol hints) without a schema bump. */+ metadata?: Record<string, unknown>;+};++/** The on-disk record: the plaintext deviceToken is replaced with base64+ * ciphertext + version byte, so a token cannot be recovered without the+ * matching safeStorage keychain. */+type SerializedRecord = {+ hostKey: string;+ label: string;+ url: string;+ /** Base64 of the `safeStorage.encryptString` output. */+ encryptedDeviceToken: string;+ metadata?: Record<string, unknown>;+};++type SerializedFile = {+ version: 1;+ hosts: SerializedRecord[];+};++export type RemoteHostRegistryOptions = {+ dataDir: string;+ encryption: EncryptionPort;+ /** File name inside `dataDir`; defaults to `remote-hosts.json`. */+ fileName?: string;+ /** Optional structured log for I/O and decrypt failures. */+ log?: (level: "warn" | "error", message: string, data?: unknown) => void;+};++export interface RemoteHostRegistry {+ /** Every host record on disk with a decryptable token, in file order. */+ list(): Promise<RemoteHostRecord[]>;+ /** Add or replace the record for `record.hostKey` and flush. */+ upsert(record: RemoteHostRecord): Promise<void>;+ /** Remove one host key; a missing key is a no-op. */+ remove(hostKey: string): Promise<void>;+}++const CURRENT_VERSION = 1;++function fileNotFound(error: unknown): boolean {+ return typeof error === "object" && error !== null && (error as { code?: string }).code === "ENOENT";+}++export function createRemoteHostRegistry(+ options: RemoteHostRegistryOptions,+): RemoteHostRegistry {+ const log = options.log ?? (() => undefined);+ const filePath = join(options.dataDir, options.fileName ?? "remote-hosts.json");++ const readFileContents = async (): Promise<SerializedFile> => {+ try {+ const raw = await readFile(filePath, "utf8");+ const parsed = JSON.parse(raw) as Partial<SerializedFile>;+ if (parsed.version !== CURRENT_VERSION || !Array.isArray(parsed.hosts)) {+ log("warn", "remote-hosts.json shape rejected; treating as empty", { file: filePath });+ return { version: CURRENT_VERSION, hosts: [] };+ }+ return { version: CURRENT_VERSION, hosts: parsed.hosts };+ } catch (error) {+ if (fileNotFound(error)) return { version: CURRENT_VERSION, hosts: [] };+ log("error", "remote-hosts.json read failed", { error: String(error) });+ // A corrupt file must not delete records the user cannot see; the+ // caller reads an empty list and any upsert would overwrite it.+ return { version: CURRENT_VERSION, hosts: [] };+ }+ };++ const persist = async (file: SerializedFile): Promise<void> => {+ const tmp = `${filePath}.tmp`;+ await writeFile(tmp, `${JSON.stringify(file, null, 2)}\n`, { encoding: "utf8", mode: 0o600 });+ // atomic replace — a crash leaves either the old file or the new one, never a torn write+ await rename(tmp, filePath);+ };++ return {+ async list() {+ const file = await readFileContents();+ const decoded: RemoteHostRecord[] = [];+ for (const record of file.hosts) {+ try {+ const buffer = Buffer.from(record.encryptedDeviceToken, "base64");+ const deviceToken = options.encryption.decryptString(buffer);+ decoded.push({+ hostKey: record.hostKey,+ label: record.label,+ url: record.url,+ deviceToken,+ ...(record.metadata ? { metadata: record.metadata } : {}),+ });+ } catch (error) {+ // A record we cannot decrypt (keychain moved, wrong OS user) is+ // dropped from the return: exposing an empty string as the token+ // would just cause auth failures downstream and the caller has no+ // way to distinguish that from a real revocation.+ log("warn", "remote host record could not be decrypted; skipping", {+ hostKey: record.hostKey,+ error: String(error),+ });+ }+ }+ return decoded;+ },+ async upsert(record) {+ if (!options.encryption.isAvailable()) {+ throw Object.assign(new Error("safeStorage unavailable; refusing to write remote host token"), {+ errorCode: "REMOTE_STORAGE_UNAVAILABLE",+ });+ }+ const file = await readFileContents();+ const ciphertext = options.encryption.encryptString(record.deviceToken).toString("base64");+ const serialized: SerializedRecord = {+ hostKey: record.hostKey,+ label: record.label,+ url: record.url,+ encryptedDeviceToken: ciphertext,+ ...(record.metadata ? { metadata: record.metadata } : {}),+ };+ const next = file.hosts.filter((existing) => existing.hostKey !== record.hostKey);+ next.push(serialized);+ await persist({ version: CURRENT_VERSION, hosts: next });+ },+ async remove(hostKey) {+ const file = await readFileContents();+ const next = file.hosts.filter((existing) => existing.hostKey !== hostKey);+ if (next.length === file.hosts.length) return;+ if (next.length === 0) {+ try {+ await unlink(filePath);+ } catch (error) {+ if (!fileNotFound(error)) log("warn", "remote-hosts.json unlink failed", { error: String(error) });+ }+ return;+ }+ await persist({ version: CURRENT_VERSION, hosts: next });+ },+ };+}diff --git a/apps/desktop/package.json b/apps/desktop/package.jsonindex e22f8bf46..7e3a7315b 100644--- a/apps/desktop/package.json+++ b/apps/desktop/package.json@@ -41,6 +41,7 @@"@pi-desktop/i18n": "workspace:*","@pi-desktop/plugin-devkit": "workspace:*","@pi-desktop/plugin-sdk": "workspace:*",+ "@pi-desktop/racp": "workspace:*","@pi-desktop/shared": "workspace:*","@tailwindcss/vite": "^4.3.3","@types/react": "^19.2.18",diff --git a/apps/desktop/test/racp-remote-host-client.test.mjs b/apps/desktop/test/racp-remote-host-client.test.mjsnew file mode 100644index 000000000..edd50040b--- /dev/null+++ b/apps/desktop/test/racp-remote-host-client.test.mjs@@ -0,0 +1,133 @@+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 { createRacpRemoteHostClient } = await import(+ "../electron/main/remote/racp-remote-host-client.ts"+);+const { harness, OWNER_TOKEN, MemoryLink } = await import("@pi-desktop/racp/test-harness");++/** Build a transport factory that authenticates OWNER_TOKEN and hands the+ * server the link's server side. Each call to the factory opens a fresh+ * `MemoryLink`, mirroring how the production ws factory opens a fresh socket+ * per (re)connect. */+function ownerTransport({ server, authenticator }) {+ return async () => {+ const auth = await authenticator.authenticate({+ authorization: `Bearer ${OWNER_TOKEN}`,+ urlHasToken: false,+ connectionId: `test-${Math.random()}`,+ });+ if (!auth) throw new Error("test authenticator refused OWNER_TOKEN");+ const link = new MemoryLink();+ const accepted = server.accept(auth, link.serverSide());+ if (!accepted) throw new Error("test server refused connection");+ return link.clientSide();+ };+}++test("adapter connects, request delegates to RacpClient, close is clean", async () => {+ const h = await harness();+ const adapter = createRacpRemoteHostClient({+ transport: ownerTransport(h),+ clientInfo: { name: "test-desktop", version: "0.15.0" },+ requestTimeoutMs: 2_000,+ });+ assert.equal(adapter.state(), "disconnected");+ await adapter.connect();+ assert.equal(adapter.state(), "connected");+ const result = await adapter.client.request("session/list");+ assert.ok(Array.isArray(result.sessions));+ assert.ok(result.sessions.some((session) => session.id === "s1"));+ await adapter.close();+ assert.equal(adapter.state(), "disconnected");+});++test("subscribe fans out RACP events to every attached listener", async () => {+ const h = await harness();+ const adapter = createRacpRemoteHostClient({+ transport: ownerTransport(h),+ clientInfo: { name: "test-desktop", version: "0.15.0" },+ requestTimeoutMs: 2_000,+ });+ await adapter.connect();++ const a = [];+ const b = [];+ const detachA = adapter.client.subscribe((envelope) => a.push(envelope));+ const detachB = adapter.client.subscribe((envelope) => b.push(envelope));++ // Subscribe host scope so the following session/create surfaces as an event.+ await adapter.client.request("events/subscribe", { scope: "host" });+ await adapter.client.request("session/create", { title: "New" });+ // Let the socket flush the event notification.+ await new Promise((resolve) => setTimeout(resolve, 15));++ const kinds = a.map((envelope) => envelope.kind);+ assert.ok(kinds.includes("session.created"), "listener A should have seen session.created");+ assert.deepEqual(+ b.map((envelope) => envelope.kind),+ kinds,+ "both listeners must observe the same event stream",+ );++ detachA();+ a.length = 0;+ b.length = 0;+ await adapter.client.request("session/create", { title: "Another" });+ await new Promise((resolve) => setTimeout(resolve, 15));+ assert.equal(a.length, 0, "detached listener must stop receiving events");+ assert.ok(b.length > 0, "still-attached listener continues to receive events");++ detachB();+ await adapter.close();+});++test("a listener that throws does not break the fan-out to the others", async () => {+ const h = await harness();+ const warnings = [];+ const adapter = createRacpRemoteHostClient({+ transport: ownerTransport(h),+ clientInfo: { name: "test-desktop", version: "0.15.0" },+ requestTimeoutMs: 2_000,+ log: (level, message, data) => {+ if (level === "warn") warnings.push({ message, data });+ },+ });+ await adapter.connect();++ adapter.client.subscribe(() => {+ throw new Error("bad listener");+ });+ const survivor = [];+ adapter.client.subscribe((envelope) => survivor.push(envelope));++ await adapter.client.request("events/subscribe", { scope: "host" });+ await adapter.client.request("session/create", { title: "New" });+ await new Promise((resolve) => setTimeout(resolve, 15));++ assert.ok(survivor.length > 0, "survivor must still receive events");+ assert.ok(+ warnings.some((entry) => /listener threw/.test(entry.message)),+ "adapter must log the failing listener",+ );++ await adapter.close();+});++test("request before connect rejects with HOST_DISCONNECTED", async () => {+ const h = await harness();+ const adapter = createRacpRemoteHostClient({+ transport: ownerTransport(h),+ clientInfo: { name: "test-desktop", version: "0.15.0" },+ });+ await assert.rejects(+ () => adapter.client.request("session/list"),+ (error) => error.code === "HOST_DISCONNECTED",+ );+});diff --git a/apps/desktop/test/remote-host-registry.test.mjs b/apps/desktop/test/remote-host-registry.test.mjsnew file mode 100644index 000000000..0aef7df32--- /dev/null+++ b/apps/desktop/test/remote-host-registry.test.mjs@@ -0,0 +1,183 @@+import assert from "node:assert/strict";+import test from "node:test";+import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";+import { register } from "node:module";+import { tmpdir } from "node:os";+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 { createRemoteHostRegistry } = await import(+ "../electron/main/remote/remote-host-registry.ts"+);++/**+ * Reversible fake encryption for tests: prefix the plaintext so we can prove+ * the token was passed through `encrypt` and not written as clear bytes, and+ * so a "wrong key" scenario can be simulated by rejecting the prefix.+ */+function reversibleEncryption(overrides = {}) {+ return {+ available: overrides.available ?? true,+ isAvailable() {+ return this.available;+ },+ encryptString(plain) {+ return Buffer.from(`enc:${plain}`);+ },+ decryptString(buffer) {+ const text = buffer.toString("utf8");+ if (!text.startsWith("enc:")) throw new Error("cannot decrypt");+ return text.slice("enc:".length);+ },+ };+}++async function tmpDir() {+ const dir = await mkdtemp(join(tmpdir(), "remote-hosts-"));+ return {+ dir,+ async cleanup() {+ await rm(dir, { recursive: true, force: true });+ },+ };+}++test("list returns an empty array when the file does not exist", async () => {+ const { dir, cleanup } = await tmpDir();+ const registry = createRemoteHostRegistry({ dataDir: dir, encryption: reversibleEncryption() });+ assert.deepEqual(await registry.list(), []);+ await cleanup();+});++test("upsert then list round-trips a record and encrypts the token on disk", async () => {+ const { dir, cleanup } = await tmpDir();+ const encryption = reversibleEncryption();+ const registry = createRemoteHostRegistry({ dataDir: dir, encryption });+ await registry.upsert({+ hostKey: "hostA",+ label: "Home Linux",+ url: "wss://home.local:9443/racp",+ deviceToken: "rd_secret",+ });+ const rows = await registry.list();+ assert.equal(rows.length, 1);+ assert.equal(rows[0].hostKey, "hostA");+ assert.equal(rows[0].deviceToken, "rd_secret");+ // Confirm the token bytes never landed in plaintext.+ const raw = await readFile(join(dir, "remote-hosts.json"), "utf8");+ assert.ok(!raw.includes("rd_secret"), "plaintext token must not appear on disk");+ assert.ok(raw.includes("encryptedDeviceToken"));+ await cleanup();+});++test("upsert overwrites an existing hostKey and preserves the rest", async () => {+ const { dir, cleanup } = await tmpDir();+ const registry = createRemoteHostRegistry({ dataDir: dir, encryption: reversibleEncryption() });+ await registry.upsert({ hostKey: "a", label: "A", url: "wss://a", deviceToken: "t-a" });+ await registry.upsert({ hostKey: "b", label: "B", url: "wss://b", deviceToken: "t-b" });+ await registry.upsert({ hostKey: "a", label: "A renamed", url: "wss://a2", deviceToken: "t-a2" });+ const rows = await registry.list();+ assert.equal(rows.length, 2);+ const a = rows.find((row) => row.hostKey === "a");+ const b = rows.find((row) => row.hostKey === "b");+ assert.equal(a.label, "A renamed");+ assert.equal(a.url, "wss://a2");+ assert.equal(a.deviceToken, "t-a2");+ assert.equal(b.deviceToken, "t-b");+ await cleanup();+});++test("upsert refuses to write when safeStorage is unavailable", async () => {+ const { dir, cleanup } = await tmpDir();+ const registry = createRemoteHostRegistry({+ dataDir: dir,+ encryption: reversibleEncryption({ available: false }),+ });+ await assert.rejects(+ () =>+ registry.upsert({ hostKey: "a", label: "A", url: "wss://a", deviceToken: "t" }),+ (error) => error.errorCode === "REMOTE_STORAGE_UNAVAILABLE",+ );+ await cleanup();+});++test("remove drops one hostKey and unlinks the file when the last one leaves", async () => {+ const { dir, cleanup } = await tmpDir();+ const registry = createRemoteHostRegistry({ dataDir: dir, encryption: reversibleEncryption() });+ await registry.upsert({ hostKey: "a", label: "A", url: "wss://a", deviceToken: "t-a" });+ await registry.upsert({ hostKey: "b", label: "B", url: "wss://b", deviceToken: "t-b" });+ await registry.remove("a");+ assert.deepEqual((await registry.list()).map((row) => row.hostKey), ["b"]);+ await registry.remove("b");+ assert.deepEqual(await registry.list(), []);+ // File should no longer exist after emptying.+ await assert.rejects(+ () => readFile(join(dir, "remote-hosts.json"), "utf8"),+ (error) => error.code === "ENOENT",+ );+ await cleanup();+});++test("remove of a missing hostKey is a no-op", async () => {+ const { dir, cleanup } = await tmpDir();+ const registry = createRemoteHostRegistry({ dataDir: dir, encryption: reversibleEncryption() });+ await registry.upsert({ hostKey: "a", label: "A", url: "wss://a", deviceToken: "t-a" });+ await registry.remove("nope");+ const rows = await registry.list();+ assert.equal(rows.length, 1);+ await cleanup();+});++test("a record whose token fails to decrypt is skipped, not surfaced with a placeholder", async () => {+ const { dir, cleanup } = await tmpDir();+ const encryption = reversibleEncryption();+ const filePath = join(dir, "remote-hosts.json");+ const file = {+ version: 1,+ hosts: [+ {+ hostKey: "good",+ label: "Good",+ url: "wss://good",+ encryptedDeviceToken: Buffer.from("enc:t-good").toString("base64"),+ },+ {+ hostKey: "bad",+ label: "Bad",+ url: "wss://bad",+ encryptedDeviceToken: Buffer.from("wrong-prefix").toString("base64"),+ },+ ],+ };+ await writeFile(filePath, JSON.stringify(file), "utf8");+ const warnings = [];+ const registry = createRemoteHostRegistry({+ dataDir: dir,+ encryption,+ log: (level, message) => warnings.push({ level, message }),+ });+ const rows = await registry.list();+ assert.deepEqual(rows.map((row) => row.hostKey), ["good"]);+ assert.ok(warnings.some((entry) => /could not be decrypted/.test(entry.message)));+ await cleanup();+});++test("a shape-mismatched file is treated as empty and preserved on disk until rewritten", async () => {+ const { dir, cleanup } = await tmpDir();+ await writeFile(join(dir, "remote-hosts.json"), JSON.stringify({ hosts: "oops" }), "utf8");+ const warnings = [];+ const registry = createRemoteHostRegistry({+ dataDir: dir,+ encryption: reversibleEncryption(),+ log: (level, message) => warnings.push({ level, message }),+ });+ assert.deepEqual(await registry.list(), []);+ assert.ok(warnings.some((entry) => /shape rejected/.test(entry.message)));+ // File not deleted by list().+ const still = await readFile(join(dir, "remote-hosts.json"), "utf8");+ assert.ok(still.includes("oops"));+ await cleanup();+});diff --git a/packages/racp/package.json b/packages/racp/package.jsonindex 11b8c8201..b9d83da9d 100644--- a/packages/racp/package.json+++ b/packages/racp/package.json@@ -9,6 +9,10 @@".": {"types": "./dist/index.d.ts","import": "./dist/index.js"+ },+ "./test-harness": {+ "types": "./dist/test-harness.d.ts",+ "import": "./dist/test-harness.js"}},"scripts": {diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 05ba7ee6a..70b00c794 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -55,6 +55,9 @@ importers:'@pi-desktop/plugin-sdk':specifier: workspace:*version: link:../../packages/plugin-sdk+ '@pi-desktop/racp':+ specifier: workspace:*+ version: link:../../packages/racp'@pi-desktop/shared':specifier: workspace:*version: link:../../packages/shared