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): pair, list, and remove remote hosts from Settings
vastsa87fc114056af
diff --git a/apps/desktop/electron/main/bootstrap/remote-hosts.ts b/apps/desktop/electron/main/bootstrap/remote-hosts.tsindex 3be7e47c2..cc5664fa6 100644--- a/apps/desktop/electron/main/bootstrap/remote-hosts.ts+++ b/apps/desktop/electron/main/bootstrap/remote-hosts.ts@@ -26,6 +26,7 @@ import {createRemoteHostRegistry,type EncryptionPort,type RemoteHostRecord,+ type RemoteHostRegistry,} from "../remote/remote-host-registry.js";export type RemoteHostAdapterFactory = (record: RemoteHostRecord) => RacpRemoteHostClient;@@ -42,13 +43,29 @@ export type BootRemoteHostsOptions = {log?: (level: "info" | "warn" | "error", message: string, data?: unknown) => void;};+/** Renderer-facing summary of one paired host (no secret material). */+export type RemoteHostSummary = {+ hostKey: string;+ label: string;+ url: string;+ connected: boolean;+};+export interface RemoteHostsBoot {/** Read registry, connect every host, register their sessions. Returns* the number of hosts that finished `open()` without throwing. */open(): Promise<number>;/** Close every open connection. Idempotent; safe to call before `open`. */closeAll(): Promise<void>;-}+ /** Every paired host with its live connection state; safe from the renderer. */+ list(): Promise<RemoteHostSummary[]>;+ /** Persist a paired record, then open one live connection for it. */+ addHost(record: RemoteHostRecord): Promise<RemoteHostSummary>;+ /** Close and unregister the host, then remove it from the registry. */+ removeHost(hostKey: string): Promise<void>;+ /** The underlying registry, exposed for pairing flows that write directly. */+ readonly registry: RemoteHostRegistry;+};/*** Single-slot registry so `bootstrap/shutdown.ts` can wait on the same boot@@ -93,7 +110,52 @@ export function createRemoteHostsBoot(const opened: OpenHost[] = [];+ /** Bring one record online: build adapter, connect, register the router+ * backends. Failure is thrown so the caller can decide (boot logs & skips;+ * a live pair-then-add refuses to persist a token that cannot be used). */+ const openHost = async (record: RemoteHostRecord): Promise<OpenHost> => {+ const adapter = buildAdapter(record);+ await adapter.connect();+ const connection = createRemoteHostConnection({+ hostKey: record.hostKey,+ client: adapter.client,+ router: options.router,+ emit: options.emit,+ log: (level, message, data) => log(level, message, data),+ });+ try {+ await connection.open();+ } catch (error) {+ // A connection that failed to open leaves the adapter live; close it+ // before re-throwing so the ws socket does not leak.+ await adapter.close().catch(() => undefined);+ throw error;+ }+ return { hostKey: record.hostKey, adapter, connection };+ };++ const closeHost = async (host: OpenHost): Promise<void> => {+ try {+ await host.connection.close();+ } catch (error) {+ log("warn", `remote host ${host.hostKey} connection close threw`, {+ error: String(error),+ });+ }+ try {+ await host.adapter.close();+ } catch (error) {+ log("warn", `remote host ${host.hostKey} adapter close threw`, {+ error: String(error),+ });+ }+ };++ const isConnected = (hostKey: string): boolean =>+ opened.some((host) => host.hostKey === hostKey);+return {+ registry,async open() {let records: RemoteHostRecord[];try {@@ -112,17 +174,8 @@ export function createRemoteHostsBoot(// host serves its own set of sessions.for (const record of records) {try {- const adapter = buildAdapter(record);- await adapter.connect();- const connection = createRemoteHostConnection({- hostKey: record.hostKey,- client: adapter.client,- router: options.router,- emit: options.emit,- log: (level, message, data) => log(level, message, data),- });- await connection.open();- opened.push({ hostKey: record.hostKey, adapter, connection });+ const host = await openHost(record);+ opened.push(host);successes += 1;} catch (error) {log("warn", `remote host ${record.hostKey} failed to open; leaving it disconnected`, {@@ -135,24 +188,46 @@ export function createRemoteHostsBoot(async closeAll() {// Snapshot and clear first so a re-entrant close finds nothing to do.const hosts = opened.splice(0, opened.length);- await Promise.allSettled(- hosts.map(async (host) => {- try {- await host.connection.close();- } catch (error) {- log("warn", `remote host ${host.hostKey} connection close threw`, {- error: String(error),- });- }- try {- await host.adapter.close();- } catch (error) {- log("warn", `remote host ${host.hostKey} adapter close threw`, {- error: String(error),- });- }- }),- );+ await Promise.allSettled(hosts.map((host) => closeHost(host)));+ },+ async list() {+ const records = await registry.list();+ return records.map((record) => ({+ hostKey: record.hostKey,+ label: record.label,+ url: record.url,+ connected: isConnected(record.hostKey),+ }));+ },+ async addHost(record) {+ // Persist before opening so a crash between the two leaves a record the+ // next boot can retry; a failed open is surfaced but the row stays.+ await registry.upsert(record);+ // Replace any prior live connection under the same hostKey (a re-pair+ // rotates the device token but the routing key stays stable).+ const existing = opened.findIndex((host) => host.hostKey === record.hostKey);+ if (existing >= 0) {+ const [prior] = opened.splice(existing, 1);+ if (prior) await closeHost(prior);+ }+ try {+ const host = await openHost(record);+ opened.push(host);+ return { hostKey: record.hostKey, label: record.label, url: record.url, connected: true };+ } catch (error) {+ log("warn", `remote host ${record.hostKey} paired but failed to open`, {+ error: String(error),+ });+ return { hostKey: record.hostKey, label: record.label, url: record.url, connected: false };+ }+ },+ async removeHost(hostKey) {+ const index = opened.findIndex((host) => host.hostKey === hostKey);+ if (index >= 0) {+ const [host] = opened.splice(index, 1);+ if (host) await closeHost(host);+ }+ await registry.remove(hostKey);},};}diff --git a/apps/desktop/electron/main/ipc/register.ts b/apps/desktop/electron/main/ipc/register.tsindex a2a65198e..0345e1d7a 100644--- a/apps/desktop/electron/main/ipc/register.ts+++ b/apps/desktop/electron/main/ipc/register.ts@@ -23,6 +23,7 @@ import { registerSessionIpc } from "./session-ipc";import { registerSettingsIpc } from "./settings-ipc";import { registerSkillsIpc } from "./skills-ipc";import { registerAgentImportIpc } from "./agent-import-ipc";+import { registerRemoteHostIpc } from "./remote-host-ipc";import { fetchSkillMarketDocument, searchSkillMarket } from "../skill-market-catalog";import { registerWindowIpc } from "./window-ipc";import { createComposerTemplateLoader, registerWorkspaceIpc } from "./workspace-ipc";@@ -421,6 +422,8 @@ export function registerIpcHandlers(dependencies: RegisterIpcDependencies) {registerSpeechIpc({ registrar, speech });+ registerRemoteHostIpc({ registrar });+registerMarketIpc({registrar,getHost,diff --git a/apps/desktop/electron/main/ipc/remote-host-ipc.ts b/apps/desktop/electron/main/ipc/remote-host-ipc.tsnew file mode 100644index 000000000..f1c40ddca--- /dev/null+++ b/apps/desktop/electron/main/ipc/remote-host-ipc.ts@@ -0,0 +1,155 @@+/**+ * Renderer IPC for the R2b pairing UX (ADR 0286 §Registry).+ *+ * Three channels sit between the renderer's Settings page and the remote-hosts+ * boot hook: `list` reports the currently paired hosts with their live status,+ * `pair` exchanges a `ppt1.` pairing token for a durable device token and+ * brings the connection online, and `remove` closes and forgets one host.+ *+ * The renderer never sees a device token: the pairing exchange, the encrypted+ * write to `<dataDir>/remote-hosts.json`, and every subsequent live connection+ * live inside Electron main. `list` is safe to expose to any renderer surface.+ */+import { wsClientTransport } from "@pi-desktop/racp";+import {+ ErrorCodes,+ IPC,+ type RemoteHostPairRequest,+ type RemoteHostPairResult,+ type RemoteHostRemoveRequest,+ type RemoteHostSummary,+} from "@pi-desktop/shared";+import { app } from "electron";+import {+ getActiveRemoteHostsBoot,+ type RemoteHostsBoot,+} from "../bootstrap/remote-hosts";+import { createRacpRemoteHostClient } from "../remote/racp-remote-host-client";+import type { IpcRegistrar } from "./types";++export type RegisterRemoteHostIpcOptions = {+ registrar: IpcRegistrar;+ /**+ * Optional overrides for tests. Production reads the boot singleton set by+ * `bootstrap/startup.ts` (so no new field flows through `index.ts`) and+ * derives `clientInfo` from Electron's app name/version.+ */+ getRemoteHostsBoot?: () => RemoteHostsBoot | null;+ clientInfo?: { name: string; version: string };+ log?: (level: "info" | "warn" | "error", message: string, data?: unknown) => void;+};++function requireBoot(boot: RemoteHostsBoot | null): RemoteHostsBoot {+ if (!boot) {+ throw Object.assign(new Error("remote hosts are not ready yet"), {+ errorCode: ErrorCodes.AGENT_UNAVAILABLE,+ });+ }+ return boot;+}++function trim(value: unknown): string {+ return typeof value === "string" ? value.trim() : "";+}++/**+ * Derive a routing key from a URL and a label when the renderer did not+ * supply one. The URL's hostname keeps the key readable in logs; the label's+ * ASCII-safe slug disambiguates two hosts on the same machine (e.g., a WSL+ * and a native install of `pi-host` on `localhost`).+ */+function synthesizeHostKey(url: string, label: string): string {+ let hostname = "host";+ try {+ hostname = new URL(url).hostname || hostname;+ } catch {+ /* keep the fallback */+ }+ const slug = label+ .trim()+ .toLowerCase()+ .replace(/[^a-z0-9]+/g, "-")+ .replace(/^-+|-+$/g, "")+ .slice(0, 24);+ return slug ? `${hostname}-${slug}` : hostname;+}++export function registerRemoteHostIpc(options: RegisterRemoteHostIpcOptions): void {+ const { registrar } = options;+ const getRemoteHostsBoot = options.getRemoteHostsBoot ?? getActiveRemoteHostsBoot;+ const clientInfo =+ options.clientInfo ?? { name: app.getName(), version: app.getVersion() };+ const log = options.log ?? (() => undefined);++ registrar.handle(+ IPC.invoke.remoteHostList,+ async (): Promise<{ hosts: RemoteHostSummary[] }> => {+ const boot = requireBoot(getRemoteHostsBoot());+ return { hosts: await boot.list() };+ },+ );++ registrar.handle(+ IPC.invoke.remoteHostPair,+ async (request: RemoteHostPairRequest): Promise<RemoteHostPairResult> => {+ const boot = requireBoot(getRemoteHostsBoot());+ const url = trim(request?.url);+ const pairingToken = trim(request?.pairingToken);+ const label = trim(request?.label) || "desktop";+ if (!url || !pairingToken) {+ throw Object.assign(new Error("url and pairingToken are required"), {+ errorCode: ErrorCodes.INVALID_ARGUMENT,+ });+ }+ const hostKey = trim(request?.hostKey) || synthesizeHostKey(url, label);+ if (hostKey.includes(":")) {+ throw Object.assign(new Error("hostKey must not contain ':'"), {+ errorCode: ErrorCodes.INVALID_ARGUMENT,+ });+ }++ // Pair on a throwaway connection whose transport authenticates with the+ // single-use pairing token; call `connection/pair` for the device token,+ // then close it. The durable connection reopens under the device token+ // via `boot.addHost` below.+ const pairing = createRacpRemoteHostClient({+ transport: wsClientTransport({ url, token: pairingToken }),+ clientInfo,+ log: (level, message, data) => log(level, message, data),+ });+ let deviceToken: string;+ try {+ await pairing.connect();+ const result = (await pairing.client.request("connection/pair", {+ deviceLabel: label,+ })) as { deviceToken?: unknown };+ if (typeof result?.deviceToken !== "string" || result.deviceToken.length === 0) {+ throw Object.assign(new Error("pi-host did not return a device token"), {+ errorCode: "PAIRING_FAILED",+ });+ }+ deviceToken = result.deviceToken;+ } finally {+ await pairing.close().catch(() => undefined);+ }++ const summary = await boot.addHost({ hostKey, label, url, deviceToken });+ return { host: summary };+ },+ );++ registrar.handle(+ IPC.invoke.remoteHostRemove,+ async (request: RemoteHostRemoveRequest): Promise<{ ok: true }> => {+ const boot = requireBoot(getRemoteHostsBoot());+ const hostKey = trim(request?.hostKey);+ if (!hostKey) {+ throw Object.assign(new Error("hostKey is required"), {+ errorCode: ErrorCodes.INVALID_ARGUMENT,+ });+ }+ await boot.removeHost(hostKey);+ return { ok: true };+ },+ );+}diff --git a/apps/desktop/src/components/settings/RemoteHostsPage.tsx b/apps/desktop/src/components/settings/RemoteHostsPage.tsxnew file mode 100644index 000000000..e7889acd6--- /dev/null+++ b/apps/desktop/src/components/settings/RemoteHostsPage.tsx@@ -0,0 +1,226 @@+/**+ * Settings destination for paired remote `pi-host` machines (R2b pairing UX,+ * ADR 0286 §Registry).+ *+ * List every host stored in `<dataDir>/remote-hosts.json`, show its live+ * connection state, and offer a compact form to pair a new one with a URL ++ * pairing token issued by the target `pi-host`. The renderer never sees a+ * device token — pairing exchange and encrypted persistence stay inside+ * Electron main.+ */+import { useCallback, useEffect, useState } from "react";+import { useTranslation } from "react-i18next";+import type { RemoteHostSummary } from "@pi-desktop/shared";+import { api } from "../../lib/api";+import { useAppStore } from "../../stores/app-store";+import { Input, cx } from "../ui";+import { SettingsCard, SettingsRow } from "../../features/settings/primitives";++type PairForm = {+ url: string;+ pairingToken: string;+ label: string;+};++const EMPTY_FORM: PairForm = { url: "", pairingToken: "", label: "" };++export function RemoteHostsPage() {+ const { t } = useTranslation();+ const showToast = useAppStore((state) => state.showToast);+ const [hosts, setHosts] = useState<RemoteHostSummary[] | null>(null);+ const [error, setError] = useState<string | null>(null);+ const [form, setForm] = useState<PairForm>(EMPTY_FORM);+ const [pairing, setPairing] = useState(false);+ const [removing, setRemoving] = useState<string | null>(null);++ const refresh = useCallback(async () => {+ try {+ const result = await api.listRemoteHosts();+ setHosts(result.hosts);+ setError(null);+ } catch (caught) {+ const message = caught instanceof Error ? caught.message : String(caught);+ setError(message);+ }+ }, []);++ useEffect(() => {+ void refresh();+ }, [refresh]);++ const submit = useCallback(+ async (event: React.FormEvent<HTMLFormElement>) => {+ event.preventDefault();+ const url = form.url.trim();+ const pairingToken = form.pairingToken.trim();+ const label = form.label.trim();+ if (!url || !pairingToken || !label) return;+ setPairing(true);+ try {+ const result = await api.pairRemoteHost({ url, pairingToken, label });+ showToast(t("settings.remoteHosts.pairSucceeded", { label: result.host.label }), {+ variant: "info",+ });+ setForm(EMPTY_FORM);+ await refresh();+ } catch (caught) {+ const message = caught instanceof Error ? caught.message : String(caught);+ showToast(t("settings.remoteHosts.pairFailed", { message }), { variant: "error" });+ } finally {+ setPairing(false);+ }+ },+ [form, refresh, showToast, t],+ );++ const remove = useCallback(+ async (host: RemoteHostSummary) => {+ setRemoving(host.hostKey);+ try {+ await api.removeRemoteHost(host.hostKey);+ showToast(t("settings.remoteHosts.removed", { label: host.label }), {+ variant: "info",+ });+ await refresh();+ } catch (caught) {+ const message = caught instanceof Error ? caught.message : String(caught);+ showToast(t("settings.remoteHosts.removeFailed", { message }), { variant: "error" });+ } finally {+ setRemoving(null);+ }+ },+ [refresh, showToast, t],+ );++ return (+ <div className="settings-stack">+ <SettingsCard title={t("settings.remoteHosts.listTitle")}>+ <div className="settings-row-copy" role="note">+ <div className="settings-row-desc">+ {t("settings.remoteHosts.overview")}+ </div>+ </div>+ {error ? (+ <SettingsRow title={t("settings.remoteHosts.listError")}>+ <span className="text-text-muted">{error}</span>+ </SettingsRow>+ ) : null}+ {hosts === null ? (+ <SettingsRow title={t("settings.remoteHosts.loading")}>+ <span aria-hidden="true">…</span>+ </SettingsRow>+ ) : hosts.length === 0 ? (+ <SettingsRow title={t("settings.remoteHosts.emptyTitle")}>+ <span className="text-text-muted">{t("settings.remoteHosts.emptyBody")}</span>+ </SettingsRow>+ ) : (+ hosts.map((host) => (+ <SettingsRow+ key={host.hostKey}+ title={host.label}+ description={+ <span className="font-mono text-xs-plus text-text-muted">{host.url}</span>+ }+ >+ <span+ className={cx(+ "settings-remote-host-status",+ host.connected ? "is-online" : "is-offline",+ )}+ role="status"+ aria-live="polite"+ >+ {host.connected+ ? t("settings.remoteHosts.statusOnline")+ : t("settings.remoteHosts.statusOffline")}+ </span>+ <button+ type="button"+ className="settings-button danger"+ disabled={removing === host.hostKey}+ onClick={() => void remove(host)}+ >+ {removing === host.hostKey+ ? t("settings.remoteHosts.removing")+ : t("settings.remoteHosts.remove")}+ </button>+ </SettingsRow>+ ))+ )}+ </SettingsCard>++ <SettingsCard title={t("settings.remoteHosts.pairTitle")}>+ <form onSubmit={submit} className="settings-remote-host-form">+ <SettingsRow+ title={t("settings.remoteHosts.fieldLabel")}+ description={t("settings.remoteHosts.fieldLabelDesc")}+ >+ <Input+ value={form.label}+ onChange={(event) =>+ setForm((prev) => ({ ...prev, label: event.target.value }))+ }+ placeholder={t("settings.remoteHosts.fieldLabelPlaceholder")}+ aria-label={t("settings.remoteHosts.fieldLabel")}+ autoComplete="off"+ spellCheck={false}+ disabled={pairing}+ />+ </SettingsRow>+ <SettingsRow+ title={t("settings.remoteHosts.fieldUrl")}+ description={t("settings.remoteHosts.fieldUrlDesc")}+ >+ <Input+ value={form.url}+ onChange={(event) =>+ setForm((prev) => ({ ...prev, url: event.target.value }))+ }+ placeholder="ws://127.0.0.1:9443/racp"+ aria-label={t("settings.remoteHosts.fieldUrl")}+ inputMode="url"+ autoComplete="off"+ autoCapitalize="off"+ spellCheck={false}+ disabled={pairing}+ />+ </SettingsRow>+ <SettingsRow+ title={t("settings.remoteHosts.fieldPairingToken")}+ description={t("settings.remoteHosts.fieldPairingTokenDesc")}+ >+ <Input+ value={form.pairingToken}+ onChange={(event) =>+ setForm((prev) => ({ ...prev, pairingToken: event.target.value }))+ }+ placeholder="ppt1.…"+ aria-label={t("settings.remoteHosts.fieldPairingToken")}+ autoComplete="off"+ autoCapitalize="off"+ spellCheck={false}+ type="password"+ disabled={pairing}+ />+ </SettingsRow>+ <SettingsRow title={t("settings.remoteHosts.pairAction")}>+ <button+ type="submit"+ className="settings-button primary"+ disabled={+ pairing ||+ !form.url.trim() ||+ !form.pairingToken.trim() ||+ !form.label.trim()+ }+ >+ {pairing+ ? t("settings.remoteHosts.pairing")+ : t("settings.remoteHosts.pair")}+ </button>+ </SettingsRow>+ </form>+ </SettingsCard>+ </div>+ );+}diff --git a/apps/desktop/src/features/settings/SettingsPage.tsx b/apps/desktop/src/features/settings/SettingsPage.tsxindex 5b85d54c7..aefa7a806 100644--- a/apps/desktop/src/features/settings/SettingsPage.tsx+++ b/apps/desktop/src/features/settings/SettingsPage.tsx@@ -20,6 +20,7 @@ import {IconChevronLeft,IconDownload,IconFileText,+ IconGlobe,IconInfo,IconKeyboard,IconSearch,@@ -41,6 +42,7 @@ import { ProjectsPage } from "../../pages/ProjectsPage";import { AgentSkillsPage } from "../../components/settings/AgentSkillsPage";import { AgentMcpPage } from "../../components/settings/AgentMcpPage";import { AgentSubagentsPage } from "../../components/settings/AgentSubagentsPage";+import { RemoteHostsPage } from "../../components/settings/RemoteHostsPage";import {CommandShellRow,ContextUsageDisplayRow,@@ -184,6 +186,7 @@ export function SettingsPage() {subagents: <IconBot size={14} />,import: <IconDownload size={14} />,projects: <IconArchive size={14} />,+ remoteHosts: <IconGlobe size={14} />,about: <IconInfo size={14} />,};return SETTINGS_NAV.map((entry) => ({@@ -454,6 +457,8 @@ export function SettingsPage() {{tab === "projects" && <ProjectsPage />}+ {tab === "remoteHosts" && <RemoteHostsPage />}+{tab === "about" && (<div className="settings-stack"><SettingsCard>diff --git a/apps/desktop/src/lib/api.ts b/apps/desktop/src/lib/api.tsindex f2e162e1b..9c8226c1b 100644--- a/apps/desktop/src/lib/api.ts+++ b/apps/desktop/src/lib/api.ts@@ -100,6 +100,9 @@ import type {PlanResolutionResult,PlanningStateEvent,PlansPendingResult,+ RemoteHostPairRequest,+ RemoteHostPairResult,+ RemoteHostSummary,UpdateState,WindowControlAction,CloseBehavior,@@ -1369,6 +1372,17 @@ export const api = {listener((payload as { notification: AppNotification }).notification),);},++ // --- Remote hosts (R2b pairing UX) -----------------------------------------+ /** Paired remote `pi-host` list, redacted so no device token reaches here. */+ listRemoteHosts: () =>+ invoke<{ hosts: RemoteHostSummary[] }>(IPC.invoke.remoteHostList),+ /** Exchange `ppt1.` pairing token for a durable device token and connect. */+ pairRemoteHost: (request: RemoteHostPairRequest) =>+ invoke<RemoteHostPairResult>(IPC.invoke.remoteHostPair, request),+ /** Close and drop a paired host by its stable routing key. */+ removeRemoteHost: (hostKey: string) =>+ invoke<{ ok: true }>(IPC.invoke.remoteHostRemove, { hostKey }),onSessionsChanged: (listener: (event: {reason?: string;diff --git a/apps/desktop/src/lib/settings-search.ts b/apps/desktop/src/lib/settings-search.tsindex 9ca4aeb3d..bb3dffcae 100644--- a/apps/desktop/src/lib/settings-search.ts+++ b/apps/desktop/src/lib/settings-search.ts@@ -16,6 +16,7 @@ export type SettingsTabId =| "subagents"| "import"| "projects"+ | "remoteHosts"| "about";export type SettingsNavGroupId =@@ -221,6 +222,21 @@ export const SETTINGS_NAV: SettingsNavEntry[] = ["project.delete",],},+ {+ id: "remoteHosts",+ labelKey: "settings.nav.remoteHosts",+ titleKey: "settings.remoteHosts.title",+ group: "system",+ keywordKeys: [+ "settings.remoteHosts.title",+ "settings.remoteHosts.pairTitle",+ "settings.remoteHosts.pair",+ "settings.remoteHosts.fieldUrl",+ "settings.remoteHosts.fieldPairingToken",+ "settings.remoteHosts.statusOnline",+ "settings.remoteHosts.statusOffline",+ ],+ },{id: "about",labelKey: "settings.nav.info",diff --git a/apps/desktop/test/pairing-boot-add-remove.test.mjs b/apps/desktop/test/pairing-boot-add-remove.test.mjsnew file mode 100644index 000000000..edd7cad2d--- /dev/null+++ b/apps/desktop/test/pairing-boot-add-remove.test.mjs@@ -0,0 +1,231 @@+import assert from "node:assert/strict";+import test from "node:test";+import { mkdtemp, rm } 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 { IPC } = await import("@pi-desktop/shared");+const { createBackendRouter, makeRemoteSessionId } = await import(+ "../electron/main/remote/backend-router.ts"+);+const { createRemoteHostsBoot } = await import(+ "../electron/main/bootstrap/remote-hosts.ts"+);++/** Fake encryption round-trips through a well-known prefix so a test can+ * distinguish plaintext leaks (rejected) from encrypted round-trips (accepted). */+function reversibleEncryption() {+ return {+ isAvailable: () => true,+ encryptString: (plain) => Buffer.from(`enc:${plain}`),+ decryptString: (buf) => {+ const text = buf.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(), "pairing-ux-"));+ return { dir, cleanup: () => rm(dir, { recursive: true, force: true }) };+}++function fakeSession(id) {+ 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",+ };+}++/** A fake adapter mirroring `RacpRemoteHostClient` — enough surface for the+ * boot layer to build one host from a record. Tracks connection state so a+ * test can assert on `closeHost`. */+function fakeAdapter({ sessions = [], failConnect } = {}) {+ const listeners = new Set();+ return {+ state: "disconnected",+ async connect() {+ if (failConnect) throw failConnect;+ this.state = "connected";+ },+ async close() {+ this.state = "disconnected";+ listeners.clear();+ },+ client: {+ request: async (method) =>+ method === "session/list" ? { sessions } : { ok: true },+ subscribe: (fn) => {+ listeners.add(fn);+ return () => listeners.delete(fn);+ },+ },+ };+}++test("addHost persists, opens, and reports connected=true when the adapter succeeds", async () => {+ const { dir, cleanup } = await tmpDir();+ const router = createBackendRouter();+ const boot = createRemoteHostsBoot({+ dataDir: dir,+ encryption: reversibleEncryption(),+ router,+ emit: () => undefined,+ clientInfo: { name: "test", version: "0.15.0" },+ buildAdapter: () => fakeAdapter({ sessions: [fakeSession("s1")] }),+ });+ const summary = await boot.addHost({+ hostKey: "hostA",+ label: "Home",+ url: "wss://home.local:9443/racp",+ deviceToken: "rd_secret",+ });+ assert.equal(summary.connected, true);+ assert.equal(summary.hostKey, "hostA");+ // The router now resolves a remote session id under this hostKey.+ assert.ok(+ router.resolveBackend(IPC.invoke.sessionGet, [+ { id: makeRemoteSessionId("hostA", "s1") },+ ]),+ "router must have a backend after addHost",+ );+ const listed = await boot.list();+ assert.equal(listed.length, 1);+ assert.equal(listed[0].connected, true);+ assert.ok(!("deviceToken" in listed[0]), "list must never expose the device token");+ await boot.closeAll();+ await cleanup();+});++test("addHost still persists when the connection fails to open", async () => {+ const { dir, cleanup } = await tmpDir();+ const router = createBackendRouter();+ const boot = createRemoteHostsBoot({+ dataDir: dir,+ encryption: reversibleEncryption(),+ router,+ emit: () => undefined,+ clientInfo: { name: "test", version: "0.15.0" },+ buildAdapter: () =>+ fakeAdapter({+ failConnect: Object.assign(new Error("network down"), {+ code: "REMOTE_CONNECTION_FAILED",+ }),+ }),+ });+ const summary = await boot.addHost({+ hostKey: "bad",+ label: "Bad",+ url: "wss://bad",+ deviceToken: "t",+ });+ assert.equal(summary.connected, false);+ // The record persists so the next boot can retry.+ const listed = await boot.list();+ assert.equal(listed.length, 1);+ assert.equal(listed[0].hostKey, "bad");+ assert.equal(listed[0].connected, false);+ await boot.closeAll();+ await cleanup();+});++test("addHost on an existing hostKey rotates the live connection in place", async () => {+ const { dir, cleanup } = await tmpDir();+ const router = createBackendRouter();+ const adapters = [];+ const boot = createRemoteHostsBoot({+ dataDir: dir,+ encryption: reversibleEncryption(),+ router,+ emit: () => undefined,+ clientInfo: { name: "test", version: "0.15.0" },+ buildAdapter: (record) => {+ const adapter = fakeAdapter({ sessions: [fakeSession(`s-${record.hostKey}`)] });+ adapters.push(adapter);+ return adapter;+ },+ });+ await boot.addHost({ hostKey: "a", label: "A", url: "wss://a", deviceToken: "t1" });+ await boot.addHost({ hostKey: "a", label: "A", url: "wss://a", deviceToken: "t2" });+ assert.equal(adapters.length, 2);+ // The first adapter is closed once the second rotates in.+ assert.equal(adapters[0].state, "disconnected");+ assert.equal(adapters[1].state, "connected");+ const listed = await boot.list();+ assert.equal(listed.length, 1);+ await boot.closeAll();+ await cleanup();+});++test("removeHost closes the live connection and drops the record", async () => {+ const { dir, cleanup } = await tmpDir();+ const router = createBackendRouter();+ const adapters = [];+ const boot = createRemoteHostsBoot({+ dataDir: dir,+ encryption: reversibleEncryption(),+ router,+ emit: () => undefined,+ clientInfo: { name: "test", version: "0.15.0" },+ buildAdapter: () => {+ const adapter = fakeAdapter({ sessions: [fakeSession("s1")] });+ adapters.push(adapter);+ return adapter;+ },+ });+ await boot.addHost({ hostKey: "a", label: "A", url: "wss://a", deviceToken: "t" });+ await boot.removeHost("a");+ assert.equal(adapters[0].state, "disconnected");+ assert.equal(+ router.resolveBackend(IPC.invoke.sessionGet, [+ { id: makeRemoteSessionId("a", "s1") },+ ]),+ null,+ "the router must fall back to local after removeHost",+ );+ assert.deepEqual(await boot.list(), []);+ await boot.closeAll();+ await cleanup();+});++test("list surface strips device tokens even when the record is on disk", async () => {+ const { dir, cleanup } = await tmpDir();+ const boot = createRemoteHostsBoot({+ dataDir: dir,+ encryption: reversibleEncryption(),+ router: createBackendRouter(),+ emit: () => undefined,+ clientInfo: { name: "test", version: "0.15.0" },+ buildAdapter: () => fakeAdapter(),+ });+ await boot.addHost({+ hostKey: "h",+ label: "Home",+ url: "wss://home",+ deviceToken: "device-secret",+ });+ const listed = await boot.list();+ // The summary shape has these four fields and nothing else.+ assert.deepEqual(Object.keys(listed[0]).sort(), [+ "connected",+ "hostKey",+ "label",+ "url",+ ]);+ await boot.closeAll();+ await cleanup();+});diff --git a/docs/architecture/allowlist.json b/docs/architecture/allowlist.jsonindex 13e31d849..10041d47f 100644--- a/docs/architecture/allowlist.json+++ b/docs/architecture/allowlist.json@@ -12,6 +12,7 @@"crates/host-core/src/transcripts.rs": "Legacy transcript persistence module; its extraction is outside this refactor scope.","crates/host-core/src/plugins/tests.rs": "Existing plugin-domain test module retained while production plugin code is split.","crates/host-core/src/db/tests.rs": "Existing database-domain test module retained while production database code is split.",- "crates/host-core/src/providers/tests.rs": "Existing provider-domain test module retained while production provider code is split."+ "crates/host-core/src/providers/tests.rs": "Existing provider-domain test module retained while production provider code is split.",+ "crates/host-core/src/user_skills.rs": "User-skill catalog crossed the Rust 1000-LOC limit when the scan-and-batch-import path landed (PR #515); the file still holds one cohesive discovery/import lifecycle and is exempted until the batch-import surface is separated."}}diff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.tsindex 0b7be4a46..e585431a9 100644--- a/packages/i18n/src/locales/de/index.ts+++ b/packages/i18n/src/locales/de/index.ts@@ -625,6 +625,7 @@ sklm: {"subagents": "Subagenten","import": "Importieren Sie","projects": "Projekte",+ "remoteHosts": "Remote-Hosts","info": "Informationen"},"general": "Allgemein",@@ -823,6 +824,34 @@ sklm: {"subagentSaved": "Gespeichert {{name}}","import": "Importieren","projectArchive": "Projektarchiv",+ "remoteHosts": {+ "title": "Remote-Hosts",+ "overview": "Gekoppelte pi-host-Rechner, die Sie von diesem Desktop steuern können. Sitzungen auf einem gekoppelten Host werden wie lokale angezeigt; die Verbindung bleibt im Hauptprozess, und kein Gerätetoken erreicht diese Seite.",+ "listTitle": "Gekoppelte Remote-Hosts",+ "listError": "Hosts konnten nicht geladen werden",+ "loading": "Wird geladen…",+ "emptyTitle": "Noch keine Hosts gekoppelt",+ "emptyBody": "Koppeln Sie unten einen Rechner, um dort eine Sitzung zu starten.",+ "statusOnline": "Online",+ "statusOffline": "Offline",+ "remove": "Entfernen",+ "removing": "Wird entfernt…",+ "removed": "{{label}} entfernt.",+ "removeFailed": "Entfernen fehlgeschlagen: {{message}}",+ "pairTitle": "Neuen Host koppeln",+ "pair": "Koppeln",+ "pairing": "Koppelt…",+ "pairAction": "Hinzufügen",+ "pairSucceeded": "{{label}} gekoppelt.",+ "pairFailed": "Kopplung fehlgeschlagen: {{message}}",+ "fieldLabel": "Bezeichnung",+ "fieldLabelDesc": "Wird in der Liste angezeigt und auf dem gekoppelten Host gespeichert.",+ "fieldLabelPlaceholder": "Heim-Linux",+ "fieldUrl": "RACP-URL",+ "fieldUrlDesc": "Der Loopback-Endpunkt von pi-host, z. B. ws://127.0.0.1:9443/racp (über SSH weitergeleitet).",+ "fieldPairingToken": "Kopplungstoken",+ "fieldPairingTokenDesc": "Einmaliger ppt1.*-Token aus der pi-host-Bootstrap-Ausgabe. Wird beim Koppeln verbraucht."+ },"importTitle": "Import aus anderen Tools","importScan": "Scannen","importScanning": "Scannen…",diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.tsindex e648e74c1..5f4cdaaf3 100644--- a/packages/i18n/src/locales/en/index.ts+++ b/packages/i18n/src/locales/en/index.ts@@ -632,6 +632,7 @@ sklm: {subagents: "Subagents",import: "Import",projects: "Projects",+ remoteHosts: "Remote hosts",info: "Info",},general: "General",@@ -830,6 +831,37 @@ sklm: {subagentSaved: "Saved {{name}}",import: "Import",projectArchive: "Project archive",+ remoteHosts: {+ title: "Remote hosts",+ overview:+ "Paired pi-host machines you can drive from this desktop. Sessions on a paired host render like local ones; the connection stays inside main and no device token reaches this page.",+ listTitle: "Paired remote hosts",+ listError: "Failed to load hosts",+ loading: "Loading…",+ emptyTitle: "No hosts paired yet",+ emptyBody: "Pair a machine below to start a session on it.",+ statusOnline: "Online",+ statusOffline: "Offline",+ remove: "Remove",+ removing: "Removing…",+ removed: "{{label}} removed.",+ removeFailed: "Failed to remove: {{message}}",+ pairTitle: "Pair a new host",+ pair: "Pair",+ pairing: "Pairing…",+ pairAction: "Add",+ pairSucceeded: "{{label}} paired.",+ pairFailed: "Pairing failed: {{message}}",+ fieldLabel: "Label",+ fieldLabelDesc: "Shown in this list and recorded on the paired host.",+ fieldLabelPlaceholder: "Home Linux",+ fieldUrl: "RACP URL",+ fieldUrlDesc:+ "The pi-host loopback endpoint, e.g. ws://127.0.0.1:9443/racp (forwarded over SSH).",+ fieldPairingToken: "Pairing token",+ fieldPairingTokenDesc:+ "Single-use ppt1.* token from the pi-host bootstrap output. Consumed on pair.",+ },importTitle: "Import from other tools",importScan: "Scan",importScanning: "Scanning…",diff --git a/packages/i18n/src/locales/es/index.ts b/packages/i18n/src/locales/es/index.tsindex b79a8a82a..985f75900 100644--- a/packages/i18n/src/locales/es/index.ts+++ b/packages/i18n/src/locales/es/index.ts@@ -625,6 +625,7 @@ sklm: {"subagents": "Subagentes","import": "Importar","projects": "Proyectos",+ "remoteHosts": "Hosts remotos","info": "Información"},"general": "General",@@ -823,6 +824,34 @@ sklm: {"subagentSaved": "Guardado {{name}}","import": "Importar","projectArchive": "Archivo de proyecto",+ "remoteHosts": {+ "title": "Hosts remotos",+ "overview": "Máquinas pi-host emparejadas que puede controlar desde este escritorio. Las sesiones en un host emparejado se muestran como locales; la conexión permanece en el proceso principal y ningún token de dispositivo llega a esta página.",+ "listTitle": "Hosts remotos emparejados",+ "listError": "No se pudieron cargar los hosts",+ "loading": "Cargando…",+ "emptyTitle": "Aún no hay hosts emparejados",+ "emptyBody": "Empareje una máquina a continuación para iniciar una sesión en ella.",+ "statusOnline": "En línea",+ "statusOffline": "Desconectado",+ "remove": "Eliminar",+ "removing": "Eliminando…",+ "removed": "{{label}} eliminado.",+ "removeFailed": "Error al eliminar: {{message}}",+ "pairTitle": "Emparejar un nuevo host",+ "pair": "Emparejar",+ "pairing": "Emparejando…",+ "pairAction": "Añadir",+ "pairSucceeded": "{{label}} emparejado.",+ "pairFailed": "Error de emparejamiento: {{message}}",+ "fieldLabel": "Etiqueta",+ "fieldLabelDesc": "Se muestra en la lista y se registra en el host emparejado.",+ "fieldLabelPlaceholder": "Linux de casa",+ "fieldUrl": "URL de RACP",+ "fieldUrlDesc": "Punto final de bucle de retorno de pi-host, p. ej. ws://127.0.0.1:9443/racp (reenviado por SSH).",+ "fieldPairingToken": "Token de emparejamiento",+ "fieldPairingTokenDesc": "Token ppt1.* de un solo uso del inicio de pi-host. Se consume al emparejar."+ },"importTitle": "Importar desde otras herramientas","importScan": "Escanear","importScanning": "Escaneando...",diff --git a/packages/i18n/src/locales/fr/index.ts b/packages/i18n/src/locales/fr/index.tsindex 69dad8f70..bd6291896 100644--- a/packages/i18n/src/locales/fr/index.ts+++ b/packages/i18n/src/locales/fr/index.ts@@ -625,6 +625,7 @@ sklm: {"subagents": "Sous-agents","import": "Importation","projects": "Projets",+ "remoteHosts": "Hôtes distants","info": "Informations"},"general": "Général",@@ -823,6 +824,34 @@ sklm: {"subagentSaved": "Enregistré {{name}}","import": "Importation","projectArchive": "Archive du projet",+ "remoteHosts": {+ "title": "Hôtes distants",+ "overview": "Machines pi-host appariées que vous pouvez piloter depuis ce bureau. Les sessions sur un hôte apparié s'affichent comme locales ; la connexion reste dans le processus principal et aucun jeton d'appareil n'atteint cette page.",+ "listTitle": "Hôtes distants appariés",+ "listError": "Impossible de charger les hôtes",+ "loading": "Chargement…",+ "emptyTitle": "Aucun hôte apparié pour l'instant",+ "emptyBody": "Appariez une machine ci-dessous pour y démarrer une session.",+ "statusOnline": "En ligne",+ "statusOffline": "Hors ligne",+ "remove": "Supprimer",+ "removing": "Suppression…",+ "removed": "{{label}} supprimé.",+ "removeFailed": "Échec de la suppression : {{message}}",+ "pairTitle": "Apparier un nouvel hôte",+ "pair": "Apparier",+ "pairing": "Appariement…",+ "pairAction": "Ajouter",+ "pairSucceeded": "{{label}} apparié.",+ "pairFailed": "Échec de l'appariement : {{message}}",+ "fieldLabel": "Étiquette",+ "fieldLabelDesc": "Affichée dans la liste et enregistrée sur l'hôte apparié.",+ "fieldLabelPlaceholder": "Linux à la maison",+ "fieldUrl": "URL RACP",+ "fieldUrlDesc": "Point d'accès en boucle locale de pi-host, ex. ws://127.0.0.1:9443/racp (transmis via SSH).",+ "fieldPairingToken": "Jeton d'appariement",+ "fieldPairingTokenDesc": "Jeton ppt1.* à usage unique de la sortie de démarrage de pi-host. Consommé à l'appariement."+ },"importTitle": "Importer à partir d'autres outils","importScan": "Scanner","importScanning": "Analyse…",diff --git a/packages/i18n/src/locales/ko/index.ts b/packages/i18n/src/locales/ko/index.tsindex 1a22aaf15..45ddda91d 100644--- a/packages/i18n/src/locales/ko/index.ts+++ b/packages/i18n/src/locales/ko/index.ts@@ -633,6 +633,7 @@ sklm: {subagents: "서브에이전트",import: "가져오기",projects: "프로젝트",+ remoteHosts: "원격 호스트",info: "정보",},general: "일반",@@ -831,6 +832,37 @@ sklm: {subagentSaved: "{{name}} 저장됨",import: "가져오기",projectArchive: "프로젝트 보관함",+ remoteHosts: {+ title: "원격 호스트",+ overview:+ "이 데스크톱에서 조작할 수 있는 페어링된 pi-host 머신입니다. 페어링된 호스트의 세션은 로컬처럼 렌더링되며, 연결은 메인 프로세스에 남고 디바이스 토큰은 이 페이지에 도달하지 않습니다.",+ listTitle: "페어링된 원격 호스트",+ listError: "호스트를 불러오지 못했습니다",+ loading: "로드 중…",+ emptyTitle: "페어링된 호스트가 아직 없습니다",+ emptyBody: "아래에서 머신을 페어링하여 세션을 시작하세요.",+ statusOnline: "온라인",+ statusOffline: "오프라인",+ remove: "제거",+ removing: "제거 중…",+ removed: "{{label}} 제거됨.",+ removeFailed: "제거 실패: {{message}}",+ pairTitle: "새 호스트 페어링",+ pair: "페어링",+ pairing: "페어링 중…",+ pairAction: "추가",+ pairSucceeded: "{{label}} 페어링됨.",+ pairFailed: "페어링 실패: {{message}}",+ fieldLabel: "라벨",+ fieldLabelDesc: "목록에 표시되고 페어링된 호스트에 기록됩니다.",+ fieldLabelPlaceholder: "집 Linux",+ fieldUrl: "RACP URL",+ fieldUrlDesc:+ "pi-host의 루프백 엔드포인트, 예: ws://127.0.0.1:9443/racp (SSH로 포워딩).",+ fieldPairingToken: "페어링 토큰",+ fieldPairingTokenDesc:+ "pi-host 부트스트랩 출력의 일회용 ppt1.* 토큰. 페어링 시 소비됩니다.",+ },importTitle: "다른 도구에서 가져오기",importScan: "스캔",importScanning: "스캔 중…",diff --git a/packages/i18n/src/locales/tr/index.ts b/packages/i18n/src/locales/tr/index.tsindex 2bebe5f25..1170963b5 100644--- a/packages/i18n/src/locales/tr/index.ts+++ b/packages/i18n/src/locales/tr/index.ts@@ -633,6 +633,7 @@ sklm: {subagents: "Alt ajanlar",import: "İçe aktar",projects: "Projeler",+ remoteHosts: "Uzak ana bilgisayarlar",info: "Bilgi",},general: "Genel",@@ -831,6 +832,37 @@ sklm: {subagentSaved: "{{name}} kaydedildi",import: "İçe aktar",projectArchive: "Proje arşivi",+ remoteHosts: {+ title: "Uzak ana bilgisayarlar",+ overview:+ "Bu masaüstünden yönetebileceğiniz eşleşmiş pi-host makineler. Eşleşmiş bir ana bilgisayardaki oturumlar yerel gibi görünür; bağlantı ana süreç içinde kalır ve hiçbir cihaz belirteci bu sayfaya ulaşmaz.",+ listTitle: "Eşleşmiş uzak ana bilgisayarlar",+ listError: "Ana bilgisayarlar yüklenemedi",+ loading: "Yükleniyor…",+ emptyTitle: "Henüz eşleşmiş ana bilgisayar yok",+ emptyBody: "Aşağıdan bir makineyi eşleştirerek üzerinde oturum başlatın.",+ statusOnline: "Çevrimiçi",+ statusOffline: "Çevrimdışı",+ remove: "Kaldır",+ removing: "Kaldırılıyor…",+ removed: "{{label}} kaldırıldı.",+ removeFailed: "Kaldırma başarısız: {{message}}",+ pairTitle: "Yeni ana bilgisayar eşle",+ pair: "Eşle",+ pairing: "Eşleşiyor…",+ pairAction: "Ekle",+ pairSucceeded: "{{label}} eşlendi.",+ pairFailed: "Eşleme başarısız: {{message}}",+ fieldLabel: "Etiket",+ fieldLabelDesc: "Listede görünür ve eşleşmiş ana bilgisayara kaydedilir.",+ fieldLabelPlaceholder: "Evdeki Linux",+ fieldUrl: "RACP URL",+ fieldUrlDesc:+ "pi-host geri döngü uç noktası, örn. ws://127.0.0.1:9443/racp (SSH üzerinden yönlendirilir).",+ fieldPairingToken: "Eşleşme belirteci",+ fieldPairingTokenDesc:+ "pi-host önyükleme çıktısından tek kullanımlık ppt1.* belirteci. Eşleşme sırasında tüketilir.",+ },importTitle: "Diğer araçlardan içe aktar",importScan: "Tara",importScanning: "Taranıyor…",diff --git a/packages/i18n/src/locales/zh-CN/index.ts b/packages/i18n/src/locales/zh-CN/index.tsindex 17b8bca5d..85e087d06 100644--- a/packages/i18n/src/locales/zh-CN/index.ts+++ b/packages/i18n/src/locales/zh-CN/index.ts@@ -624,6 +624,7 @@ sklm: {subagents: "子智能体",import: "导入",projects: "项目",+ remoteHosts: "远程主机",info: "信息",},general: "常规",@@ -821,6 +822,37 @@ sklm: {subagentSaved: "已保存 {{name}}",import: "导入",projectArchive: "项目归档",+ remoteHosts: {+ title: "远程主机",+ overview:+ "已配对的 pi-host 机器;桌面能像本地一样驱动其上的会话,连接留在主进程内,设备令牌不会到达此页面。",+ listTitle: "已配对的远程主机",+ listError: "加载主机列表失败",+ loading: "加载中…",+ emptyTitle: "还没有配对主机",+ emptyBody: "在下方配对一台机器以开始远程会话。",+ statusOnline: "在线",+ statusOffline: "离线",+ remove: "移除",+ removing: "移除中…",+ removed: "已移除 {{label}}。",+ removeFailed: "移除失败:{{message}}",+ pairTitle: "配对新主机",+ pair: "配对",+ pairing: "配对中…",+ pairAction: "添加",+ pairSucceeded: "已配对 {{label}}。",+ pairFailed: "配对失败:{{message}}",+ fieldLabel: "标签",+ fieldLabelDesc: "在列表中显示,也记录到已配对主机上。",+ fieldLabelPlaceholder: "家里的 Linux",+ fieldUrl: "RACP 地址",+ fieldUrlDesc:+ "pi-host 的回环端点,例如 ws://127.0.0.1:9443/racp(经 SSH 转发)。",+ fieldPairingToken: "配对令牌",+ fieldPairingTokenDesc:+ "来自 pi-host 引导输出的一次性 ppt1.* 令牌,配对后即消耗。",+ },importTitle: "从其他工具导入",importScan: "扫描",importScanning: "正在扫描…",diff --git a/packages/i18n/src/locales/zh-TW/index.ts b/packages/i18n/src/locales/zh-TW/index.tsindex 035f7a13f..d45accfdb 100644--- a/packages/i18n/src/locales/zh-TW/index.ts+++ b/packages/i18n/src/locales/zh-TW/index.ts@@ -624,6 +624,7 @@ sklm: {subagents: "子智慧體",import: "匯入",projects: "專案",+ remoteHosts: "遠端主機",info: "資訊",},general: "常規",@@ -821,6 +822,37 @@ sklm: {subagentSaved: "已儲存 {{name}}",import: "匯入",projectArchive: "專案歸檔",+ remoteHosts: {+ title: "遠端主機",+ overview:+ "已配對的 pi-host 機器;桌面能像本地一樣驅動其上的工作階段,連線留在主行程內,裝置權杖不會到達此頁面。",+ listTitle: "已配對的遠端主機",+ listError: "載入主機清單失敗",+ loading: "載入中…",+ emptyTitle: "尚未配對主機",+ emptyBody: "於下方配對一台機器以開始遠端工作階段。",+ statusOnline: "在線",+ statusOffline: "離線",+ remove: "移除",+ removing: "移除中…",+ removed: "已移除 {{label}}。",+ removeFailed: "移除失敗:{{message}}",+ pairTitle: "配對新主機",+ pair: "配對",+ pairing: "配對中…",+ pairAction: "新增",+ pairSucceeded: "已配對 {{label}}。",+ pairFailed: "配對失敗:{{message}}",+ fieldLabel: "標籤",+ fieldLabelDesc: "顯示於清單,並記錄到已配對主機上。",+ fieldLabelPlaceholder: "家裡的 Linux",+ fieldUrl: "RACP 位址",+ fieldUrlDesc:+ "pi-host 的迴環端點,例如 ws://127.0.0.1:9443/racp(經 SSH 轉發)。",+ fieldPairingToken: "配對權杖",+ fieldPairingTokenDesc:+ "來自 pi-host 引導輸出的一次性 ppt1.* 權杖,配對後即消耗。",+ },importTitle: "從其他工具匯入",importScan: "掃描",importScanning: "正在掃描…",diff --git a/packages/shared/src/protocol.ts b/packages/shared/src/protocol.tsindex 1a271f942..01d2c8b3b 100644--- a/packages/shared/src/protocol.ts+++ b/packages/shared/src/protocol.ts@@ -146,6 +146,18 @@ export const IPC = {askToolResolve: "pi-desktop/agent/askTool/resolve",plansPending: "pi-desktop/plans/pending",plansResolve: "pi-desktop/plans/resolve",+ /**+ * List every paired remote `pi-host` this desktop knows, redacted so no+ * device token reaches the renderer. See ADR 0286 (R2b pairing UX).+ */+ remoteHostList: "pi-desktop/remoteHost/list",+ /**+ * Pair with a `pi-host` at `url` using a single-use `pairingToken`, mint+ * a device token, persist it encrypted, and open the live connection.+ */+ remoteHostPair: "pi-desktop/remoteHost/pair",+ /** Close the live connection for `hostKey` and drop its persisted record. */+ remoteHostRemove: "pi-desktop/remoteHost/remove",providersList: "pi-desktop/providers/list",providersCreate: "pi-desktop/providers/create",providersUpdate: "pi-desktop/providers/update",diff --git a/packages/shared/src/types.ts b/packages/shared/src/types.tsindex 7c69b9425..b03d5b7ae 100644--- a/packages/shared/src/types.ts+++ b/packages/shared/src/types.ts@@ -21,3 +21,4 @@ export * from "./types/platform.js";export * from "./types/workpanel.js";export * from "./types/filesystem.js";export * from "./types/speech.js";+export * from "./types/remote-host.js";diff --git a/packages/shared/src/types/remote-host.ts b/packages/shared/src/types/remote-host.tsnew file mode 100644index 000000000..18bb3ee54--- /dev/null+++ b/packages/shared/src/types/remote-host.ts@@ -0,0 +1,43 @@+/**+ * Renderer-facing shape of one paired remote `pi-host`. The device token that+ * authenticates the connection stays inside Electron main — the renderer only+ * sees the routing key, label, URL, and last-known live-connection state so+ * the Settings row can render a status pill without a second round trip.+ *+ * Companion of `RemoteHostRecord` inside main (which additionally carries+ * `deviceToken`). See ADR 0286 §Registry and R2b pairing UX.+ */+export type RemoteHostSummary = {+ hostKey: string;+ label: string;+ url: string;+ connected: boolean;+};++/**+ * Input for `remoteHostPair`. The pairing token is single-use and expiring+ * (spec §3.4); the desktop uses it once on the upgrade to call+ * `connection/pair`, exchanges it for a durable device token, and stores that+ * token encrypted with the OS keychain via `safeStorage`.+ */+export type RemoteHostPairRequest = {+ /** `ws://` or `wss://` URL of the paired host's RACP endpoint. */+ url: string;+ /** `ppt1.` pairing token the host issued in its bootstrap output. */+ pairingToken: string;+ /** Human label; the host records it against the minted device. */+ label: string;+ /**+ * Optional stable routing key. Absent means the desktop mints one from the+ * URL host + label; a caller may supply its own to keep the id predictable.+ */+ hostKey?: string;+};++export type RemoteHostPairResult = {+ host: RemoteHostSummary;+};++export type RemoteHostRemoveRequest = {+ hostKey: string;+};