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-ssh): optimize verified host workspace access
vastsab8b9ffe26725
diff --git a/apps/desktop/electron/main/bootstrap/remote-hosts.ts b/apps/desktop/electron/main/bootstrap/remote-hosts.tsindex cd3bd6f77..354ce0e21 100644--- a/apps/desktop/electron/main/bootstrap/remote-hosts.ts+++ b/apps/desktop/electron/main/bootstrap/remote-hosts.ts@@ -5,7 +5,7 @@ import {type RacpEventEnvelope, type RacpItemSummary, type RacpProjectSummary, type RacpSession,type RemoteHostBootstrapRequest, type RemoteHostBootstrapResult,type RemoteHostCreateSessionRequest, type RemoteHostSummary, type RemoteHostBrowseProjectsResult,- type RemoteHostSyncProvidersRequest, type RemoteHostSyncProvidersResult, type SessionSummary,+ type RemoteHostConnectionStatus, type RemoteHostSyncProvidersRequest, type RemoteHostSyncProvidersResult, type SessionSummary,type CommandShellOption, isCommandShellOption,type WorkspaceFilesRequest,} from "@pi-desktop/shared";@@ -21,6 +21,7 @@ import { createRemoteHostRegistry, type EncryptionPort, type RemoteHostRecord, timport { sshMetadataOf, sshHostRecord, transportOf } from "../remote/remote-host-metadata.js";import { createRemoteSessionCatalog } from "../remote/remote-session-catalog.js";import { syncRemoteProviders } from "../remote/remote-provider-transfer.js";+import { workspaceExecutionError } from "../remote/remote-workspace-outcome.js";export { sshMetadataOf, sshHostRecord, transportOf } from "../remote/remote-host-metadata.js";export type { RemoteHostSummary };@@ -55,6 +56,7 @@ export interface RemoteHostsBoot {addHost(record: RemoteHostRecord): Promise<RemoteHostSummary>;bootstrapHost(request: RemoteHostBootstrapRequest): Promise<RemoteHostBootstrapResult>;reconnectHost(hostKey: string): Promise<RemoteHostSummary>;+ ensureReady(hostKey: string): Promise<RemoteHostSummary>;removeHost(hostKey: string): Promise<void>;sessionSummaries(): SessionSummary[];sessions(hostKey: string): Promise<SessionSummary[]>;@@ -81,14 +83,24 @@ function unavailable(): Error {return Object.assign(new Error("remote host is unavailable"), { errorCode: "AGENT_UNAVAILABLE" });}+function requiresUserAction(error: unknown): boolean {+ if (!error || typeof error !== "object") return false;+ const fields = error as { errorCode?: string; code?: string };+ return ["HOST_AUTH_FAILED", "REMOTE_AUTH_FAILED", "HOST_VERSION_MISMATCH", "CAPABILITY_UNAVAILABLE"]+ .includes(fields.errorCode ?? fields.code ?? "");+}+export function createRemoteHostsBoot(options: BootRemoteHostsOptions): RemoteHostsBoot {const log = options.log ?? (() => undefined);const registry = createRemoteHostRegistry({ dataDir: options.dataDir, encryption: options.encryption, log });const tunnels = options.tunnels ?? createSshTunnelManager({ log });const opened = new Map<string, OpenHost>();+ const actionRequired = new Set<string>();const openingHosts = new Set<OpenHost>();const hostClosings = new WeakMap<OpenHost, Promise<void>>();const operations = new Map<string, Promise<unknown>>();+ const readiness = new Map<string, Promise<RemoteHostSummary>>();+ const bootstraps = new Map<AbortController, Promise<unknown>>();let closed = false;let opening: Promise<number> | undefined;let closing: Promise<void> | undefined;@@ -140,6 +152,8 @@ export function createRemoteHostsBoot(options: BootRemoteHostsOptions): RemoteHofirst = false;return wsClientTransport({ url, token: record.deviceToken })();},+ expectedHostId: ssh?.hostId,+ onStateChange: () => { if (!closed) changed(); },clientInfo: options.clientInfo,reconnect: { enabled: true, baseDelayMs: 500, maxDelayMs: 15_000, maxAttempts: 10 },log,@@ -147,7 +161,7 @@ export function createRemoteHostsBoot(options: BootRemoteHostsOptions): RemoteHo});const bootstrap = createSshBootstrap({version: options.clientInfo.version,- exchangePairing: ({ url, pairingToken, label }) => exchangePairingToken({ url, pairingToken, label, clientInfo: options.clientInfo, log }),+ exchangePairing: ({ url, pairingToken, label, expectedHostId }) => exchangePairingToken({ url, pairingToken, label, expectedHostId, clientInfo: options.clientInfo, requireWorkspace: true, log }),log, ...options.sshBootstrap,});@@ -191,6 +205,8 @@ export function createRemoteHostsBoot(options: BootRemoteHostsOptions): RemoteHoopeningHosts.add(live);try {assertOpen();+ actionRequired.delete(record.hostKey);+ opened.set(record.hostKey, live);await adapter.connect();assertOpen();await connection.open();@@ -200,6 +216,7 @@ export function createRemoteHostsBoot(options: BootRemoteHostsOptions): RemoteHoassertOpen();return live;} catch (error) {+ if (requiresUserAction(error)) actionRequired.add(record.hostKey);if (opened.get(record.hostKey) === live) opened.delete(record.hostKey);await closeHost(live);throw error;@@ -208,8 +225,12 @@ export function createRemoteHostsBoot(options: BootRemoteHostsOptions): RemoteHo}}function summaryOf(record: RemoteHostRecord): RemoteHostSummary {+ const state = opened.get(record.hostKey)?.adapter.state();+ const status: RemoteHostConnectionStatus = state === "connected" || state === "connecting" || state === "reconnecting"+ ? state+ : state === "error" || actionRequired.has(record.hostKey) ? "action-required" : "disconnected";return { hostKey: record.hostKey, label: record.label, url: opened.get(record.hostKey)?.url ?? record.url,- connected: Boolean(connectedHost(record.hostKey)), transport: transportOf(record) };+ connected: status === "connected", status, transport: transportOf(record) };}async function addRecord(record: RemoteHostRecord): Promise<RemoteHostSummary> {assertOpen();@@ -223,8 +244,28 @@ export function createRemoteHostsBoot(options: BootRemoteHostsOptions): RemoteHoreturn summaryOf(record);}+ const ensureReady = (key: string): Promise<RemoteHostSummary> => {+ const pending = readiness.get(key);+ if (pending) return pending;+ const task = serial(key, async () => {+ const record = (await registry.list()).find((item) => item.hostKey === key);+ assertOpen();+ if (!record) throw unavailable();+ if (!connectedHost(key)) {+ await closeLive(key);+ assertOpen();+ await openHost(record);+ }+ return summaryOf(record);+ });+ readiness.set(key, task);+ void task.finally(() => { if (readiness.get(key) === task) readiness.delete(key); }).catch(() => undefined);+ return task;+ };+return {registry,+ ensureReady,open() {if (opening) return opening;opening = (async () => {@@ -251,6 +292,7 @@ export function createRemoteHostsBoot(options: BootRemoteHostsOptions): RemoteHocloseAll() {if (closing) return closing;closed = true;+ for (const controller of bootstraps.keys()) controller.abort();const hosts = new Set([...opened.values(), ...openingHosts]);opened.clear();closing = (async () => {@@ -258,7 +300,7 @@ export function createRemoteHostsBoot(options: BootRemoteHostsOptions): RemoteHo// Forward creation is itself an operation we must cancel, not await// before disposal. The same fence prevents all late registrations.const disposal = tunnels.dispose();- await Promise.allSettled([...cleanup, disposal, ...operations.values()]);+ await Promise.allSettled([...cleanup, disposal, ...operations.values(), ...bootstraps.values()]);await disposal;})();return closing;@@ -267,9 +309,13 @@ export function createRemoteHostsBoot(options: BootRemoteHostsOptions): RemoteHosessionSummaries: () => catalog.summaries(),sessions: catalog.sessions,projects: catalog.projects,- browseProjects: catalog.browseProjects,+ async browseProjects(hostKey, path) {+ await ensureReady(hostKey);+ return catalog.browseProjects(hostKey, path);+ },registerProject: catalog.registerProject,async workspaceFiles(hostKey, input) {+ await ensureReady(hostKey);const host = connectedHost(hostKey);if (!host) throw unavailable();const result = await host.adapter.client.request("workspace/files", input);@@ -277,6 +323,7 @@ export function createRemoteHostsBoot(options: BootRemoteHostsOptions): RemoteHoreturn result;},async workspaceCommandShell(hostKey) {+ await ensureReady(hostKey);const host = connectedHost(hostKey);if (!host) throw unavailable();const { shell } = await host.adapter.client.request<{ shell: unknown }>("workspace/toolShell", {});@@ -314,7 +361,7 @@ export function createRemoteHostsBoot(options: BootRemoteHostsOptions): RemoteHosessionId: input.sessionId, toolCallId: input.toolCallId,}); } catch (abortError) { log("warn", "remote tool abort failed", { error: String(abortError) }); }}- throw error;+ throw workspaceExecutionError(input.toolName, error);}},async abortWorkspaceTool(input) {@@ -350,7 +397,10 @@ export function createRemoteHostsBoot(options: BootRemoteHostsOptions): RemoteHo}),async bootstrapHost(request) {assertOpen();- const outcome = await bootstrap.bootstrap(request);+ const controller = new AbortController();+ const task = bootstrap.bootstrap(request, { signal: controller.signal });+ bootstraps.set(controller, task);+ const outcome = await task.finally(() => { bootstraps.delete(controller); });let adopted = false;try {return await serial(outcome.hostKey, async () => {@@ -377,6 +427,7 @@ export function createRemoteHostsBoot(options: BootRemoteHostsOptions): RemoteHoawait closeLive(key);await tunnels.close(key);await registry.remove(key);+ actionRequired.delete(key);catalog.forget(key);changed();}),diff --git a/apps/desktop/electron/main/remote/pi-host-bootstrap-script.ts b/apps/desktop/electron/main/remote/pi-host-bootstrap-script.tsindex e2a380ffb..b7f829701 100644--- a/apps/desktop/electron/main/remote/pi-host-bootstrap-script.ts+++ b/apps/desktop/electron/main/remote/pi-host-bootstrap-script.ts@@ -1,3 +1,5 @@+import { REMOTE_DEPLOY_LOCK_SCRIPT } from "./remote-deploy-lock.js";+/*** The bootstrap script the desktop uploads over SSH (spec §5.2 step 2, §3.4).*@@ -31,6 +33,8 @@ export type PiHostBootstrapScriptInput = {bundleDir: string;/** Lower-case hex digest from the published `.sha256`. */expectedSha256: string;+ /** Verified local-download fallback, already uploaded through SSH. */+ artifactPath?: string;/** Loopback port for `pi-host`; `0` lets it pick a free port and report it. */port: number;/** Pairing token lifetime handed to `--pairing-lifetime-ms`. */@@ -57,6 +61,7 @@ const SCRIPT_VARIABLES = ["PAIRING_LIFETIME_MS","READY_TIMEOUT_SEC","MIN_NODE_MAJOR",+ "ARTIFACT_PATH",] as const;export function buildBootstrapScript(input: PiHostBootstrapScriptInput): string {@@ -70,15 +75,15 @@ export function buildBootstrapScript(input: PiHostBootstrapScriptInput): stringString(input.pairingLifetimeMs),String(input.readyTimeoutSec),String(MIN_NODE_MAJOR),+ input.artifactPath ?? "",];const assignments = SCRIPT_VARIABLES.map((name, index) => `${name}=${shellQuote(values[index] ?? "")}`,).join("\n");return `#!/bin/sh-# pi-host bootstrap — generated by PI-Desktop. Idempotent: it replaces the-# bundle for its own version, restarts the host it previously started, and-# prints a fresh single-use pairing token.+# pi-host bootstrap — generated by PI-Desktop. Reuses verified releases,+# restarts the host it previously started, and prints a fresh pairing token.set -euumask 077@@ -97,21 +102,48 @@ need() {[ -n "\${HOME:-}" ] || die "no-home"-need nodeneed tar-node_major=$(node -p 'process.versions.node.split(".")[0]' 2>/dev/null || printf '0')-[ "$node_major" -ge "$MIN_NODE_MAJOR" ] 2>/dev/null || die "node-too-old"--work="$HOME/.pi-desktop/pi-host/.bootstrap"+base="$HOME/.pi-desktop/pi-host"+work="$base/.bootstrap"mkdir -p "$work"chmod 700 "$work" 2>/dev/null || die "bootstrap-permissions"+${REMOTE_DEPLOY_LOCK_SCRIPT}+stage=""+cleanup() {+ [ -z "$stage" ] || rm -rf "$stage"+ release_deploy_lock+}+trap cleanup EXIT+trap 'exit 1' HUP INT TERM+stage=$(mktemp -d "$base/.stage.XXXXXX") || die "stage-failed"log="$work/pi-host.log"err="$work/pi-host.err"pidfile="$work/pi-host.pid"-: > "$log"-: > "$err"+sha256_of() {+ if command -v sha256sum >/dev/null 2>&1; then+ sha256sum "$1" | cut -d ' ' -f 1+ elif command -v shasum >/dev/null 2>&1; then+ shasum -a 256 "$1" | cut -d ' ' -f 1+ else+ return 127+ fi+}+# The archive trust anchor and installed manifest must both match. Keep the+# receipt outside immutable version contents, which reject extra files.+receipt="$base/.release.sha256"+reuse=0+if [ -x "$base/current/bin/node" ] && [ -f "$base/current/SHA256SUMS" ] && [ -f "$receipt" ]; then+ manifest_sha256=$(sha256_of "$base/current/SHA256SUMS") || die "missing-sha256-tool"+ expected_receipt="$VERSION $EXPECTED_SHA256 $manifest_sha256"+ if [ "$(cat "$receipt")" = "$expected_receipt" ] && \\+ sh "$base/current/install.sh" --verify >/dev/null 2>&1; then+ reuse=1+ step "reuse"+ fi+fi+if [ "$reuse" = 0 ]; then# --- download the pinned bundle -------------------------------------------step "download"http_get() {@@ -124,33 +156,43 @@ http_get() {fi}-tarball="$work/$ARTIFACT_NAME"-rm -f "$tarball"-http_get "$ARTIFACT_URL" "$tarball" || die "download-failed"+tarball="$stage/$ARTIFACT_NAME"+if [ -n "$ARTIFACT_PATH" ]; then+ case "$ARTIFACT_PATH" in "$base"/.upload.*/artifact.tar.gz) ;; *) die "invalid-artifact-path" ;; esac+ cp "$ARTIFACT_PATH" "$tarball" || die "upload-missing"+else+ http_get "$ARTIFACT_URL" "$tarball" || die "download-failed"+fichmod 600 "$tarball" 2>/dev/null || die "artifact-permissions"# --- verify the published digest ------------------------------------------step "verify"-sha256_of() {- if command -v sha256sum >/dev/null 2>&1; then- sha256sum "$1" | cut -d ' ' -f 1- elif command -v shasum >/dev/null 2>&1; then- shasum -a 256 "$1" | cut -d ' ' -f 1- else- return 127- fi-}actual_sha256=$(sha256_of "$tarball") || die "missing-sha256-tool"[ "$actual_sha256" = "$EXPECTED_SHA256" ] || die "checksum-mismatch"# --- install under the user's home ----------------------------------------step "install"-unpack="$work/unpack"-rm -rf "$unpack"+unpack="$stage/unpack"mkdir -p "$unpack"tar -xzf "$tarball" -C "$unpack" || die "extract-failed"[ -d "$unpack/$BUNDLE_DIR" ] || die "unexpected-archive-layout"sh "$unpack/$BUNDLE_DIR/install.sh" >/dev/null || die "install-failed"+ if [ -x "$base/current/bin/node" ] && [ -f "$base/current/SHA256SUMS" ]; then+ sh "$base/current/install.sh" --verify >/dev/null 2>&1 || die "installed-verification-failed"+ manifest_sha256=$(sha256_of "$base/current/SHA256SUMS") || die "missing-sha256-tool"+ printf '%s\\n' "$VERSION $EXPECTED_SHA256 $manifest_sha256" > "$stage/receipt"+ mv -f "$stage/receipt" "$receipt" || die "receipt-failed"+ fi+fi++# Bundles carry Node; only older bundles need a system runtime.+node="$base/current/bin/node"+if [ ! -x "$node" ]; then+ need node+ node=$(command -v node)+fi+node_major=$("$node" -p 'process.versions.node.split(".")[0]' 2>/dev/null || printf '0')+[ "$node_major" -ge "$MIN_NODE_MAJOR" ] 2>/dev/null || die "node-too-old"# --- (re)start on loopback with a fresh pairing token ----------------------step "start"@@ -167,14 +209,17 @@ if [ -f "$pidfile" ]; thensleep 1waited=$((waited + 1))done+ kill -0 "$previous" 2>/dev/null && die "host-stop-timeout"fifi-nohup node "$HOME/.pi-desktop/pi-host/current/pi-host.js" \\+: > "$log"+: > "$err"+nohup "$node" "$HOME/.pi-desktop/pi-host/current/pi-host.js" \\--port "$PORT" \\--pair \\--pairing-lifetime-ms "$PAIRING_LIFETIME_MS" \\- >"$log" 2>"$err" </dev/null &+ >"$log" 2>"$err" </dev/null 9>&- &host_pid=$!printf '%s\\n' "$host_pid" > "$pidfile"@@ -280,10 +325,11 @@ export function parseBootstrapOutput(stdout: string): PiHostBootstrapOutput {if (typeof hostId === "string" &&hostId.length > 0 &&- typeof host === "string" &&+ (host === "127.0.0.1" || host === "::1") &&typeof port === "number" &&Number.isInteger(port) &&port > 0 &&+ port <= 65535 &&typeof version === "string") {output.ready = { hostId, host, port, version };diff --git a/apps/desktop/electron/main/remote/pi-host-installer.ts b/apps/desktop/electron/main/remote/pi-host-installer.tsnew file mode 100644index 000000000..dcf1d2a4d--- /dev/null+++ b/apps/desktop/electron/main/remote/pi-host-installer.ts@@ -0,0 +1,43 @@+/** Remote-first install with one verified SSH-upload fallback, never tool replay. */+import { buildBootstrapScript, parseBootstrapOutput, type PiHostBootstrapScriptInput } from "./pi-host-bootstrap-script.js";+import { uploadSshArtifact } from "./ssh-artifact-transfer.js";+import type { SshExecResult, SshTransport } from "./ssh-transport.js";++export async function installPiHost(+ transport: SshTransport,+ input: PiHostBootstrapScriptInput,+ options: {+ timeoutMs: number; signal?: AbortSignal;+ uploadArtifact?: typeof uploadSshArtifact;+ onUpload?: () => void;+ log?: (level: "warn", message: string) => void;+ },+): Promise<SshExecResult> {+ const run = async (artifactPath?: string) => {+ options.signal?.throwIfAborted();+ const result = await transport.execWithInput("sh -s", buildBootstrapScript({ ...input, artifactPath }),+ { timeoutMs: options.timeoutMs, maxOutputBytes: 64 * 1024 });+ options.signal?.throwIfAborted();+ return result;+ };+ let initial: SshExecResult;+ try {+ initial = await run();+ if (parseBootstrapOutput(initial.stdout).failure !== "download-failed") return initial;+ } catch (error) {+ options.signal?.throwIfAborted();+ const step = parseBootstrapOutput(String((error as { stdout?: unknown })?.stdout ?? "")).failure;+ if (step !== "download-failed" || (!transport.execWithFile && !options.uploadArtifact)) throw error;+ initial = { stdout: String((error as { stdout?: unknown }).stdout ?? ""), stderr: "", code: 1 };+ }+ if (!transport.execWithFile && !options.uploadArtifact) return initial;+ options.signal?.throwIfAborted();+ options.onUpload?.();+ const artifact = await (options.uploadArtifact ?? uploadSshArtifact)(transport,+ { url: input.artifactUrl, expectedSha256: input.expectedSha256, signal: options.signal });+ try { return await run(artifact.path); }+ finally {+ try { await artifact.cleanup(); }+ catch { options.log?.("warn", "SSH artifact temporary directory cleanup failed"); }+ }+}diff --git a/apps/desktop/electron/main/remote/racp-remote-host-client.ts b/apps/desktop/electron/main/remote/racp-remote-host-client.tsindex 816567eca..42a1dc2f1 100644--- a/apps/desktop/electron/main/remote/racp-remote-host-client.ts+++ b/apps/desktop/electron/main/remote/racp-remote-host-client.ts@@ -28,6 +28,9 @@ export type PairingExchangeOptions = {/** Device label the host records against the minted device. */label: string;clientInfo: { name: string; version: string };+ /** New SSH workspace installs require both additive workspace services. */+ requireWorkspace?: boolean;+ expectedHostId?: string;log?: (level: "info" | "warn", message: string, data?: Record<string, unknown>) => void;};@@ -43,6 +46,8 @@ export async function exchangePairingToken(options: PairingExchangeOptions): Proconst pairing = createRacpRemoteHostClient({transport: wsClientTransport({ url: options.url, token: options.pairingToken }),clientInfo: options.clientInfo,+ requireWorkspace: options.requireWorkspace,+ expectedHostId: options.expectedHostId,log: options.log,});try {@@ -65,6 +70,9 @@ export type RacpRemoteHostClientOptions = {transport: ClientTransportFactory;/** Identity sent in `connection/initialize`; the host records it as the device label. */clientInfo: { name: string; version: string };+ /** Leave false for legacy remote-Agent histories and manual pairing. */+ requireWorkspace?: boolean;+ expectedHostId?: 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. */@@ -119,6 +127,24 @@ export function createRacpRemoteHostClient(try { options.onStateChange?.(state); }catch (error) { options.log?.("warn", "remote state listener threw", { error: String(error) }); }};+ const requireWorkspace = (capability?: "workspaceTools" | "workspaceFiles") => {+ const capabilities = racp.initialized?.capabilities;+ const supported = capability ? capabilities?.[capability] === true+ : capabilities?.workspaceTools === true && capabilities?.workspaceFiles === true;+ if (!supported) {+ throw Object.assign(new Error("Upgrade pi-host to a matching Desktop release with workspace tools and files support"), {+ errorCode: ErrorCodes.HOST_VERSION_MISMATCH,+ retriable: false,+ });+ }+ };+ const validateIdentity = () => {+ if (options.expectedHostId !== undefined && racp.initialized?.server.hostId !== options.expectedHostId) {+ throw Object.assign(new Error("Remote Host identity changed; pair the intended Host again"), {+ errorCode: "HOST_AUTH_FAILED", retriable: false,+ });+ }+ };const racp = new RacpClient({transport: options.transport,client: options.clientInfo,@@ -126,12 +152,14 @@ export function createRacpRemoteHostClient(if (closed && state !== "disconnected") return;// The socket is initialized before onReconnected runs. Do not advertise// readiness until subscription/snapshot recovery has also completed.- if (state === "connected" && visibleState === "reconnecting") return;+ if (state === "connected" && (visibleState === "reconnecting" || options.requireWorkspace || options.expectedHostId)) return;publishState(state);},onSubscriptionClosed: notice => { if (!closed) notify(closedListeners, notice); },onReconnected: async () => {if (closed) return;+ validateIdentity();+ if (options.requireWorkspace) requireWorkspace();const token = generation;const results = await Promise.allSettled([...reconnectListeners].map(listener => Promise.resolve().then(listener)));if (closed || token !== generation) return;@@ -155,7 +183,16 @@ export function createRacpRemoteHostClient(...(options.log ? { log: options.log } : {}),});const client: RemoteHostClient = {- request: (method, params, timeoutMs) => racp.request(method, params, timeoutMs),+ async request<T = unknown>(method: string, params?: unknown, timeoutMs?: number): Promise<T> {+ // Offline errors remain offline errors; capabilities belong to the live handshake.+ if (racp.state === "connected") {+ if (method === "workspace/files") requireWorkspace("workspaceFiles");+ else if (["workspace/toolExecute", "workspace/toolAbort", "workspace/toolShell"].includes(method)) {+ requireWorkspace("workspaceTools");+ }+ }+ return racp.request<T>(method, params, timeoutMs);+ },state: () => visibleState,subscribeReconnect(listener) { reconnectListeners.add(listener); return () => { reconnectListeners.delete(listener); }; },subscribeState(listener) { stateListeners.add(listener); return () => { stateListeners.delete(listener); }; },@@ -173,6 +210,11 @@ export function createRacpRemoteHostClient(async connect() {closed = false;await racp.connect();+ if (options.requireWorkspace || options.expectedHostId) {+ try { validateIdentity(); if (options.requireWorkspace) requireWorkspace(); }+ catch (error) { await racp.close(); throw error; }+ if (!closed && racp.state === "connected") publishState("connected");+ }},async close() {closed = true;diff --git a/apps/desktop/electron/main/remote/remote-deploy-lock.ts b/apps/desktop/electron/main/remote/remote-deploy-lock.tsnew file mode 100644index 000000000..3dca20857--- /dev/null+++ b/apps/desktop/electron/main/remote/remote-deploy-lock.ts@@ -0,0 +1,15 @@+/** Linux kernel-owned deployment lock; unsupported-platform shell fixtures use mkdir. */+export const REMOTE_DEPLOY_LOCK_SCRIPT = `+directory_lock=""+if [ "$(uname -s)" = "Linux" ]; then+ command -v flock >/dev/null 2>&1 || die "missing-flock"+ exec 9>"$base/.deploy.lock"+ flock -w 120 9 || die "deployment-busy"+else+ directory_lock="$base/.deploy-lock"+ mkdir "$directory_lock" 2>/dev/null || die "deployment-busy"+fi+release_deploy_lock() {+ [ -z "$directory_lock" ] || rmdir "$directory_lock" 2>/dev/null || true+}+`;diff --git a/apps/desktop/electron/main/remote/remote-host-metadata.ts b/apps/desktop/electron/main/remote/remote-host-metadata.tsindex ece6ce6f1..b322b3184 100644--- a/apps/desktop/electron/main/remote/remote-host-metadata.ts+++ b/apps/desktop/electron/main/remote/remote-host-metadata.ts@@ -26,8 +26,11 @@ export function sshMetadataOf(record: RemoteHostRecord): RemoteHostSshMetadata |if (port === null && candidate.port !== undefined) return null;const remotePort = safeSshPort(candidate.remotePort);if (remotePort === null) return null;+ const hostId = candidate.hostId;+ if (hostId !== undefined && (typeof hostId !== "string" || !hostId.trim() || hostId.length > 256 || /[\u0000-\u001f]/.test(hostId))) return null;return {host, remotePort,+ ...(hostId !== undefined ? { hostId } : {}),...(port !== null ? { port } : {}),...(user !== null ? { user } : {}),...(identityFile !== null ? { identityFile } : {}),diff --git a/apps/desktop/electron/main/remote/remote-host-supervisor.ts b/apps/desktop/electron/main/remote/remote-host-supervisor.tsnew file mode 100644index 000000000..498234910--- /dev/null+++ b/apps/desktop/electron/main/remote/remote-host-supervisor.ts@@ -0,0 +1,128 @@+import { shellQuote, type PiHostReadyLine } from "./pi-host-bootstrap-script.js";+import { REMOTE_DEPLOY_LOCK_SCRIPT } from "./remote-deploy-lock.js";+import type { SshTransport } from "./ssh-transport.js";++export type RemoteHostSupervisorOptions = {+ version: string;+ expectedHostId?: string;+ readyTimeoutSec?: number;+};++function failure(message: string, errorCode = "HOST_BOOTSTRAP_FAILED"): Error {+ return Object.assign(new Error(message), {+ errorCode, retriable: !["HOST_AUTH_FAILED", "HOST_VERSION_MISMATCH"].includes(errorCode),+ });+}++/** Daily startup only: no installation, pairing, credentials reset or restart. */+export function buildRemoteHostSupervisorScript(readyTimeoutSec = 30): string {+ if (!Number.isInteger(readyTimeoutSec) || readyTimeoutSec < 1 || readyTimeoutSec > 120) {+ throw new Error("Invalid Host ready timeout");+ }+ return `#!/bin/sh+set -eu+umask 077+die() { printf '%s\\n' "PI_HOST_SUPERVISOR_FAILED $1" >&2; exit 1; }+[ -n "\${HOME:-}" ] || die no-home+base="$HOME/.pi-desktop/pi-host"+entry="$base/current/pi-host.js"+work="$base/.bootstrap"+[ ! -L "$work" ] || die unsafe-work-directory+mkdir -p "$work"+chmod 700 "$work" || die work-permissions+${REMOTE_DEPLOY_LOCK_SCRIPT}+trap release_deploy_lock EXIT+trap 'exit 1' HUP INT TERM+[ -f "$entry" ] || die host-not-installed+log="$work/pi-host.log"+err="$work/pi-host.err"+pidfile="$work/pi-host.pid"+for file in "$log" "$err" "$pidfile"; do+ [ ! -L "$file" ] || die unsafe-state-file+ [ ! -e "$file" ] || [ -f "$file" ] || die unsafe-state-file+done+# Match the installed entry point, not a generic node or pi-host process.+physical_entry="$(cd "$base/current" && pwd -P)/pi-host.js"+is_host() {+ kill -0 "$host_pid" 2>/dev/null || return 1+ command_line=$(ps -p "$host_pid" -o command= 2>/dev/null) || die host-process-unreadable+ case " $command_line " in+ *" $entry "*|*" $physical_entry "*) return 0 ;;+ *) die host-pid-mismatch ;;+ esac+}+host_pid=""+if [ -f "$pidfile" ]; then+ host_pid=$(cat "$pidfile")+ case "$host_pid" in ''|*[!0-9]*|0) die invalid-host-pid ;; esac+fi+if [ -z "$host_pid" ] || ! is_host; then+ node="$base/current/bin/node"+ if [ ! -x "$node" ]; then+ node=$(command -v node) || die missing-node+ fi+ major=$("$node" -p 'process.versions.node.split(".")[0]') || die invalid-node+ [ "$major" -ge 22 ] 2>/dev/null || die node-too-old+ # Only discard old ready/token lines after the previous Host is down.+ : > "$log"+ : > "$err"+ nohup "$node" "$entry" --port 0 >"$log" 2>"$err" </dev/null 9>&- &+ host_pid=$!+ printf '%s\\n' "$host_pid" > "$pidfile"+fi+waited=0+while [ "$waited" -lt ${shellQuote(String(readyTimeoutSec))} ]; do+ kill -0 "$host_pid" 2>/dev/null || die host-exited+ grep -q '^PI_HOST_FAILED ' "$log" 2>/dev/null && die host-start-failed+ ready=$(grep -m1 '^PI_HOST_READY ' "$log" 2>/dev/null || true)+ if [ -n "$ready" ]; then+ is_host || die host-exited+ # Never echo a historic single-use pairing token.+ printf '%s\\n' "$ready"+ exit 0+ fi+ sleep 1+ waited=$((waited + 1))+done+die ready-timeout+`;+}++/** Treat SSH stdout as an untrusted boundary; never include it in diagnostics. */+export function parseRemoteHostReady(stdout: string, options: RemoteHostSupervisorOptions): PiHostReadyLine {+ const lines = stdout.trim().split(/\r?\n/);+ if (lines.length !== 1 || !lines[0]?.startsWith("PI_HOST_READY ")) {+ throw failure("Remote Host did not report a single ready line");+ }+ let value: unknown;+ try { value = JSON.parse(lines[0].slice("PI_HOST_READY ".length)); }+ catch { throw failure("Remote Host reported malformed readiness"); }+ if (!value || typeof value !== "object") throw failure("Remote Host reported malformed readiness");+ const { hostId, host, port, version } = value as Record<string, unknown>;+ if (typeof hostId !== "string" || !hostId.trim() ||+ (host !== "127.0.0.1" && host !== "::1") ||+ typeof port !== "number" || !Number.isInteger(port) || port < 1 || port > 65535 ||+ typeof version !== "string" || !version.trim()) {+ throw failure("Remote Host reported invalid readiness");+ }+ if (version.replace(/^v/, "") !== options.version.replace(/^v/, "")) {+ throw failure("Remote Host version does not match the installed descriptor", "HOST_VERSION_MISMATCH");+ }+ if (options.expectedHostId !== undefined && hostId !== options.expectedHostId) {+ throw failure("Remote Host identity changed", "HOST_AUTH_FAILED");+ }+ return { hostId, host, port, version };+}++export async function ensureRemoteHostReady(+ transport: SshTransport,+ options: RemoteHostSupervisorOptions,+): Promise<PiHostReadyLine> {+ const timeout = options.readyTimeoutSec ?? 30;+ const result = await transport.execWithInput("sh -s", buildRemoteHostSupervisorScript(timeout), {+ timeoutMs: (120 + timeout + 15) * 1000,+ maxOutputBytes: 16 * 1024,+ });+ if (result.code !== 0) throw failure("Remote Host startup check failed");+ return parseRemoteHostReady(result.stdout, options);+}diff --git a/apps/desktop/electron/main/remote/remote-workspace-instructions.ts b/apps/desktop/electron/main/remote/remote-workspace-instructions.tsnew file mode 100644index 000000000..fbed461fb--- /dev/null+++ b/apps/desktop/electron/main/remote/remote-workspace-instructions.ts@@ -0,0 +1,25 @@+import type { ProjectInstructions } from "@pi-desktop/agent-runtime";+import type { WorkspaceFilesRequest } from "@pi-desktop/shared";++const SOURCES = new Set(["AGENTS.override.md", "AGENTS.md", "CLAUDE.md", ".claude/CLAUDE.md"]);++/** Host repository instructions only; local global defaults are supplied separately. */+export async function loadRemoteWorkspaceInstructions(+ files: (hostKey: string, input: WorkspaceFilesRequest) => Promise<unknown>,+ workspace: { hostKey: string; path: string },+ defaults?: ProjectInstructions,+): Promise<ProjectInstructions | undefined> {+ const value = await files(workspace.hostKey, { path: workspace.path, operation: "instructions" });+ const invalid = (): never => {+ throw Object.assign(new Error("Remote Host returned invalid repository instructions"), { errorCode: "INVALID_ARGUMENT" });+ };+ if (!value || typeof value !== "object" || !("entries" in value) || !Array.isArray(value.entries) || value.entries.length > 1) return invalid();+ const entries = value.entries.map((entry: unknown) => {+ if (!entry || typeof entry !== "object" || !("source" in entry) || !("content" in entry)+ || typeof entry.source !== "string" || !SOURCES.has(entry.source)+ || typeof entry.content !== "string" || Buffer.byteLength(entry.content, "utf8") > 33_280) return invalid();+ return { source: entry.source, content: entry.content };+ });+ const merged = [...(defaults?.entries ?? []), ...entries];+ return merged.length ? { entries: merged } : undefined;+}diff --git a/apps/desktop/electron/main/remote/remote-workspace-outcome.ts b/apps/desktop/electron/main/remote/remote-workspace-outcome.tsnew file mode 100644index 000000000..b0b28dea7--- /dev/null+++ b/apps/desktop/electron/main/remote/remote-workspace-outcome.ts@@ -0,0 +1,11 @@+/** A lost reply cannot prove whether a side effect reached the remote filesystem. */+export function workspaceExecutionError(toolName: string, error: unknown): unknown {+ if (!["Write", "Edit", "Bash"].includes(toolName)) return error;+ const code = error && typeof error === "object"+ ? "errorCode" in error ? error.errorCode : "code" in error ? error.code : undefined+ : undefined;+ if (!["HOST_DISCONNECTED", "TIMEOUT", "AGENT_UNAVAILABLE", "REMOTE_CONNECTION_FAILED"].includes(String(code))) return error;+ return Object.assign(new Error("Remote mutation outcome is unknown after the connection was interrupted. Inspect the remote files before retrying; this call was not replayed."), {+ errorCode: "REMOTE_MUTATION_OUTCOME_UNKNOWN", retriable: false,+ });+}diff --git a/apps/desktop/electron/main/remote/ssh-artifact-transfer.ts b/apps/desktop/electron/main/remote/ssh-artifact-transfer.tsnew file mode 100644index 000000000..78de5cddf--- /dev/null+++ b/apps/desktop/electron/main/remote/ssh-artifact-transfer.ts@@ -0,0 +1,95 @@+/** Verified release transfer through the existing authenticated OpenSSH transport. */+import { createHash } from "node:crypto";+import { createWriteStream } from "node:fs";+import { mkdtemp, rm } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { Readable, Transform } from "node:stream";+import { pipeline } from "node:stream/promises";+import { ErrorCodes } from "@pi-desktop/shared";+import { shellQuote } from "./pi-host-bootstrap-script.js";+import { checksumMatches, normalizeChecksum } from "./pi-host-release.js";+import type { SshTransport } from "./ssh-transport.js";++const MAX_ARTIFACT_BYTES = 512 * 1024 * 1024;+export type UploadedSshArtifact = { path: string; cleanup(): Promise<void> };+export type SshArtifactTransferInput = {+ url: string; expectedSha256: string; signal?: AbortSignal;+ fetchArtifact?: typeof fetch;+};+function failure(): Error {+ return Object.assign(new Error("The pi-host artifact could not be transferred or verified"), {+ errorCode: ErrorCodes.HOST_BOOTSTRAP_FAILED,+ });+}+/** The path must identify only a directory minted by our remote mktemp command. */+function uploadDirectory(value: string): string {+ const path = value.trim();+ if (!/^\/[^\r\n\0]*\/\.pi-desktop\/pi-host\/\.upload\.[a-zA-Z0-9]{6,}$/.test(path)) throw failure();+ return path;+}+export async function uploadSshArtifact(+ transport: SshTransport, input: SshArtifactTransferInput,+): Promise<UploadedSshArtifact> {+ if (!transport.execWithFile || !normalizeChecksum(input.expectedSha256)) throw failure();+ const url = new URL(input.url);+ if (url.protocol !== "https:" || url.username || url.password) throw failure();+ input.signal?.throwIfAborted();+ const localDir = await mkdtemp(join(tmpdir(), "pi-host-artifact-"));+ let remoteDir: string | undefined;+ const cleanup = async () => {+ if (!remoteDir) return;+ // Never trust remote output to choose a deletion target outside this prefix.+ const directory = shellQuote(remoteDir);+ await transport.exec(`path=${directory}; case "$path" in "$HOME"/.pi-desktop/pi-host/.upload.*) rm -rf -- "$path" ;; *) exit 1 ;; esac`, { timeoutMs: 30_000 });+ remoteDir = undefined;+ };+ try {+ const signal = input.signal ? AbortSignal.any([input.signal, AbortSignal.timeout(600_000)])+ : AbortSignal.timeout(600_000);+ const response = await (input.fetchArtifact ?? fetch)(input.url, { signal, redirect: "follow" });+ if (!response.ok || !response.body) throw failure();+ const hash = createHash("sha256");+ let bytes = 0;+ const verify = new Transform({+ transform(chunk: Buffer, _encoding, callback) {+ bytes += chunk.length;+ if (bytes > MAX_ARTIFACT_BYTES) { callback(failure()); return; }+ hash.update(chunk); callback(null, chunk);+ },+ });+ const reader = response.body.getReader();+ const chunks = (async function* () {+ try {+ for (;;) {+ const chunk = await reader.read();+ if (chunk.done) return;+ yield chunk.value;+ }+ } finally {+ await reader.cancel();+ reader.releaseLock();+ }+ })();+ const localPath = join(localDir, "artifact.tar.gz");+ await pipeline(Readable.from(chunks), verify,+ createWriteStream(localPath, { flags: "wx", mode: 0o600 }), { signal });+ if (!checksumMatches(hash.digest("hex"), input.expectedSha256)) throw failure();+ input.signal?.throwIfAborted();+ const created = await transport.exec('umask 077; mkdir -p "$HOME/.pi-desktop/pi-host" && mktemp -d "$HOME/.pi-desktop/pi-host/.upload.XXXXXX"');+ remoteDir = uploadDirectory(created.stdout);+ input.signal?.throwIfAborted();+ const path = `${remoteDir}/artifact.tar.gz`;+ await transport.execWithFile(`umask 077; cat > ${shellQuote(path)}`, localPath,+ { timeoutMs: 600_000, maxOutputBytes: 16_384 });+ input.signal?.throwIfAborted();+ return { path, cleanup };+ } catch (error) {+ try { await cleanup(); } catch { /* Preserve the original transfer error; remote temp remains private. */ }+ if (input.signal?.aborted) input.signal.throwIfAborted();+ // Fetch/stream/SSH diagnostics are not safe renderer or log payloads.+ throw failure();+ } finally {+ await rm(localDir, { recursive: true, force: true });+ }+}diff --git a/apps/desktop/electron/main/remote/ssh-bootstrap.ts b/apps/desktop/electron/main/remote/ssh-bootstrap.tsindex cf696c0ed..8a5a988b9 100644--- a/apps/desktop/electron/main/remote/ssh-bootstrap.ts+++ b/apps/desktop/electron/main/remote/ssh-bootstrap.ts@@ -8,8 +8,7 @@* 1. probe the remote with `uname` so the artifact is chosen for *its** platform, not the desktop's;* 2. resolve the bundle at the desktop's version and read the SHA-256 the- * release publishes — the desktop holds the trust anchor and never uploads- * executable bytes;+ * release publishes — the desktop holds the trust anchor;* 3. upload the bootstrap script through the SSH channel and run it, which* installs under the remote user's home and starts the host on loopback* with a single-use pairing token;@@ -25,7 +24,7 @@ import {type RemoteHostSshMetadata,} from "@pi-desktop/shared";import {- buildBootstrapScript,+ type PiHostBootstrapScriptInput,parseBootstrapOutput,redactBootstrapOutput,} from "./pi-host-bootstrap-script.js";@@ -50,6 +49,8 @@ import {} from "./ssh-transport.js";import { assertSshPassword } from "./ssh-askpass.js";import { racpUrlForLocalPort } from "./ssh-tunnel.js";+import { installPiHost } from "./pi-host-installer.js";+import type { uploadSshArtifact } from "./ssh-artifact-transfer.js";/** Progress the Settings surface can render while a bootstrap runs. */export type SshBootstrapStep =@@ -57,6 +58,7 @@ export type SshBootstrapStep =| "resolve-release"| "download-checksum"| "install"+ | "upload"| "forward"| "pair";@@ -66,7 +68,8 @@ export type SshBootstrapDeps = {/** Build the SSH transport for one target. Defaults to the system `ssh`. */buildTransport?: (target: SshTarget) => SshTransport;/** Read the published `.sha256` text. Defaults to an HTTPS GET. */- fetchChecksum?: (url: string) => Promise<string>;+ fetchChecksum?: (url: string, signal?: AbortSignal) => Promise<string>;+ uploadArtifact?: typeof uploadSshArtifact;/** Reserve the loopback port the forward binds. */reservePort?: () => Promise<number>;/**@@ -78,6 +81,7 @@ export type SshBootstrapDeps = {url: string;pairingToken: string;label: string;+ expectedHostId: string;}) => Promise<string>;/** Called once per completed step, in order. */onProgress?: (step: SshBootstrapStep) => void;@@ -108,7 +112,7 @@ export type SshBootstrapOutcome = {};export type SshBootstrap = {- bootstrap(request: RemoteHostBootstrapRequest): Promise<SshBootstrapOutcome>;+ bootstrap(request: RemoteHostBootstrapRequest, options?: { signal?: AbortSignal }): Promise<SshBootstrapOutcome>;};const DEFAULT_READY_TIMEOUT_SEC = 120;@@ -173,10 +177,10 @@ export function sshMetadataFromTarget(target: SshTarget): Omit<RemoteHostSshMeta};}-async function defaultFetchChecksum(url: string): Promise<string> {+async function defaultFetchChecksum(url: string, signal?: AbortSignal): Promise<string> {const response = await fetch(url, {redirect: "follow",- signal: AbortSignal.timeout(30_000),+ signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(30_000)]) : AbortSignal.timeout(30_000),});if (!response.ok) {throw fail(`published checksum could not be downloaded (HTTP ${response.status})`, ErrorCodes.HOST_BOOTSTRAP_FAILED, {@@ -246,7 +250,9 @@ export function createSshBootstrap(deps: SshBootstrapDeps): SshBootstrap {const installTimeoutMs = deps.installTimeoutMs ?? DEFAULT_INSTALL_TIMEOUT_MS;return {- async bootstrap(request) {+ async bootstrap(request, options = {}) {+ const signal = options.signal;+ signal?.throwIfAborted();const label = String(request?.label ?? "").trim() || "remote host";const target = validateTarget(request);const hostKey = (request?.hostKey ?? "").trim() || synthesizeSshHostKey(target, label);@@ -261,11 +267,14 @@ export function createSshBootstrap(deps: SshBootstrapDeps): SshBootstrap {};const transport = buildTransport(target);+ const abort = () => transport.dispose();+ signal?.addEventListener("abort", abort, { once: true });let completed = false;try {// 1. Ask the remote machine what it is.mark("probe");const probe = await transport.exec("uname -s && uname -m");+ signal?.throwIfAborted();const remoteTarget = resolveTarget(probe.stdout);if (!remoteTarget) {throw fail(@@ -287,7 +296,8 @@ export function createSshBootstrap(deps: SshBootstrapDeps): SshBootstrap {const urls = piHostArtifactUrls(deps.version, remoteTarget);const artifactName = piHostArtifactName(deps.version, remoteTarget);mark("download-checksum");- const expectedSha256 = parseChecksumFile(await fetchChecksum(urls.checksum), artifactName);+ const expectedSha256 = parseChecksumFile(await fetchChecksum(urls.checksum, signal), artifactName);+ signal?.throwIfAborted();if (!expectedSha256) {throw fail(`no usable SHA-256 published for ${artifactName}`,@@ -296,10 +306,9 @@ export function createSshBootstrap(deps: SshBootstrapDeps): SshBootstrap {);}- // 3. Upload and run the script. It downloads the bundle itself, so no- // executable bytes travel over this channel.+ // 3. Prefer remote download; use a verified upload only if that download fails.mark("install");- const script = buildBootstrapScript({+ const scriptInput: PiHostBootstrapScriptInput = {version: deps.version,artifactUrl: urls.tarball,artifactName,@@ -308,11 +317,12 @@ export function createSshBootstrap(deps: SshBootstrapDeps): SshBootstrap {port: resolveRemotePort(request),pairingLifetimeMs: 600_000,readyTimeoutSec,- });+ };let result: SshExecResult;try {- result = await transport.execWithInput("sh -s", script, {- timeoutMs: installTimeoutMs,+ result = await installPiHost(transport, scriptInput, {+ timeoutMs: installTimeoutMs, signal, uploadArtifact: deps.uploadArtifact,+ onUpload: () => mark("upload"), log,});} catch (error) {// The script names the step it failed at on stdout even when it@@ -356,6 +366,7 @@ export function createSshBootstrap(deps: SshBootstrapDeps): SshBootstrap {// 4. Forward a loopback port to the host's loopback port.mark("forward");const localPort = await reservePort();+ signal?.throwIfAborted();const forward = await transport.forward({localPort,remoteHost: "127.0.0.1",@@ -367,11 +378,14 @@ export function createSshBootstrap(deps: SshBootstrapDeps): SshBootstrap {mark("pair");let deviceToken: string;try {+ signal?.throwIfAborted();deviceToken = await deps.exchangePairing({url,pairingToken: parsed.pairing.token,label,+ expectedHostId: parsed.ready.hostId,});+ signal?.throwIfAborted();} catch (error) {await forward.close().catch(() => undefined);throw error;@@ -381,6 +395,7 @@ export function createSshBootstrap(deps: SshBootstrapDeps): SshBootstrap {...sshMetadataFromTarget(target),remotePort: parsed.ready.port,version: parsed.ready.version,+ hostId: parsed.ready.hostId,};completed = true;log("info", "ssh bootstrap completed", {@@ -412,6 +427,7 @@ export function createSshBootstrap(deps: SshBootstrapDeps): SshBootstrap {});throw error;} finally {+ signal?.removeEventListener("abort", abort);// On success the caller adopts the forward, which is a child of this// transport — disposing here would tear down the tunnel it just got.if (!completed) transport.dispose();diff --git a/apps/desktop/electron/main/remote/ssh-transport.ts b/apps/desktop/electron/main/remote/ssh-transport.tsindex e8dc56d17..392b3bd76 100644--- a/apps/desktop/electron/main/remote/ssh-transport.ts+++ b/apps/desktop/electron/main/remote/ssh-transport.ts@@ -24,6 +24,8 @@*/import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";import { createServer, connect } from "node:net";+import { createReadStream } from "node:fs";+import { pipeline } from "node:stream/promises";import { ErrorCodes } from "@pi-desktop/shared";import { redactBootstrapOutput } from "./pi-host-bootstrap-script.js";import { createSshAskpass, type SshAskpassMaterial } from "./ssh-askpass.js";@@ -64,6 +66,10 @@ export interface SshTransport {input: string,options?: { timeoutMs?: number; maxOutputBytes?: number },): Promise<SshExecResult>;+ /** Stream a verified local artifact over SSH without buffering it in memory. */+ execWithFile?(+ command: string, path: string, options?: { timeoutMs?: number; maxOutputBytes?: number },+ ): Promise<SshExecResult>;/** Forward a loopback port on this machine to a loopback port on the remote. */forward(options: {localPort: number;@@ -238,6 +244,7 @@ function runCommand(args: string[],options: {input?: string;+ inputFile?: string;timeoutMs: number;maxOutputBytes?: number;/** Full environment for the child; defaults to the app's own. */@@ -316,7 +323,18 @@ function runCommand(// A child that exits early closes the pipe under us; swallowing the write// error keeps it from surfacing as an unhandled stream error.child.stdin.on("error", () => undefined);- if (options.input !== undefined) child.stdin.end(options.input);+ if (options.inputFile !== undefined) {+ const source = createReadStream(options.inputFile);+ child.once("close", () => source.destroy());+ void pipeline(source, child.stdin).catch((error: NodeJS.ErrnoException) => {+ // SSH's exit status owns early pipe closure; local read failures do not.+ if (settled || error.code === "EPIPE" || error.code === "ERR_STREAM_PREMATURE_CLOSE") return;+ settled = true;+ clearTimeout(timer);+ child.kill("SIGKILL");+ rejectRun(fail("SSH artifact upload failed", ErrorCodes.HOST_BOOTSTRAP_FAILED));+ });+ } else if (options.input !== undefined) child.stdin.end(options.input);else child.stdin.end();});}@@ -373,6 +391,7 @@ export function createSystemSshTransport(input: string | undefined,timeoutMs: number,maxOutputBytes?: number,+ inputFile?: string,): Promise<SshExecResult> => {// The caller selects the program; bootstrap explicitly requests `sh -s`.// Data sent on stdin must never be interpreted as a shell script implicitly.@@ -382,6 +401,7 @@ export function createSystemSshTransport(try {result = await runCommand(binary, args, {input,+ inputFile,timeoutMs,maxOutputBytes,env,@@ -421,6 +441,8 @@ export function createSystemSshTransport(execOnce(command, undefined, execOptions?.timeoutMs ?? DEFAULT_EXEC_TIMEOUT_MS),execWithInput: (command, input, execOptions) =>execOnce(command, input, execOptions?.timeoutMs ?? DEFAULT_EXEC_TIMEOUT_MS, execOptions?.maxOutputBytes),+ execWithFile: (command, path, execOptions) =>+ execOnce(command, undefined, execOptions?.timeoutMs ?? DEFAULT_EXEC_TIMEOUT_MS, execOptions?.maxOutputBytes, path),async forward({ localPort, remoteHost, remotePort, timeoutMs }) {const env = await acquireEnv();const args = [diff --git a/apps/desktop/electron/main/remote/ssh-tunnel.ts b/apps/desktop/electron/main/remote/ssh-tunnel.tsindex a6a7af195..08118ed24 100644--- a/apps/desktop/electron/main/remote/ssh-tunnel.ts+++ b/apps/desktop/electron/main/remote/ssh-tunnel.ts@@ -12,6 +12,7 @@* about to throw away.*/import { RACP_WS_PATH, type RemoteHostSshMetadata } from "@pi-desktop/shared";+import { ensureRemoteHostReady } from "./remote-host-supervisor.js";import {createSystemSshTransport,reserveLocalPort,@@ -146,11 +147,13 @@ export function createSshTunnelManager(options: SshTunnelManagerOptions = {}): Sconst promise = (async () => {let forward: SshForward | undefined;try {+ const ready = await ensureRemoteHostReady(transport, { version: ssh.version, expectedHostId: ssh.hostId });+ assertActive();const localPort = await reservePort();assertActive();- forward = await transport.forward({ localPort, remoteHost: "127.0.0.1", remotePort: ssh.remotePort });+ forward = await transport.forward({ localPort, remoteHost: ready.host === "::1" ? "[::1]" : ready.host, remotePort: ready.port });assertActive();- log("info", "ssh forward open", { hostKey, localPort: forward.localPort, remotePort: ssh.remotePort });+ log("info", "ssh forward open", { hostKey, localPort: forward.localPort, remotePort: ready.port });return remember(hostKey, ssh, transport, forward);} catch (error) {try {diff --git a/apps/desktop/electron/main/runtime/session-launch.ts b/apps/desktop/electron/main/runtime/session-launch.tsindex 7b0a4b9ef..70a5c0471 100644--- a/apps/desktop/electron/main/runtime/session-launch.ts+++ b/apps/desktop/electron/main/runtime/session-launch.ts@@ -42,6 +42,7 @@ import type { RuntimeState } from "./context";import type { RuntimeProvider } from "./provider-catalog";import type { LoadedSkillDocument } from "../skill-document";import { getActiveRemoteHostsBoot } from "../bootstrap/remote-hosts";+import { loadRemoteWorkspaceInstructions } from "../remote/remote-workspace-instructions.js";const ErrorCodes = {...SharedErrorCodes,@@ -402,6 +403,11 @@ export function createSessionLaunchRuntime({: undefined;const localInstructionRoot = remoteWorkspace ? undefined : projectPath;let projectInstructions = await loadInstructionChain(localInstructionRoot);+ if (remoteWorkspace) {+ projectInstructions = await loadRemoteWorkspaceInstructions(+ remoteBoot!.workspaceFiles, remoteWorkspace, projectInstructions,+ );+ }// pi-compatible SYSTEM.md / APPEND_SYSTEM.md (issue #542): resolved once// per launch; a change retires the runtime through the reuse match.const customSystemPrompt = await loadCustomSystemPrompt(localInstructionRoot);diff --git a/apps/desktop/src/components/remote/RemoteFolderDialog.tsx b/apps/desktop/src/components/remote/RemoteFolderDialog.tsxindex 6b243f8da..6db12774d 100644--- a/apps/desktop/src/components/remote/RemoteFolderDialog.tsx+++ b/apps/desktop/src/components/remote/RemoteFolderDialog.tsx@@ -3,6 +3,7 @@ import { createPortal } from "react-dom";import { useTranslation } from "react-i18next";import type { RemoteHostBrowseProjectsResult } from "@pi-desktop/shared";import { api } from "../../lib/api";+import { remoteHostErrorKey } from "../../lib/remote-host-errors";import { useBlockingOverlay } from "../../lib/blocking-overlay";import { Button, Field, Input, TooltipButton } from "../ui";import { IconChevronRight, IconClose, IconFolder } from "../icons";@@ -35,7 +36,7 @@ export function RemoteFolderDialog({ hostKey, hostLabel, initialPath, onChoose,setDirectory(result);setPath(result.path);} catch (error) {- if (request === generation.current) setError(error instanceof Error ? error.message : String(error));+ if (request === generation.current) setError(t(remoteHostErrorKey(error)));} finally {if (request === generation.current) setBrowsing(false);}diff --git a/apps/desktop/src/components/remote/RemoteProjectPicker.tsx b/apps/desktop/src/components/remote/RemoteProjectPicker.tsxindex b358275c3..d97e6b3d9 100644--- a/apps/desktop/src/components/remote/RemoteProjectPicker.tsx+++ b/apps/desktop/src/components/remote/RemoteProjectPicker.tsx@@ -2,6 +2,7 @@ import { useEffect, useRef, useState } from "react";import { useTranslation } from "react-i18next";import type { RemoteHostSummary } from "@pi-desktop/shared";import { api } from "../../lib/api";+import { remoteHostErrorKey } from "../../lib/remote-host-errors";import { Button, Field, Input, Select } from "../ui";import { RemoteFolderDialog } from "./RemoteFolderDialog";@@ -29,11 +30,10 @@ export function RemoteProjectPicker({ busy, onChange, onBrowsingChange }: {let active = true;void api.listRemoteHosts().then(({ hosts }) => {if (!active) return;- const connected = hosts.filter((host) => host.connected);- setHosts(connected);- setHostKey(connected[0]?.hostKey ?? "");+ setHosts(hosts);+ setHostKey(hosts.find((host) => host.connected)?.hostKey ?? hosts[0]?.hostKey ?? "");}).catch((error: unknown) => {- if (active) setError(error instanceof Error ? error.message : String(error));+ if (active) setError(t(remoteHostErrorKey(error)));}).finally(() => { if (active) setLoading(false); });return () => { active = false; selectionCallback.current(null); browsingCallback.current(false); };}, []);@@ -49,10 +49,11 @@ export function RemoteProjectPicker({ busy, onChange, onBrowsingChange }: {selectionCallback.current(null); setPath(""); setHostKey(event.target.value); setBrowsing(false);}}>{!hosts.length ? <option value="">{t("remote:noConnectedHosts")}</option> : null}- {hosts.map((host) => <option key={host.hostKey} value={host.hostKey}>{host.label}</option>)}+ {hosts.map((host) => <option key={host.hostKey} value={host.hostKey}>{host.connected ? host.label : t("remote:offlineHost", { label: host.label })}</option>)}</Select></Field>{host ? <>+ {!host.connected ? <p role="status">{t("remote:reconnectOnUse")}</p> : null}<Field label={t("remote:projectFolder")}><div className="remote-folder-dialog-path-entry"><Input value={path} aria-label={t("remote:projectFolder")} placeholder={t("remote:pathPlaceholder")} disabled={busy}diff --git a/apps/desktop/src/components/settings/RemoteHostsPage.tsx b/apps/desktop/src/components/settings/RemoteHostsPage.tsxindex d29135c02..1ee49939a 100644--- a/apps/desktop/src/components/settings/RemoteHostsPage.tsx+++ b/apps/desktop/src/components/settings/RemoteHostsPage.tsx@@ -13,6 +13,7 @@ import { useCallback, useEffect, useRef, useState } from "react";import { useTranslation } from "react-i18next";import type { RemoteHostSshAuth, RemoteHostSummary } from "@pi-desktop/shared";import { api } from "../../lib/api";+import { remoteHostErrorKey } from "../../lib/remote-host-errors";import { useAppStore } from "../../stores/app-store";import { Badge, Button, Field, Input, PasswordInput, SegmentedControl, cx } from "../ui";import { RemoteHostSessions } from "./RemoteHostSessions";@@ -27,6 +28,13 @@ type PairForm = {const EMPTY_FORM: PairForm = { url: "", pairingToken: "", label: "" };+function remoteHostStatusKey(host: RemoteHostSummary) {+ if (host.status === "connecting") return "settings.remoteHosts.statusConnecting";+ if (host.status === "reconnecting") return "settings.remoteHosts.statusReconnecting";+ if (host.status === "action-required") return "settings.remoteHosts.statusActionRequired";+ return host.connected ? "settings.remoteHosts.statusOnline" : "settings.remoteHosts.statusOffline";+}+type SshForm = {label: string;host: string;@@ -73,10 +81,10 @@ export function RemoteHostsPage() {setError(null);} catch (caught) {if (!alive.current || generation !== refreshGeneration.current) return;- const message = caught instanceof Error ? caught.message : String(caught);+ const message = t(remoteHostErrorKey(caught));setError(message);}- }, []);+ }, [t]);useEffect(() => {alive.current = true;@@ -93,7 +101,7 @@ export function RemoteHostsPage() {await api.reconnectRemoteHost(host.hostKey);if (alive.current) await refresh();} catch (caught) {- if (alive.current) setError(caught instanceof Error ? caught.message : String(caught));+ if (alive.current) setError(t(remoteHostErrorKey(caught)));} finally {if (alive.current) setReconnecting(null);}@@ -115,7 +123,7 @@ export function RemoteHostsPage() {setForm(EMPTY_FORM);await refresh();} catch (caught) {- const message = caught instanceof Error ? caught.message : String(caught);+ const message = t(remoteHostErrorKey(caught));showToast(t("settings.remoteHosts.pairFailed", { message }), { variant: "error" });} finally {setPairing(false);@@ -134,7 +142,7 @@ export function RemoteHostsPage() {});await refresh();} catch (caught) {- const message = caught instanceof Error ? caught.message : String(caught);+ const message = t(remoteHostErrorKey(caught));showToast(t("settings.remoteHosts.removeFailed", { message }), { variant: "error" });} finally {setRemoving(null);@@ -187,7 +195,7 @@ export function RemoteHostsPage() {setSshForm(EMPTY_SSH_FORM);await refresh();} catch (caught) {- const message = caught instanceof Error ? caught.message : String(caught);+ const message = t(remoteHostErrorKey(caught));showToast(t("settings.remoteHosts.sshFailed", { message }), { variant: "error" });} finally {setInstalling(false);@@ -239,15 +247,13 @@ export function RemoteHostsPage() {<div className="settings-remote-host-name">{host.label}</div><div className="settings-remote-host-meta">{host.transport === "ssh"- ? `${t("settings.remoteHosts.transportSsh")} · ${host.url}`+ ? t("settings.remoteHosts.transportSsh"): host.url}</div></div><span className="settings-remote-host-card-actions">- <Badge tone={host.connected ? "success" : "neutral"}>- {host.connected- ? t("settings.remoteHosts.statusOnline")- : t("settings.remoteHosts.statusOffline")}+ <Badge tone={host.connected ? "success" : host.status === "action-required" ? "warning" : "neutral"}>+ {t(remoteHostStatusKey(host))}</Badge><Button variant="secondary" onClick={() => setSelectedHost(host)}>{remoteT("sessions")}diff --git a/apps/desktop/src/lib/remote-host-errors.ts b/apps/desktop/src/lib/remote-host-errors.tsnew file mode 100644index 000000000..af593c212--- /dev/null+++ b/apps/desktop/src/lib/remote-host-errors.ts@@ -0,0 +1,21 @@+/** Only approved localized summaries cross into remote-host UI; never raw stderr. */+export function remoteHostErrorKey(error: unknown): string {+ let code: unknown;+ if (error && typeof error === "object") {+ code = "errorCode" in error ? error.errorCode : "code" in error ? error.code : undefined;+ }+ switch (code) {+ case "REMOTE_PATH_NOT_FOUND": return "remote:pathUnavailable";+ case "REMOTE_PATH_FORBIDDEN": return "remote:pathForbidden";+ case "HOST_VERSION_MISMATCH": return "remote:upgradeRequired";+ case "HOST_AUTH_FAILED":+ case "SSH_AUTH_FAILED":+ case "TOKEN_INVALID":+ case "PAIRING_FAILED": return "remote:authenticationRequired";+ case "HOST_DISCONNECTED":+ case "REMOTE_CONNECTION_FAILED":+ case "AGENT_UNAVAILABLE": return "remote:connectionUnavailable";+ case "REMOTE_MUTATION_OUTCOME_UNKNOWN": return "remote:mutationUncertain";+ default: return "remote:operationFailed";+ }+}diff --git a/apps/desktop/src/locales/remote.ts b/apps/desktop/src/locales/remote.tsindex 0216dbc7b..e048f9e7d 100644--- a/apps/desktop/src/locales/remote.ts+++ b/apps/desktop/src/locales/remote.ts@@ -1,5 +1,5 @@export const remoteEn = {- projectHost: "Host", noConnectedHosts: "Connect a remote host in Settings first.",+ projectHost: "Host", noConnectedHosts: "Add a remote host in Settings first.",projectFolder: "Remote folder", chooseFolder: "Choose a folder or enter its path",browseFolders: "Browse folders", useFolder: "Use this folder",folderPickerTitle: "Choose a folder", folderPath: "Folder path", goToFolder: "Go",@@ -11,6 +11,14 @@ export const remoteEn = {refresh: "Refresh",close: "Close",loading: "Working…",+ offlineHost: "{{label}} (offline)", reconnectOnUse: "This host is offline. Browsing or opening the project will reconnect it.",+ pathUnavailable: "The remote directory is unavailable. Check the path and try again.",+ pathForbidden: "This path is outside the allowed remote workspace.",+ upgradeRequired: "Upgrade the remote Host to a matching Desktop release.",+ authenticationRequired: "Authentication failed. Check SSH access or pair the Host again.",+ connectionUnavailable: "The remote Host is unavailable. Check the connection and try again.",+ operationFailed: "The remote operation failed. Check the Host connection and try again.",+ mutationUncertain: "The connection was interrupted; the remote change may have completed. Check the files before retrying.",empty: "No remote conversations yet.",project: "Remote project",selectProject: "Select a remote project",@@ -51,7 +59,7 @@ export const remoteEn = {};export const remoteZh: typeof remoteEn = {- projectHost: "主机", noConnectedHosts: "请先在设置中连接远程主机。",+ projectHost: "主机", noConnectedHosts: "请先在设置中添加远程主机。",projectFolder: "远程文件夹", chooseFolder: "选择文件夹或输入路径",browseFolders: "浏览文件夹", useFolder: "使用此文件夹",folderPickerTitle: "选择文件夹", folderPath: "文件夹路径", goToFolder: "前往",@@ -59,6 +67,13 @@ export const remoteZh: typeof remoteEn = {older: "加载更早消息", thinking: "思考",newer: "加载较新消息", latest: "返回最新消息",sessions: "会话 / 新建会话", reconnect: "重新连接", refresh: "刷新", close: "关闭", loading: "处理中…",+ offlineHost: "{{label}}(离线)", reconnectOnUse: "主机已离线。浏览或打开项目时会尝试重新连接。",+ pathUnavailable: "远程目录不可用,请检查路径后重试。", pathForbidden: "此路径超出允许的远程工作区。",+ upgradeRequired: "请将远程 Host 升级到与 Desktop 匹配的版本。",+ authenticationRequired: "认证失败,请检查 SSH 登录或重新配对主机。",+ connectionUnavailable: "远程主机不可用,请检查连接后重试。",+ operationFailed: "远程操作失败,请检查主机连接后重试。",+ mutationUncertain: "连接已中断,远程修改可能已完成。请先检查文件,不要直接重试。",empty: "暂无远程会话。", project: "远程项目", selectProject: "选择远程项目",path: "或注册远程绝对路径", pathPlaceholder: "/home/user/project", title: "会话标题(可选)",create: "创建远程会话", defaultModel: "新会话使用远程主机的默认模型,需要时请先同步模型。使用 Agent 模式并逐次询问权限。",diff --git a/apps/desktop/test/boot-remote-hosts.test.mjs b/apps/desktop/test/boot-remote-hosts.test.mjsindex aa56d3828..35e300dcf 100644--- a/apps/desktop/test/boot-remote-hosts.test.mjs+++ b/apps/desktop/test/boot-remote-hosts.test.mjs@@ -45,6 +45,7 @@ function fakeAdapter(options = {}) {let state = "disconnected";return {requests,+ setState: next => { state = next; },state: () => state,async connect() {if (options.connectRejects) throw options.connectRejects;@@ -60,13 +61,11 @@ function fakeAdapter(options = {}) {client: {request: async (method, params, timeoutMs) => {requests.push({ method, params, ...(timeoutMs ? { timeoutMs } : {}) });- if (options.request && method.startsWith("workspace/")) return options.request(method, params);- if (method === "session/list") {- return { sessions: options.sessions ?? [] };- }+ if (options.request && (method.startsWith("workspace/") || method.startsWith("project/"))) return options.request(method, params);+ if (method === "session/list") return { sessions: options.sessions ?? [] };if (method === "events/subscribe") return { subscriptionId: `sub-${params.sessionId ?? "host"}`, starting: { epoch: "e1", sequence: 1 }, replayComplete: true };if (method === "session/attach") {- const session = options.sessions.find((row) => row.id === params.sessionId);+ const session = options.sessions.find(row => row.id === params.sessionId);return { session, snapshot: { session, items: [], activeItems: [], pendingApprovals: [], pendingInputs: [], queuedTurns: [], hasMoreHistory: false, cursor: { epoch: "e1", sequence: 0 }, revision: 1, generatedAt: session.updatedAt } };}return { ok: true };@@ -78,7 +77,6 @@ function fakeAdapter(options = {}) {},};}-function makeSession(id) {return {id,@@ -94,6 +92,32 @@ function makeSession(id) {};}+test("remote host summaries expose live connection lifecycle states", async () => {+ const { dir, cleanup } = await tmpDir();+ const started = Promise.withResolvers();+ const connected = Promise.withResolvers();+ const adapter = fakeAdapter();+ adapter.connect = () => { adapter.setState("connecting"); started.resolve(); return connected.promise.then(() => adapter.setState("connected")); };+ const boot = createRemoteHostsBoot({ dataDir: dir, encryption: reversibleEncryption(), router: createBackendRouter(),+ emit: () => {}, clientInfo: { name: "test", version: "1" }, buildAdapter: () => adapter });+ try {+ await boot.registry.upsert({ hostKey: "stateful", label: "Stateful", url: "wss://stateful", deviceToken: "t" });+ const opening = boot.open();+ await started.promise;+ assert.equal((await boot.list())[0].status, "connecting");+ connected.resolve();+ await opening;+ assert.deepEqual(await boot.list().then(([host]) => ({ connected: host.connected, status: host.status })), { connected: true, status: "connected" });+ adapter.setState("reconnecting");+ assert.equal((await boot.list())[0].status, "reconnecting");+ adapter.setState("error");+ const needsAction = (await boot.list())[0];+ assert.equal(needsAction.connected, false);+ assert.equal(needsAction.status, "action-required");+ await boot.removeHost("stateful");+ } finally { await boot.closeAll(); await cleanup(); }+});+test("open on an empty registry is a no-op: nothing registers, closeAll clean", async () => {const { dir, cleanup } = await tmpDir();const router = createBackendRouter();@@ -256,7 +280,10 @@ test("closeAll disposes a pending SSH forward before draining host operations",let adapters = 0;const tunnels = createSshTunnelManager({reservePort: async () => 1234,- buildTransport: () => ({ forward: () => { started.resolve(); return forwarding.promise; }, dispose: () => { disposed++; } }),+ buildTransport: () => ({+ execWithInput: async () => ({ stdout: 'PI_HOST_READY {"hostId":"fixture","host":"127.0.0.1","port":1234,"version":"0.15.0"}', stderr: "", code: 0 }),+ forward: () => { started.resolve(); return forwarding.promise; }, dispose: () => { disposed++; },+ }),});const boot = createRemoteHostsBoot({dataDir: dir, encryption: reversibleEncryption(), router: createBackendRouter(), emit: () => undefined,@@ -378,15 +405,92 @@ test("workspace execution keeps model configuration local and extends only the ttest("failed workspace execution cancels once and never replays a side effect", async () => {const { dir, cleanup } = await tmpDir();const adapter = fakeAdapter({ request: async (method) => {- if (method === "workspace/toolExecute") throw new Error("disconnected");+ if (method === "workspace/toolExecute") throw Object.assign(new Error("disconnected"), { errorCode: "HOST_DISCONNECTED" });return { ok: true };} });const boot = createRemoteHostsBoot({ dataDir: dir, encryption: reversibleEncryption(), router: createBackendRouter(),emit: () => {}, clientInfo: { name: "test", version: "1" }, buildAdapter: () => adapter });try {await boot.addHost({ hostKey: "ssh", label: "SSH", url: "wss://fixture", deviceToken: "fixture-only" });- await assert.rejects(boot.executeWorkspaceTool({ hostKey: "ssh", path: "/workspace", sessionId: "local", turnId: "turn", toolCallId: "write", toolName: "Write", args: { path: "out", content: "new" } }), /disconnected/);+ await assert.rejects(boot.executeWorkspaceTool({ hostKey: "ssh", path: "/workspace", sessionId: "local", turnId: "turn", toolCallId: "write", toolName: "Write", args: { path: "out", content: "new" } }), { errorCode: "REMOTE_MUTATION_OUTCOME_UNKNOWN", retriable: false });assert.equal(adapter.requests.filter(row => row.method === "workspace/toolExecute").length, 1);assert.equal(adapter.requests.filter(row => row.method === "workspace/toolAbort").length, 1);} finally { await boot.closeAll(); await cleanup(); }});++test("offline project browsing restores one connection shared by concurrent user entries", async () => {+ const { dir, cleanup } = await tmpDir();+ let builds = 0;+ const adapter = fakeAdapter({ request: async (method, params) => {+ if (method === "project/browse") return { path: params.path ?? "/remote", entries: [] };+ if (method === "workspace/files") return { files: [] };+ throw new Error(`unexpected method ${method}`);+ } });+ const boot = createRemoteHostsBoot({+ dataDir: dir, encryption: reversibleEncryption(), router: createBackendRouter(), emit: () => undefined,+ clientInfo: { name: "test", version: "0.15.0" }, buildAdapter: () => { builds++; return adapter; },+ });+ try {+ await boot.registry.upsert({ hostKey: "offline", label: "Offline", url: "wss://offline", deviceToken: "t" });+ assert.equal((await boot.list())[0].connected, false);+ const [browse, files, ready] = await Promise.all([+ boot.browseProjects("offline", "/remote/repo"),+ boot.workspaceFiles("offline", { operation: "list", root: "/remote/repo" }),+ boot.ensureReady("offline"),+ ]);+ assert.equal(browse.path, "/remote/repo");+ assert.deepEqual(files, { files: [] });+ assert.equal(ready.connected, true);+ assert.equal(builds, 1);+ assert.equal((await boot.list())[0].connected, true);+ await boot.ensureReady("offline");+ assert.equal(builds, 1, "ready connection must not restart");+ await boot.closeAll();+ await assert.rejects(boot.ensureReady("offline"), { errorCode: "AGENT_UNAVAILABLE" });+ assert.equal(builds, 1);+ } finally { await boot.closeAll(); await cleanup(); }+});++test("concurrent readiness failures share one attempt and allow a later explicit retry", async () => {+ const { dir, cleanup } = await tmpDir();+ let builds = 0;+ const failure = Object.assign(new Error("revoked"), { errorCode: "HOST_AUTH_FAILED", retriable: false });+ const boot = createRemoteHostsBoot({ dataDir: dir, encryption: reversibleEncryption(), router: createBackendRouter(),+ emit: () => {}, clientInfo: { name: "test", version: "1" },+ buildAdapter: () => { builds++; return fakeAdapter({ connectRejects: failure }); } });+ try {+ await boot.registry.upsert({ hostKey: "offline", label: "Offline", url: "wss://offline", deviceToken: "t" });+ const results = await Promise.allSettled([boot.ensureReady("offline"), boot.browseProjects("offline"),+ boot.workspaceFiles("offline", { operation: "list", root: "/repo" })]);+ assert.ok(results.every(result => result.status === "rejected" && result.reason === failure));+ assert.equal(builds, 1);+ assert.equal((await boot.list())[0].status, "action-required");+ await assert.rejects(boot.ensureReady("offline"), { errorCode: "HOST_AUTH_FAILED" });+ assert.equal(builds, 2);+ assert.equal((await boot.list())[0].status, "action-required", "auth failure remains visible after the adapter is closed");+ await boot.removeHost("offline");+ await assert.rejects(boot.ensureReady("offline"), { errorCode: "AGENT_UNAVAILABLE" });+ assert.equal(builds, 2);+ } finally { await boot.closeAll(); await cleanup(); }+});++test("shutdown cancels shared readiness and fences every concurrent waiter", async () => {+ const { dir, cleanup } = await tmpDir();+ const connecting = Promise.withResolvers();+ const started = Promise.withResolvers();+ let builds = 0;+ const adapter = fakeAdapter();+ adapter.connect = () => { started.resolve(); return connecting.promise; };+ adapter.close = async () => { connecting.reject(new Error("closed")); };+ const boot = createRemoteHostsBoot({ dataDir: dir, encryption: reversibleEncryption(), router: createBackendRouter(),+ emit: () => {}, clientInfo: { name: "test", version: "1" }, buildAdapter: () => { builds++; return adapter; } });+ try {+ await boot.registry.upsert({ hostKey: "offline", label: "Offline", url: "wss://offline", deviceToken: "t" });+ const waiters = Promise.allSettled([boot.ensureReady("offline"), boot.ensureReady("offline")]);+ await started.promise;+ await boot.closeAll();+ assert.ok((await waiters).every(result => result.status === "rejected"));+ assert.equal(builds, 1);+ assert.equal((await boot.list())[0].connected, false);+ } finally { await boot.closeAll(); await cleanup(); }+});diff --git a/apps/desktop/test/racp-remote-host-client.test.mjs b/apps/desktop/test/racp-remote-host-client.test.mjsindex 4b69a973d..40100ec37 100644--- a/apps/desktop/test/racp-remote-host-client.test.mjs+++ b/apps/desktop/test/racp-remote-host-client.test.mjs@@ -31,6 +31,53 @@ function ownerTransport({ server, authenticator }) {};}+test("new workspace pairing rejects an old Host immediately and closes the connection", async () => {+ const h = await harness();+ const adapter = createRacpRemoteHostClient({+ transport: ownerTransport(h), clientInfo: { name: "test", version: "1" },+ requireWorkspace: true,+ });+ try {+ await assert.rejects(adapter.connect(), error => error.errorCode === "HOST_VERSION_MISMATCH"+ && /upgrade/i.test(error.message));+ assert.equal(adapter.state(), "disconnected");+ } finally { await adapter.close(); }+});++test("legacy Agent remains usable but unsupported workspace calls fail before dispatch", async () => {+ const h = await harness();+ const adapter = createRacpRemoteHostClient({+ transport: ownerTransport(h), clientInfo: { name: "test", version: "1" },+ });+ try {+ await adapter.connect();+ assert.ok(Array.isArray((await adapter.client.request("session/list")).sessions));+ for (const method of ["workspace/toolShell", "workspace/toolExecute", "workspace/toolAbort", "workspace/files"]) {+ await assert.rejects(adapter.client.request(method, {}), error => error.errorCode === "HOST_VERSION_MISMATCH"+ && /upgrade/i.test(error.message));+ }+ assert.equal(adapter.state(), "connected");+ } finally { await adapter.close(); }+});++test("new workspace connection requires both capabilities and executes the real RACP path", async () => {+ const tools = { shell: async () => ({ id: "bash" }), execute: async () => ({ ok: true, content: "remote" }),+ abort: async () => {}, disconnect: async () => {} };+ const incomplete = await harness({ operations: { workspaceTools: tools } });+ const refused = createRacpRemoteHostClient({ transport: ownerTransport(incomplete),+ clientInfo: { name: "test", version: "1" }, requireWorkspace: true });+ try { await assert.rejects(refused.connect(), error => error.errorCode === "HOST_VERSION_MISMATCH"); }+ finally { await refused.close(); }+ const h = await harness({ operations: { workspaceTools: tools,+ workspaceFiles: { read: async () => ({ content: "README" }) } } });+ const adapter = createRacpRemoteHostClient({ transport: ownerTransport(h),+ clientInfo: { name: "test", version: "1" }, requireWorkspace: true });+ try {+ await adapter.connect();+ assert.deepEqual(await adapter.client.request("workspace/toolShell", {}), { shell: { id: "bash" } });+ } finally { await adapter.close(); }+});+test("adapter connects, request delegates to RacpClient, close is clean", async () => {const h = await harness();const adapter = createRacpRemoteHostClient({@@ -158,3 +205,18 @@ test("adapter exposes detachable reconnect, state, and subscription-closed listeawait adapter.close();assert.deepEqual(states, ["connecting", "connected"]);});++test("identity mismatch never advertises a usable Host or dispatches requests", async () => {+ const h = await harness();+ const states = [];+ const adapter = createRacpRemoteHostClient({+ transport: ownerTransport(h), clientInfo: { name: "test", version: "1" },+ expectedHostId: "different-installation", onStateChange: state => states.push(state),+ });+ try {+ await assert.rejects(adapter.connect(), error => error.errorCode === "HOST_AUTH_FAILED" && error.retriable === false);+ assert.equal(adapter.state(), "disconnected");+ assert.ok(!states.includes("connected"));+ await assert.rejects(adapter.client.request("session/list"));+ } finally { await adapter.close(); }+});diff --git a/apps/desktop/test/remote-host-artifact-transfer.test.mjs b/apps/desktop/test/remote-host-artifact-transfer.test.mjsnew file mode 100644index 000000000..c436773c4--- /dev/null+++ b/apps/desktop/test/remote-host-artifact-transfer.test.mjs@@ -0,0 +1,126 @@+import assert from "node:assert/strict";+import test from "node:test";+import { createHash } from "node:crypto";+import { mkdtemp, readFile, writeFile, rm, stat } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { register } from "node:module";+register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url));+const { uploadSshArtifact } = await import("../electron/main/remote/ssh-artifact-transfer.ts");+const { createSshBootstrap } = await import("../electron/main/remote/ssh-bootstrap.ts");+const { createSystemSshTransport } = await import("../electron/main/remote/ssh-transport.ts");+const bytes = Buffer.from([0, 255, 10, 13, 42, 0, 123]);+const digest = createHash("sha256").update(bytes).digest("hex");+const url = "https://github.com/example/release/artifact.tar.gz";+const remoteDir = "/home/test/.pi-desktop/pi-host/.upload.ABC123";+function transferFixture(overrides = {}) {+ const commands = [], uploads = [];+ const transport = {+ async exec(command) { commands.push(command); return { stdout: `${remoteDir}\n`, stderr: "", code: 0 }; },+ async execWithFile(command, path) {+ uploads.push({ command, path, data: await readFile(path), mode: (await stat(path)).mode & 0o777 });+ return { stdout: "", stderr: "", code: 0 };+ }, ...overrides,+ };+ return { transport, commands, uploads };+}+test("verified bytes stream over SSH, temporary local bytes are removed, cleanup is idempotent", async () => {+ const f = transferFixture();+ const artifact = await uploadSshArtifact(f.transport, { url, expectedSha256: digest,+ fetchArtifact: async () => new Response(bytes) });+ assert.equal(artifact.path, `${remoteDir}/artifact.tar.gz`);+ assert.deepEqual(f.uploads[0].data, bytes);+ assert.equal(f.uploads[0].mode, 0o600);+ await assert.rejects(stat(f.uploads[0].path), { code: "ENOENT" });+ await artifact.cleanup(); await artifact.cleanup();+ assert.equal(f.commands.length, 2);+ assert.match(f.commands[1], /case.*HOME/);+});+test("tampering is refused before any remote command", async () => {+ const f = transferFixture();+ await assert.rejects(uploadSshArtifact(f.transport, { url, expectedSha256: digest,+ fetchArtifact: async () => new Response("tampered") }), { errorCode: "HOST_BOOTSTRAP_FAILED" });+ assert.equal(f.commands.length, 0); assert.equal(f.uploads.length, 0);+});+test("unsafe deletion paths from remote stdout are never used", async () => {+ const f = transferFixture({ exec: async () => ({ stdout: "/home/test\n", stderr: "", code: 0 }) });+ await assert.rejects(uploadSshArtifact(f.transport, { url, expectedSha256: digest,+ fetchArtifact: async () => new Response(bytes) }), { errorCode: "HOST_BOOTSTRAP_FAILED" });+ assert.equal(f.uploads.length, 0);+});+test("a failed upload cleans its own remote directory without leaking diagnostics", async () => {+ const f = transferFixture({ execWithFile: async () => { throw new Error("private-token-sentinel"); } });+ await assert.rejects(uploadSshArtifact(f.transport, { url, expectedSha256: digest,+ fetchArtifact: async () => new Response(bytes) }), error => error.errorCode === "HOST_BOOTSTRAP_FAILED"+ && !error.message.includes("private-token-sentinel"));+ assert.equal(f.commands.length, 2);+});+test("already cancelled transfer does not fetch or create remote state", async () => {+ const f = transferFixture();+ const controller = new AbortController(); controller.abort();+ await assert.rejects(uploadSshArtifact(f.transport, { url, expectedSha256: digest, signal: controller.signal,+ fetchArtifact: () => assert.fail("must not fetch") }), { name: "AbortError" });+ assert.equal(f.commands.length, 0);+});+function bootstrapFixture(step = "download-failed") {+ const scripts = [], uploads = [], paired = [];+ let cleanups = 0, disposed = 0, forwarded = 0;+ const bootstrap = createSshBootstrap({ version: "1.0.0", fetchChecksum: async () => digest,+ reservePort: async () => 40000,+ buildTransport: () => ({+ exec: async () => ({ stdout: "Linux\nx86_64\n", stderr: "", code: 0 }),+ execWithInput: async (_command, script) => {+ scripts.push(script);+ if (scripts.length === 1) throw Object.assign(new Error("remote download failed"), {+ stdout: `PI_HOST_BOOTSTRAP_FAILED ${step}\n`, stderr: "" });+ return { stdout: 'PI_HOST_READY {"hostId":"fixture","host":"127.0.0.1","port":41000,"version":"1.0.0"}\nPI_HOST_PAIRING_TOKEN {"token":"test","expiresAt":1}\n', stderr: "", code: 0 };+ },+ forward: async () => { forwarded++; return { localPort: 40000, close: async () => {} }; },+ dispose: () => { disposed++; },+ }),+ uploadArtifact: async (_transport, input) => { uploads.push(input); return {+ path: `${remoteDir}/artifact.tar.gz`, cleanup: async () => { cleanups++; },+ }; },+ exchangePairing: async input => { paired.push(input); return "device"; },+ });+ return { bootstrap, scripts, uploads, paired, counts: () => ({ cleanups, disposed, forwarded }) };+}+test("remote download failure takes one verified upload path then pairs successfully", async () => {+ const f = bootstrapFixture();+ const result = await f.bootstrap.bootstrap({ host: "test", label: "test" });+ assert.equal(result.deviceToken, "device");+ assert.equal(f.uploads.length, 1); assert.equal(f.scripts.length, 2); assert.equal(f.paired.length, 1);+ assert.equal(f.uploads[0].expectedSha256, digest);+ assert.match(f.scripts[1], /ARTIFACT_PATH='\/home\/test\/\.pi-desktop\/pi-host\/\.upload.ABC123\/artifact.tar.gz'/);+ assert.deepEqual(f.counts(), { cleanups: 1, disposed: 0, forwarded: 1 });+});+test("checksum failure never falls back or forwards", async () => {+ const f = bootstrapFixture("checksum-mismatch");+ await assert.rejects(f.bootstrap.bootstrap({ host: "test", label: "test" }), error => error.step === "checksum-mismatch");+ assert.equal(f.uploads.length, 0); assert.equal(f.paired.length, 0);+ assert.deepEqual(f.counts(), { cleanups: 0, disposed: 1, forwarded: 0 });+});+test("cancellation while checksum waits cannot resume installation", async () => {+ const gate = Promise.withResolvers(); const controller = new AbortController();+ let installs = 0;+ const bootstrap = createSshBootstrap({ version: "1", fetchChecksum: () => gate.promise,+ exchangePairing: () => assert.fail("must not pair"), buildTransport: () => ({+ exec: async () => ({ stdout: "Linux\nx86_64\n", stderr: "", code: 0 }),+ execWithInput: async () => { installs++; }, dispose() {},+ }) });+ const pending = bootstrap.bootstrap({ host: "test", label: "test" }, { signal: controller.signal });+ controller.abort(); gate.resolve(digest);+ await assert.rejects(pending, { name: "AbortError" }); assert.equal(installs, 0);+});+test("system SSH file transport preserves binary stdin", async () => {+ const dir = await mkdtemp(join(tmpdir(), "ssh-file-stream-"));+ const binary = join(dir, "ssh"), source = join(dir, "source"), dest = join(dir, "dest");+ await writeFile(binary, '#!/bin/sh\nfor arg do command="$arg"; done\nexec sh -c "$command"\n', { mode: 0o755 });+ await writeFile(source, bytes);+ const transport = createSystemSshTransport({ host: "fixture" }, { binary });+ try {+ await transport.execWithFile(`cat > '${dest}'`, source);+ assert.deepEqual(await readFile(dest), bytes);+ await assert.rejects(transport.execWithFile("cat >/dev/null", join(dir, "missing")), { errorCode: "HOST_BOOTSTRAP_FAILED" });+ } finally { transport.dispose(); await rm(dir, { recursive: true, force: true }); }+});diff --git a/apps/desktop/test/remote-host-bootstrap-script.test.mjs b/apps/desktop/test/remote-host-bootstrap-script.test.mjsindex 183c36722..2f46c8f16 100644--- a/apps/desktop/test/remote-host-bootstrap-script.test.mjs+++ b/apps/desktop/test/remote-host-bootstrap-script.test.mjs@@ -3,7 +3,7 @@ import test from "node:test";import { execFileSync } from "node:child_process";import { createHash } from "node:crypto";import { existsSync } from "node:fs";-import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";+import { chmod, copyFile, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";import { register } from "node:module";import { tmpdir } from "node:os";import { dirname, join } from "node:path";@@ -75,11 +75,16 @@ async function prepareSandbox(root, { readyVersion = VERSION } = {}) {'import { createHash } from "node:crypto";','import { readFileSync } from "node:fs";',"const file = process.argv[2];",+ 'if (file === "-c") {',+ ' const manifest = readFileSync(process.argv[3], "utf8").trim().split("\\n");',+ ' for (const line of manifest) { const [hash, path] = line.split(/ /); if (createHash("sha256").update(readFileSync(path)).digest("hex") !== hash) process.exit(1); }',+ ' process.exit(0);',+ '}','process.stdout.write(`${createHash("sha256").update(readFileSync(file)).digest("hex")} ${file}\\n`);',"",].join("\n"),);- await writeFile(join(bin, "sha256sum"), `#!/bin/sh\nexec "${process.execPath}" "${sha256Helper}" "$1"\n`, {+ await writeFile(join(bin, "sha256sum"), `#!/bin/sh\nexec "${process.execPath}" "${sha256Helper}" "$@"\n`, {mode: 0o755,});@@ -356,6 +361,9 @@ test("parseBootstrapOutput refuses a ready line with an unusable port", () => {assert.equal(ready({ ...valid, port: 41234.5 }).ready, null, "a fractional port is not a port");assert.equal(ready({ ...valid, port: "41234" }).ready, null, "a string port is not a port");assert.equal(ready({ ...valid, hostId: "" }).ready, null);+ assert.equal(ready({ ...valid, port: 65536 }).ready, null);+ assert.equal(ready({ ...valid, host: "0.0.0.0" }).ready, null);+ assert.equal(ready({ ...valid, host: "example.com" }).ready, null);assert.equal(parseBootstrapOutput("PI_HOST_READY {not json").ready, null);// The pairing line tolerates a missing expiry rather than dropping the token.@@ -363,3 +371,60 @@ test("parseBootstrapOutput refuses a ready line with an unusable port", () => {assert.deepEqual(pairing.pairing, { token: "ppt1.abc", expiresAt: 0 });assert.equal(parseBootstrapOutput('PI_HOST_PAIRING_TOKEN {"expiresAt":1}').pairing, null);});++async function seedVerifiedInstall(root, sandbox) {+ const base = join(sandbox.home, ".pi-desktop/pi-host");+ const current = join(base, "current");+ await mkdir(join(current, "bin"), { recursive: true });+ await copyFile(join(root, "bin/node"), join(current, "bin/node"));+ await copyFile(fileURLToPath(new URL("../../pi-host/scripts/install.sh", import.meta.url)), join(current, "install.sh"));+ await chmod(join(current, "install.sh"), 0o755);+ const files = ["bin/node", "bin/pi-host", "bin/pi-desktop-host-core", "pi-host.js", "install.sh"];+ for (const file of ["bin/pi-host", "bin/pi-desktop-host-core", "pi-host.js"]) {+ await writeFile(join(current, file), "#!/bin/sh\nexit 0\n", { mode: 0o755 });+ }+ const manifest = (await Promise.all(files.map(async (file) => `${createHash("sha256").update(await readFile(join(current, file))).digest("hex")} ${file}\n`))).join("");+ await writeFile(join(current, "SHA256SUMS"), manifest);+ const manifestDigest = createHash("sha256").update(manifest).digest("hex");+ await writeFile(join(base, ".release.sha256"), `${VERSION} ${sandbox.digest} ${manifestDigest}\n`);+ await writeFile(join(root, "bin/curl"), "#!/bin/sh\nexit 1\n", { mode: 0o755 });+ return { base, current };+}++test("a fully verified release is reused without a download", async () => {+ const { dir, cleanup } = await tempDir("pi-host-reuse-");+ try {+ const sandbox = await prepareSandbox(dir);+ const { current } = await seedVerifiedInstall(dir, sandbox);+ // Any accidental system Node dependency must fail this scenario.+ await writeFile(join(dir, "bin/node"), "#!/bin/sh\nexit 1\n", { mode: 0o755 });+ const script = join(dir, "bootstrap.sh");+ await writeFile(script, buildBootstrapScript(scriptInput({ expectedSha256: sandbox.digest })));+ const result = parseBootstrapOutput(runScript(script, sandbox.env));+ assert.deepEqual(result.steps, ["reuse", "start", "await-ready", "ok"]);+ assert.equal(result.ready?.port, 41234);+ assert.equal(result.pairing?.token, "ppt1.stub");+ assert.equal(existsSync(join(current, ".release.sha256")), false);+ } finally { await cleanup(); }+});++for (const kind of ["damaged", "different-release", "changed-manifest"]) {+ test(`refuses ${kind} reuse and preserves installed contents on download failure`, async () => {+ const { dir, cleanup } = await tempDir("pi-host-reuse-refused-");+ try {+ const sandbox = await prepareSandbox(dir);+ const { current } = await seedVerifiedInstall(dir, sandbox);+ if (kind === "damaged") await writeFile(join(current, "pi-host.js"), "damaged");+ if (kind === "changed-manifest") await writeFile(join(current, "SHA256SUMS"), "tampered manifest");+ const before = await readFile(join(current, "pi-host.js"));+ const script = join(dir, "bootstrap.sh");+ await writeFile(script, buildBootstrapScript(scriptInput({ expectedSha256: kind === "different-release" ? DIGEST : sandbox.digest })));+ assert.throws(() => runScript(script, sandbox.env), (error) => {+ assert.match(String(error.stderr), /PI_HOST_BOOTSTRAP_FAILED download-failed/);+ assert.ok(!String(error.stdout).includes("PI_HOST_BOOTSTRAP reuse"));+ return true;+ });+ assert.deepEqual(await readFile(join(current, "pi-host.js")), before);+ } finally { await cleanup(); }+ });+}diff --git a/apps/desktop/test/remote-host-ssh-bootstrap.test.mjs b/apps/desktop/test/remote-host-ssh-bootstrap.test.mjsindex 91a0aac00..649866b46 100644--- a/apps/desktop/test/remote-host-ssh-bootstrap.test.mjs+++ b/apps/desktop/test/remote-host-ssh-bootstrap.test.mjs@@ -133,6 +133,7 @@ test("bootstrap probes, installs, forwards, and pairs in order", async () => {user: "deploy",remotePort: 41_234,version: VERSION,+ hostId: "host_x",});// One tunnel: reserved here, bound to the port the host reported remotely.@@ -145,7 +146,7 @@ test("bootstrap probes, installs, forwards, and pairs in order", async () => {// Pairing spends the single-use token over the forwarded URL only.assert.deepEqual(pairings, [- { url: `ws://127.0.0.1:${RESERVED_PORT}/v1/racp/ws`, pairingToken: "ppt1.abc", label: "Prod box" },+ { url: `ws://127.0.0.1:${RESERVED_PORT}/v1/racp/ws`, pairingToken: "ppt1.abc", label: "Prod box", expectedHostId: "host_x" },]);// What travelled over SSH is the script with the pinned digest and URL, not@@ -338,3 +339,11 @@ test("sshMetadataOf refuses direct, missing, and malformed descriptors", () => {);}});++test("SSH identity metadata remains optional for legacy records and rejects malformed enrollment", () => {+ const ssh = { host: "remote.example", remotePort: 1234, version: VERSION };+ const record = (value) => ({ hostKey: "h", metadata: { transport: "ssh", ssh: value } });+ assert.equal(sshMetadataOf(record(ssh)).hostId, undefined);+ assert.equal(sshMetadataOf(record({ ...ssh, hostId: "enrolled" })).hostId, "enrolled");+ for (const hostId of ["", "x\n", 42, "x".repeat(257)]) assert.equal(sshMetadataOf(record({ ...ssh, hostId })), null);+});diff --git a/apps/desktop/test/remote-host-ssh-tunnel.test.mjs b/apps/desktop/test/remote-host-ssh-tunnel.test.mjsindex 1e79f5d45..f2bea5b7a 100644--- a/apps/desktop/test/remote-host-ssh-tunnel.test.mjs+++ b/apps/desktop/test/remote-host-ssh-tunnel.test.mjs@@ -54,9 +54,7 @@ function harness({ ports = [41_001, 41_002, 41_003] } = {}) {exec: async () => {throw new Error("the tunnel never execs");},- execWithInput: async () => {- throw new Error("the tunnel never execs");- },+ execWithInput: async () => ({ code: 0, stderr: "", stdout: `PI_HOST_READY ${JSON.stringify({ hostId: "host-1", host: "127.0.0.1", port: 45678, version: VERSION })}\n` }),async forward(options) {entry.forwards.push(options);if (entry.nextFailure) {@@ -132,7 +130,7 @@ test("open reuses the forward for a host key instead of stacking tunnels", asyncassert.deepEqual(transports[0].forwards[0], {localPort: first.localPort,remoteHost: "127.0.0.1",- remotePort: SSH.remotePort,+ remotePort: 45678,});});@@ -229,6 +227,7 @@ test("close during forward creation disposes the late forward instead of cachingreservePort: async () => 1234,buildTransport: () => ({forward: async () => { started.resolve(); await gate.promise; return forward; },+ execWithInput: async () => ({ code: 0, stdout: `PI_HOST_READY ${JSON.stringify({ hostId: "h", host: "127.0.0.1", port: 1234, version: VERSION })}` }),dispose: () => { disposed++; },}),});@@ -249,6 +248,7 @@ test("a failed open disposes its transport even when forward cleanup rejects", aconst manager = createSshTunnelManager({reservePort: async () => 1234,buildTransport: () => ({+ execWithInput: async () => ({ code: 0, stdout: `PI_HOST_READY ${JSON.stringify({ hostId: "h", host: "127.0.0.1", port: 1234, version: VERSION })}` }),forward: async () => ({ localPort: 1234, close: async () => { closes++; throw closeError; } }),dispose: () => { disposed++; },}),@@ -259,3 +259,52 @@ test("a failed open disposes its transport even when forward cleanup rejects", aassert.equal(closes, 1);assert.equal(disposed, 1, "cleanup failure must not skip disposal of the SSH process");});++test("supervision precedes reservation and cancellation never forwards a late ready", async () => {+ const gate = Promise.withResolvers();+ const started = Promise.withResolvers();+ let reserves = 0;+ let forwards = 0;+ let disposed = 0;+ const manager = createSshTunnelManager({+ reservePort: async () => { reserves++; return 1234; },+ buildTransport: () => ({+ execWithInput: async () => { started.resolve(); return gate.promise; },+ forward: async () => { forwards++; return fakeForward(1234); },+ dispose: () => { disposed++; },+ }),+ });+ const opening = manager.open("k", SSH);+ await started.promise;+ assert.equal(reserves, 0);+ await manager.close("k");+ gate.resolve({ code: 0, stderr: "", stdout: `PI_HOST_READY ${JSON.stringify({ hostId: "host-1", host: "::1", port: 45678, version: VERSION })}` });+ await assert.rejects(opening, { errorCode: "HOST_DISCONNECTED" });+ assert.equal(reserves, 0);+ assert.equal(forwards, 0);+ assert.equal(disposed, 1);+});++test("invalid readiness prevents reservation and forwarding; IPv6 readiness uses bracketed SSH syntax", async () => {+ for (const host of ["0.0.0.0", "::1"]) {+ let reserves = 0;+ const forwarded = [];+ const manager = createSshTunnelManager({+ reservePort: async () => { reserves++; return 1234; },+ buildTransport: () => ({+ execWithInput: async () => ({ code: 0, stdout: `PI_HOST_READY ${JSON.stringify({ hostId: "h", host, port: 45678, version: VERSION })}` }),+ forward: async options => { forwarded.push(options); return fakeForward(1234); },+ dispose: () => {},+ }),+ });+ if (host === "0.0.0.0") {+ await assert.rejects(manager.open("k", SSH), { errorCode: "HOST_BOOTSTRAP_FAILED" });+ assert.equal(reserves, 0);+ assert.deepEqual(forwarded, []);+ } else {+ await manager.open("k", SSH);+ assert.deepEqual(forwarded, [{ localPort: 1234, remoteHost: "[::1]", remotePort: 45678 }]);+ }+ await manager.dispose();+ }+});diff --git a/apps/desktop/test/remote-host-supervisor.test.mjs b/apps/desktop/test/remote-host-supervisor.test.mjsnew file mode 100644index 000000000..bb41fc3fd--- /dev/null+++ b/apps/desktop/test/remote-host-supervisor.test.mjs@@ -0,0 +1,119 @@+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";+import { mkdtemp, mkdir, writeFile, readFile, symlink, rm } from "node:fs/promises";+import { spawn } from "node:child_process";++const here = dirname(fileURLToPath(import.meta.url));+register(pathToFileURL(join(here, "helpers/ts-import-hooks.mjs")));+const { buildRemoteHostSupervisorScript, parseRemoteHostReady, ensureRemoteHostReady } = await import("../electron/main/remote/remote-host-supervisor.ts");+const VERSION = "0.15.1-beta.5";+const ready = { hostId: "durable-host", host: "127.0.0.1", port: 45678, version: VERSION };+const line = value => `PI_HOST_READY ${JSON.stringify(value)}\n`;++test("readiness validates loopback, integral port, identity and version without leaking output", () => {+ assert.deepEqual(parseRemoteHostReady(line(ready), { version: `v${VERSION}`, expectedHostId: ready.hostId }), ready);+ for (const invalid of [{ host: "0.0.0.0" }, { port: 0 }, { port: 65536 }, { port: 1.5 }, { port: "42" }, { hostId: " " }, { version: "" }]) {+ assert.throws(() => parseRemoteHostReady(line({ ...ready, ...invalid }), { version: VERSION }), { errorCode: "HOST_BOOTSTRAP_FAILED" });+ }+ for (const output of ["", "PI_HOST_READY {", line(ready) + line(ready), line(ready) + "PI_HOST_PAIRING_TOKEN secret"]) {+ assert.throws(() => parseRemoteHostReady(output, { version: VERSION }), error => !error.message.includes("secret"));+ }+ assert.throws(() => parseRemoteHostReady(line(ready), { version: "other" }), { errorCode: "HOST_VERSION_MISMATCH", retriable: false });+ assert.throws(() => parseRemoteHostReady(line(ready), { version: VERSION, expectedHostId: "other" }), { errorCode: "HOST_AUTH_FAILED", retriable: false });+ assert.throws(() => buildRemoteHostSupervisorScript(0));+});++test("supervisor uses bounded stdin execution and refuses nonzero status", async () => {+ const transport = { execWithInput: async (command, script, options) => {+ assert.equal(command, "sh -s");+ assert.equal(options.timeoutMs, 165000);+ assert.equal(options.maxOutputBytes, 16384);+ assert.ok(script.includes('9>&-'));+ return { code: 1, stdout: line(ready), stderr: "private diagnostic" };+ } };+ await assert.rejects(ensureRemoteHostReady(transport, { version: VERSION }), { errorCode: "HOST_BOOTSTRAP_FAILED" });+});++async function fixture(t, { legacy = false } = {}) {+ const home = await mkdtemp(join(process.env.PI_SCRATCH_DIR, "supervisor-"));+ const base = join(home, ".pi-desktop/pi-host");+ const work = join(base, ".bootstrap");+ await mkdir(join(base, "current/bin"), { recursive: true });+ await mkdir(work);+ const credentials = join(home, "credentials");+ await writeFile(credentials, "durable-device-token");+ const entry = join(base, "current/pi-host.js");+ await writeFile(entry, `const fs = require('node:fs');+const net = require('node:net');+if (process.argv.slice(2).join(' ') !== '--port 0') process.exit(2);+let inheritedLock = false;+try { inheritedLock = fs.readlinkSync('/proc/self/fd/9').endsWith('/.deploy.lock'); } catch {}+if (inheritedLock) process.exit(3);+const server = net.createServer();+server.listen(0, '127.0.0.1', () => console.log('PI_HOST_READY ' + JSON.stringify({ hostId: 'durable-host', host: '127.0.0.1', port: server.address().port, version: '${VERSION}' })));+`);+ if (!legacy) await symlink(process.execPath, join(base, "current/bin/node"));+ t.after(async () => {+ const pid = Number(await readFile(join(work, "pi-host.pid"), "utf8").catch(() => "0"));+ if (pid > 0 && pid !== 99999999 && pid !== process.pid) { try { process.kill(pid); } catch {} }+ await rm(home, { recursive: true, force: true });+ });+ const run = () => new Promise((resolve, reject) => {+ const child = spawn("sh", ["-s"], { env: { ...process.env, HOME: home } });+ let stdout = "", stderr = "";+ child.stdout.on("data", chunk => { stdout += chunk; });+ child.stderr.on("data", chunk => { stderr += chunk; });+ child.on("error", reject);+ child.on("close", code => resolve({ code, stdout, stderr }));+ child.stdin.end(buildRemoteHostSupervisorScript(5));+ });+ return { home, base, work, credentials, run };+}++test("stopped installed Host starts at a fresh port, then running reuse preserves PID and credentials", async t => {+ const f = await fixture(t);+ await writeFile(join(f.work, "pi-host.pid"), "99999999\n");+ await writeFile(join(f.work, "pi-host.log"), line(ready) + "PI_HOST_PAIRING_TOKEN historic-secret\n");+ const first = await f.run();+ assert.equal(first.code, 0, first.stderr);+ const live = parseRemoteHostReady(first.stdout, { version: VERSION });+ assert.notEqual(live.port, ready.port);+ const pid = await readFile(join(f.work, "pi-host.pid"), "utf8");+ // Simulate a bootstrap log that still contains its original pairing token.+ await writeFile(join(f.work, "pi-host.log"), first.stdout + "PI_HOST_PAIRING_TOKEN historic-secret\n");+ const second = await f.run();+ assert.equal(second.code, 0, second.stderr);+ assert.equal(second.stdout, first.stdout);+ assert.equal(await readFile(join(f.work, "pi-host.pid"), "utf8"), pid);+ assert.equal(await readFile(f.credentials, "utf8"), "durable-device-token");+ assert.ok((await readFile(join(f.work, "pi-host.log"), "utf8")).includes("historic-secret"));+});++test("legacy installed bundle can use system Node without installing", async t => {+ const f = await fixture(t, { legacy: true });+ const result = await f.run();+ assert.equal(result.code, 0, result.stderr);+ parseRemoteHostReady(result.stdout, { version: VERSION });+});++test("unrelated live PID is neither killed nor mistaken for an installed Host", async t => {+ const f = await fixture(t);+ await writeFile(join(f.work, "pi-host.pid"), String(process.pid));+ await writeFile(join(f.work, "pi-host.log"), line(ready));+ const result = await f.run();+ assert.equal(result.code, 1);+ assert.match(result.stderr, /host-pid-mismatch/);+ assert.equal(await readFile(join(f.work, "pi-host.log"), "utf8"), line(ready));+});++test("symlinked stale log is rejected without truncating its target", async t => {+ const f = await fixture(t);+ await symlink(f.credentials, join(f.work, "pi-host.log"));+ const result = await f.run();+ assert.equal(result.code, 1);+ assert.match(result.stderr, /unsafe-state-file/);+ assert.equal(await readFile(f.credentials, "utf8"), "durable-device-token");+});diff --git a/apps/desktop/test/remote-project-dialog-user-path.test.mjs b/apps/desktop/test/remote-project-dialog-user-path.test.mjsindex b42a8be89..969817955 100644--- a/apps/desktop/test/remote-project-dialog-user-path.test.mjs+++ b/apps/desktop/test/remote-project-dialog-user-path.test.mjs@@ -41,7 +41,7 @@ window.piDesktop = { platform: "darwin", channels: IPC, on() { return () => {};case IPC.invoke.remoteHostList: return { hosts: [{ hostKey: "h1", label: "Server 1", connected: true }, { hostKey: "h2", label: "Server 2", connected: true }, { hostKey: "offline", label: "Offline", connected: false }] };case IPC.invoke.remoteHostBrowseProjects:if (input.hostKey === "h1") return new Promise((resolve) => { releaseOldBrowse = () => resolve({ path: "/old", entries: [{ name: "stale", path: "/old/stale" }] }); });- if (input.path === "/missing") throw new Error("Directory not found");+ if (input.path === "/missing") throw Object.assign(new Error("private diagnostic ppt1.secret"), { errorCode: "REMOTE_PATH_NOT_FOUND" });return { path: input.path ?? "/home/user", parent: input.path === "/home/user/app" ? "/home/user" : "/home", entries: input.path === "/home/user/app" ? [] : [{ name: "app", path: "/home/user/app" }] };case IPC.invoke.projectGroupCreateRemote: return new Promise((resolve) => { releaseCreate = () => resolve({ group: { ...group, name: input.name } }); });case IPC.invoke.projectSet: return { workspace: { path: input, name: group.name, remote: group.remote, projectGroup: group } };@@ -75,7 +75,7 @@ window.remoteProjectProbe = async () => {button("Remote").click();await until(() => document.querySelector('select')?.value === "h1", "hosts did not load");check(document.querySelector("#project-create-name").value === "My server app", "remote source lost editable local name");- check(!document.querySelector('option[value="offline"]'), "disconnected host offered");+ check(document.querySelector('option[value="offline"]'), "disconnected paired host not offered");check(document.querySelectorAll('select').length === 1, "host project catalog still required");check(!calls.some((entry) => entry.channel === IPC.invoke.remoteHostProjects), "host project catalog was fetched");check(!calls.some((entry) => entry.channel === IPC.invoke.remoteHostBrowseProjects), "browse loaded inside project form");@@ -86,6 +86,12 @@ window.remoteProjectProbe = async () => {await until(() => !picker(), "Escape did not close picker"); await settle();check(document.querySelector('.project-create-dialog'), "Escape closed parent project dialog");check(document.activeElement === button("Browse folders"), "cancel did not restore browse focus");+ choose(document.querySelector("select"), "offline");+ button("Browse folders").click();+ await until(() => picker()?.querySelector(".remote-project-browser-path")?.textContent === "/home/user", "offline paired host did not browse after restore");+ check(calls.some((entry) => entry.channel === IPC.invoke.remoteHostBrowseProjects && entry.input.hostKey === "offline"), "offline browse did not reach recovery entry");+ button("Cancel", picker()).click();+ await until(() => !picker(), "offline browse cancel failed");choose(document.querySelector("select"), "h2");button("Browse folders").click();await until(() => picker()?.querySelector(".remote-project-browser-path")?.textContent === "/home/user", "new host did not load");@@ -102,7 +108,8 @@ window.remoteProjectProbe = async () => {await until(() => picker()?.querySelector(".remote-project-browser-path")?.textContent === "/home/user", "parent navigation failed");input(picker().querySelector("input"), "/missing");picker().querySelector('form').dispatchEvent(new Event("submit", { bubbles: true, cancelable: true }));- await until(() => picker()?.querySelector('[role="alert"]')?.textContent.includes("Directory not found"), "directory error missing");+ await until(() => picker()?.querySelector('[role="alert"]')?.textContent.includes("remote directory"), "safe directory error missing");+ check(!document.body.textContent.includes("ppt1.secret"), "raw remote diagnostic leaked");check(button("Use this folder", picker()).disabled, "failed directory still selectable");input(picker().querySelector("input"), "/home/user/app");picker().querySelector('form').dispatchEvent(new Event("submit", { bubbles: true, cancelable: true }));diff --git a/apps/desktop/test/remote-workspace-instructions.test.mjs b/apps/desktop/test/remote-workspace-instructions.test.mjsnew file mode 100644index 000000000..d7f9fd7cf--- /dev/null+++ b/apps/desktop/test/remote-workspace-instructions.test.mjs@@ -0,0 +1,41 @@+import assert from "node:assert/strict";+import test from "node:test";+import { mkdtemp, mkdir, rm, writeFile } from "node:fs/promises";+import { register } from "node:module";+import { tmpdir } from "node:os";+import { join } from "node:path";+register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url));+const { loadRemoteWorkspaceInstructions } = await import("../electron/main/remote/remote-workspace-instructions.ts");+const { createWorkspaceFiles } = await import("../../pi-host/src/workspace-files.ts");++test("local Agent configuration loads remote repository instructions after local defaults", async () => {+ const root = await mkdtemp(join(process.env.PI_SCRATCH_DIR ?? tmpdir(), "remote-instructions-"));+ try {+ const path = join(root, "remote-repo");+ await mkdir(path);+ await writeFile(join(root, "AGENTS.md"), "parent must not be loaded");+ await writeFile(join(path, "AGENTS.md"), "remote repository policy");+ const defaults = { entries: [{ source: "~/.pi/agent/AGENTS.md", content: "local user defaults" }] };+ const files = createWorkspaceFiles();+ const requests = [];+ const loaded = await loadRemoteWorkspaceInstructions(async (hostKey, input) => {+ requests.push({ hostKey, input });+ return files.read(input);+ }, { hostKey: "paired", path }, defaults);+ assert.deepEqual(requests, [{ hostKey: "paired", input: { path, operation: "instructions" } }]);+ assert.deepEqual(loaded, { entries: [...defaults.entries, { source: "AGENTS.md", content: "remote repository policy" }] });+ await rm(join(path, "AGENTS.md"));+ assert.deepEqual(await loadRemoteWorkspaceInstructions((_key, input) => files.read(input), { hostKey: "paired", path }, defaults), defaults);+ } finally { await rm(root, { recursive: true, force: true }); }+});++test("offline instruction loading fails without a local fallback", async () => {+ const offline = Object.assign(new Error("Host disconnected"), { errorCode: "HOST_DISCONNECTED" });+ await assert.rejects(loadRemoteWorkspaceInstructions(async () => { throw offline; }, { hostKey: "paired", path: "/repo" }), (error) => error === offline);+});++for (const value of [undefined, { entries: "bad" }, { entries: [{ source: "~/.pi/agent/AGENTS.md", content: "remote home" }] }, { entries: [{ source: "../AGENTS.md", content: "outside" }] }, { entries: [{ source: "AGENTS.md", content: "x".repeat(33_281) }] }, { entries: [{ source: "AGENTS.md", content: 42 }] }]) {+ test("rejects malformed or out-of-scope Host instructions", async () => {+ await assert.rejects(loadRemoteWorkspaceInstructions(async () => value, { hostKey: "paired", path: "/repo" }), { errorCode: "INVALID_ARGUMENT" });+ });+}diff --git a/apps/desktop/test/settings-remote-hosts.test.mjs b/apps/desktop/test/settings-remote-hosts.test.mjsindex 1701bd227..b7d185cd5 100644--- a/apps/desktop/test/settings-remote-hosts.test.mjs+++ b/apps/desktop/test/settings-remote-hosts.test.mjs@@ -69,3 +69,10 @@ test("the remote-hosts destination is marked experimental", () => {assert.doesNotMatch(page, /experimentalGateway/);assert.doesNotMatch(page, /SettingsCard/);});++test("remote host inventory renders non-binary connection states with localized labels", () => {+ assert.match(page, /statusConnecting/);+ assert.match(page, /statusReconnecting/);+ assert.match(page, /statusActionRequired/);+ assert.match(page, /statusOffline/);+});diff --git a/apps/pi-host/README.md b/apps/pi-host/README.mdindex a07e846cb..30b6cf257 100644--- a/apps/pi-host/README.md+++ b/apps/pi-host/README.md@@ -10,8 +10,9 @@ Use a Desktop and Host bundle built from the same candidate.1. Open **Settings → Remote Hosts (Experimental)**. Developer mode is not required.2. Add an SSH host using your existing SSH key/configuration, or password where- supported. Bootstrap downloads the same-version platform bundle and verifies- the published checksum. The server needs Node and outbound release access.+ supported. Remote download is preferred; only a classified download failure+ permits one bounded, locally verified upload. New bundles include Node 22++ and do not require remote Node or outbound release access.3. Return to Chat home and open **Create project**. Choose the connected Host,open the directory-selection dialog, and choose or enter the remote directory.Name the project locally, exactly as for a local project.@@ -28,8 +29,8 @@ configuration, project registration and session creation are not prerequisites.Legacy remote-Agent histories still use their original backend. Trusted-extensionmodel providers remain local; an extension workspace `pi.exec` needs a remoteadapter and currently fails explicitly, while a local model helper can specify-its local cwd. Remote terminal and legacy session features retain their existing-capability boundaries. This is not full R2 acceptance.+its local cwd. There is no interactive terminal UI (ADR 0108); local Agent Bash+commands still run against the remote workspace. This is not full R2 acceptance.**Release prerequisite:** automatic SSH install uses published release assets.Building this branch does not update an existing release. Publish a matching@@ -48,6 +49,7 @@ cargo build -p host-core --lockednode apps/pi-host/scripts/bundle.mjs --host-core "$PWD/target/debug/pi-desktop-host-core" --out "$PWD/apps/pi-host/dist-bundle/candidate"PI_HOST_E2E_BUNDLE="$PWD/apps/pi-host/dist-bundle/candidate" node scripts/e2e-remote-mvp.mjsnode scripts/e2e-remote-mvp-ui.mjs+PI_HOST_CORE_BINARY="$PWD/target/debug/pi-desktop-host-core" node scripts/e2e-local-agent-remote-tools.mjs```Set `--out <directory>` to place the Host bundle elsewhere, and use the actualdiff --git a/apps/pi-host/scripts/bundle.mjs b/apps/pi-host/scripts/bundle.mjsindex 7ae92ef10..2ad9e615e 100644--- a/apps/pi-host/scripts/bundle.mjs+++ b/apps/pi-host/scripts/bundle.mjs@@ -1,16 +1,17 @@#!/usr/bin/env node/**- * Assemble the self-contained `pi-host` bundle for one Linux target:+ * Assemble the self-contained `pi-host` bundle for one native POSIX target:** dist-bundle/pi-host-<version>-<platform>-<arch>/* pi-host.js the CLI, esbuild-bundled with every workspace package* agent-runtime/ the complete sidecar bundle (entry, chunks, manifest)* bin/pi-desktop-host-core the platform host-core binary+ * bin/node, bin/pi-host matching Node runtime and launcher* node_modules/node-pty optional; terminals are disabled without it* package.json { type: module, version }- * install.sh copies the bundle under ~/.pi-desktop/pi-host/<version>+ * install.sh, SHA256SUMS verified content-addressed installation*- * Usage: node scripts/bundle.mjs [--host-core <path>] [--platform linux] [--arch x64|arm64] [--out <dir>]+ * Usage: node scripts/bundle.mjs [--node <path>] [--host-core <path>] [--platform linux|darwin] [--arch x64|arm64] [--out <dir>]*/import { execFileSync } from "node:child_process";import { cpSync, existsSync, mkdirSync, rmSync, writeFileSync, chmodSync } from "node:fs";@@ -19,6 +20,7 @@ import { fileURLToPath } from "node:url";import { createRequire } from "node:module";import { copyAgentRuntimeBundle } from "./runtime-bundle.mjs";import { ensureDarwinSpawnHelperExecutable } from "./spawn-helper-permissions.mjs";+import { writePackageManifest } from "./package-integrity.mjs";const here = dirname(fileURLToPath(import.meta.url));const app = resolve(here, "..");@@ -36,6 +38,18 @@ const hostCore = resolve(String(args["host-core"] ?? join(root, `target/release/const runtimeBundle = join(root, "packages/agent-runtime/dist-bundle");const out = resolve(String(args.out ?? join(app, "dist-bundle", `pi-host-${version}-${platform}-${arch}`)));+// Probe the actual selected executable before removing or writing output. Native+// addons and host-core are built on this runner, so cross-target labels are unsafe.+const nodeRuntime = resolve(String(args.node ?? process.execPath));+const runtime = JSON.parse(execFileSync(nodeRuntime, ["-p", "JSON.stringify({version:process.versions.node,platform:process.platform,arch:process.arch})"], {+ encoding: "utf8", timeout: 10_000, env: { ...process.env, NODE_OPTIONS: "", NODE_PATH: "" },+}));+if (!['linux', 'darwin'].includes(platform) || !['x64', 'arm64'].includes(arch)+ || platform !== process.platform || arch !== process.arch+ || runtime.platform !== platform || runtime.arch !== arch+ || !/^\d+\./.test(runtime.version) || Number(runtime.version.split('.')[0]) < 22) {+ throw new Error(`Node runtime >=22 and native platform/arch must match bundle target ${platform}/${arch}; got ${JSON.stringify(runtime)}`);+}for (const [label, path] of [["host-core binary", hostCore], ["sidecar bundle", join(runtimeBundle, "sidecar.js")]]) {if (!existsSync(path)) {console.error(`${label} missing: ${path}`);@@ -78,19 +92,16 @@ if (ptyPackageDir) {} else {console.warn("node-pty not installed; the bundle ships without terminals");}-writeFileSync(join(out, "package.json"), `${JSON.stringify({ name: "pi-host", version, type: "module", bin: { "pi-host": "./pi-host.js" } }, null, 2)}\n`);-writeFileSync(- join(out, "install.sh"),- `#!/bin/sh-# Install this pi-host bundle under the user's home (D375 bootstrap).+cpSync(nodeRuntime, join(out, "bin/node"));+chmodSync(join(out, "bin/node"), 0o755);+writeFileSync(join(out, "bin/pi-host"), `#!/bin/shset -eu-target="\${PI_HOST_INSTALL_DIR:-$HOME/.pi-desktop/pi-host}/${version}"-mkdir -p "$target"-cp -R "$(dirname "$0")"/. "$target"/-chmod 755 "$target/bin/pi-desktop-host-core${exe}"-ln -sfn "$target" "$(dirname "$target")/current"-echo "PI_HOST_INSTALLED $target"-`,-);+here=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd -P)+exec "$here/node" "$here/../pi-host.js" "$@"+`);+chmodSync(join(out, "bin/pi-host"), 0o755);+writeFileSync(join(out, "package.json"), `${JSON.stringify({ name: "pi-host", version, type: "module", bin: { "pi-host": "./bin/pi-host" } }, null, 2)}\n`);+cpSync(join(here, "install.sh"), join(out, "install.sh"));chmodSync(join(out, "install.sh"), 0o755);+writePackageManifest(out);console.log(`bundled ${out}`);diff --git a/apps/pi-host/scripts/install.sh b/apps/pi-host/scripts/install.shnew file mode 100644index 000000000..29b27f671--- /dev/null+++ b/apps/pi-host/scripts/install.sh@@ -0,0 +1,79 @@+#!/bin/sh+# The release archive checksum authenticates this installer and SHA256SUMS.+# File checksums protect the staged bytes; no system Node or service is needed.+set -eu+umask 077+source_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd -P)+if command -v sha256sum >/dev/null 2>&1; then+ hash() { sha256sum "$1"; }+ check() { sha256sum -c SHA256SUMS; }+elif command -v shasum >/dev/null 2>&1; then+ hash() { shasum -a 256 "$1"; }+ check() { shasum -a 256 -c SHA256SUMS; }+else+ echo 'SHA256 verifier missing (sha256sum or shasum required)' >&2+ exit 1+fi+verify() (+ cd "$1"+ [ -f SHA256SUMS ] && [ ! -L SHA256SUMS ]+ # No absolute/traversal/escaped names, duplicate records, or special files.+ awk '+ length($1) != 64 || $1 ~ /[^0-9a-f]/ { exit 1 }+ NF != 2 || $2 !~ /^[A-Za-z0-9_.\/@+-]+$/ { exit 1 }+ $2 ~ /^\// || $2 ~ /(^|\/)\.\.?($|\/)/ || $2 ~ /\/\// { exit 1 }+ $2 == "SHA256SUMS" || seen[$2]++ { exit 1 }+ END { if (NR == 0) exit 1 }+ ' SHA256SUMS+ [ -z "$(find . ! -type f ! -type d -print)" ]+ [ "$(find . -type f | wc -l | tr -d ' ')" = "$(($(wc -l < SHA256SUMS) + 1))" ]+ check+ for executable in bin/node bin/pi-host bin/pi-desktop-host-core install.sh; do+ [ -x "$executable" ]+ done+ [ -f pi-host.js ]+)+if [ "${1:-}" = "--verify" ]; then+ verify "$source_dir"+ exit 0+fi+root=${PI_HOST_INSTALL_DIR:-$HOME/.pi-desktop/pi-host}+mkdir -p "$root"+root=$(CDPATH= cd -- "$root" && pwd -P)+# Linux locks are kernel-owned and release on crashes; no stale PID takeover.+if [ "$(uname -s)" = "Linux" ]; then+ command -v flock >/dev/null 2>&1 || { echo 'flock is required on Linux' >&2; exit 1; }+ exec 8>"$root/.install.lock"+ flock -w 120 8 || { echo 'Another install is active' >&2; exit 1; }+ lock=$(mktemp -d "$root/.install.XXXXXXXX")+else+ lock="$root/.install-lock"+ mkdir "$lock" || { echo 'Another install is active' >&2; exit 1; }+fi+stage=+cleanup() {+ [ -z "$stage" ] || rm -rf "$stage"+ rm -rf "$lock"+}+trap cleanup EXIT+trap 'exit 1' HUP INT TERM+stage=$(mktemp -d "$root/.stage.XXXXXXXX")+cp -R "$source_dir"/. "$stage"/+verify "$stage"+digest=$(hash "$stage/SHA256SUMS")+digest=${digest%% *}+version="$root/sha256-$digest"+if [ -e "$version" ] || [ -L "$version" ]; then+ [ -d "$version" ] && [ ! -L "$version" ]+ verify "$version"+ cmp "$stage/SHA256SUMS" "$version/SHA256SUMS"+else+ mv "$stage" "$version"+ stage=+fi+# Refuse a legacy real directory, then rename a new symlink atomically. Unlike+# ln -sfn or portable mv, rename never follows an existing directory symlink.+[ ! -e "$root/current" ] || [ -L "$root/current" ]+ln -s "$version" "$lock/current"+NODE_OPTIONS= NODE_PATH= "$version/bin/node" --input-type=module -e 'import { renameSync } from "node:fs"; renameSync(process.argv[1], process.argv[2]);' "$lock/current" "$root/current"+echo "PI_HOST_INSTALLED $version"diff --git a/apps/pi-host/scripts/package-integrity.mjs b/apps/pi-host/scripts/package-integrity.mjsnew file mode 100644index 000000000..d4815fc55--- /dev/null+++ b/apps/pi-host/scripts/package-integrity.mjs@@ -0,0 +1,24 @@+import { createHash } from "node:crypto";+import { lstatSync, readFileSync, readdirSync, writeFileSync } from "node:fs";+import { join } from "node:path";++/** Standard sha256sum records, restricted to unambiguous relative file names. */+export function writePackageManifest(root) {+ const records = [];+ function visit(directory, prefix = "") {+ for (const name of readdirSync(directory).sort()) {+ const relative = prefix + name;+ if (!/^[A-Za-z0-9_./@+-]+$/.test(relative) || relative.split("/").some((part) => part === "." || part === "..")) {+ throw new Error(`Unsafe package path: ${relative}`);+ }+ const path = join(directory, name);+ const stat = lstatSync(path);+ if (stat.isDirectory()) visit(path, `${relative}/`);+ else if (stat.isFile()) {+ if (relative !== "SHA256SUMS") records.push(`${createHash("sha256").update(readFileSync(path)).digest("hex")} ${relative}\n`);+ } else throw new Error(`Non-regular package file: ${relative}`);+ }+ }+ visit(root);+ writeFileSync(join(root, "SHA256SUMS"), records.join(""));+}diff --git a/apps/pi-host/src/packaging.test.ts b/apps/pi-host/src/packaging.test.tsindex a0f727fac..eb0d66b3f 100644--- a/apps/pi-host/src/packaging.test.ts+++ b/apps/pi-host/src/packaging.test.ts@@ -1,5 +1,5 @@import { spawnSync } from "node:child_process";-import { cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, symlinkSync, writeFileSync } from "node:fs";+import { chmodSync, cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readlinkSync, readdirSync, rmSync, statSync, symlinkSync, writeFileSync } from "node:fs";import { createRequire } from "node:module";import { tmpdir } from "node:os";import { dirname, join } from "node:path";@@ -7,6 +7,7 @@ import { fileURLToPath, pathToFileURL } from "node:url";import { afterEach, describe, expect, it } from "vitest";import { copyAgentRuntimeBundle } from "../scripts/runtime-bundle.mjs";import { ensureDarwinSpawnHelperExecutable } from "../scripts/spawn-helper-permissions.mjs";+import { writePackageManifest } from "../scripts/package-integrity.mjs";const scripts = fileURLToPath(new URL("../scripts/", import.meta.url));const require = createRequire(import.meta.url);@@ -43,6 +44,7 @@ export async function probe() {write(join(runtime, "chunks/nested/suffix.js"), 'export const suffix = "-runtime";\n');write(join(runtime, "assets/fixture.txt"), "runtime asset\n");write(join(pty, "package.json"), JSON.stringify({ name: "node-pty", version: "1.1.0" }));+ if (process.platform === "darwin") write(join(pty, `prebuilds/darwin-${process.arch}/spawn-helper`), "#!/bin/sh\nexit 0\n");symlinkSync(dirname(require.resolve("esbuild/package.json")), join(app, "node_modules/esbuild"), "junction");return { root, app, runtime, out, pty };}@@ -58,7 +60,7 @@ function node(root: string, args: string[]) {});}-function bundle(f: Fixture, platform = "linux") {+function bundle(f: Fixture, platform: string = process.platform) {return node(f.root, [join(f.app, "scripts/bundle.mjs"), "--platform", platform, "--arch", process.arch, "--out", f.out]);}@@ -99,7 +101,7 @@ describe("pi-host packaging", () => {expect(result.stderr).toMatch(/agent-runtime.*package\.json/s);});- it("packages Linux PTYs without a macOS spawn-helper", () => {+ it.skipIf(process.platform !== "linux")("packages Linux PTYs without a macOS spawn-helper", () => {const f = fixture();write(join(f.pty, "build/Release/pty.node"), "fixture Linux native addon");const result = bundle(f, "linux");@@ -108,7 +110,7 @@ describe("pi-host packaging", () => {expect(existsSync(join(f.out, "node_modules/node-pty/build/Release/spawn-helper"))).toBe(false);});- it.skipIf(process.platform === "win32").each([`prebuilds/darwin-${process.arch}`, "build/Release", "build/Debug"])("makes the Darwin spawn-helper executable in %s without changing the source", (nativeDir) => {+ it.skipIf(process.platform !== "darwin").each([`prebuilds/darwin-${process.arch}`, "build/Release", "build/Debug"])("makes the Darwin spawn-helper executable in %s without changing the source", (nativeDir) => {const f = fixture();write(join(f.pty, nativeDir, "pty.node"), "fixture Darwin native addon");const sourceHelper = join(f.pty, nativeDir, "spawn-helper");@@ -123,7 +125,7 @@ describe("pi-host packaging", () => {expect(executed.stdout).toBe("helper-ok");});- it("does not swallow a missing Darwin helper as an optional node-pty install", () => {+ it.skipIf(process.platform !== "darwin")("does not swallow a missing Darwin helper as an optional node-pty install", () => {const f = fixture();write(join(f.pty, "build/Release/pty.node"), "fixture Darwin native addon");const result = bundle(f, "darwin");@@ -140,6 +142,145 @@ describe("pi-host packaging", () => {expect(result.stderr).toContain("node-pty not installed");expect(existsSync(join(f.out, "node_modules/node-pty"))).toBe(false);});++ it("ships the selected Node and launcher, not a system Node", () => {+ const f = fixture();+ const selected = join(f.root, "selected-node");+ cpSync(process.execPath, selected);+ chmodSync(selected, 0o755);+ write(join(f.app, "src/cli.ts"), 'console.log(JSON.stringify({exec:process.execPath,args:process.argv.slice(2)}));');+ const result = node(f.root, [join(f.app, "scripts/bundle.mjs"), "--node", selected, "--out", f.out]);+ expect(result.status, result.stderr).toBe(0);+ expect(readFileSync(join(f.out, "bin/node")).equals(readFileSync(selected))).toBe(true);+ const launched = spawnSync(join(f.out, "bin/pi-host"), ["hello world"], { env: { ...process.env, PATH: "/usr/bin:/bin", NODE_OPTIONS: "" }, encoding: "utf8" });+ expect(launched.status, launched.stderr).toBe(0);+ expect(JSON.parse(launched.stdout)).toEqual({ exec: join(f.out, "bin/node"), args: ["hello world"] });+ });++ it.each(["old", "wrong-platform", "wrong-arch", "missing"])("rejects %s Node before destroying existing output", (kind) => {+ const f = fixture();+ write(join(f.out, "keep"), "old output");+ const selected = join(f.root, "bad-node");+ const metadata = { version: kind === "old" ? "20.0.0" : "24.0.0", platform: kind === "wrong-platform" ? "other" : process.platform, arch: kind === "wrong-arch" ? "other" : process.arch };+ if (kind !== "missing") {+ write(selected, `#!/bin/sh\nprintf '%s\\n' '${JSON.stringify(metadata)}'\n`);+ chmodSync(selected, 0o755);+ }+ const result = node(f.root, [join(f.app, "scripts/bundle.mjs"), "--node", selected, "--out", f.out]);+ expect(result.status).not.toBe(0);+ expect(readFileSync(join(f.out, "keep"), "utf8")).toBe("old output");+ });++ it("refuses fake cross-target labels before output writes", () => {+ const f = fixture();+ write(join(f.out, "keep"), "old output");+ const result = bundle(f, process.platform === "linux" ? "darwin" : "linux");+ expect(result.status).not.toBe(0);+ expect(readFileSync(join(f.out, "keep"), "utf8")).toBe("old output");+ });++ it("installs verified contents, atomically switches current, and reuses immutable versions", () => {+ const f = fixture();+ expect(bundle(f).status).toBe(0);+ const root = join(f.root, "installed with spaces");+ const install = () => spawnSync("/bin/sh", [join(f.out, "install.sh")], { env: { ...process.env, PI_HOST_INSTALL_DIR: root }, encoding: "utf8" });+ const first = install();+ expect(first.status, first.stderr).toBe(0);+ const original = readlinkSync(join(root, "current"));+ expect(original).toMatch(/sha256-[a-f0-9]{64}$/);+ expect(statSync(original).mode & 0o777).toBe(0o700);+ for (const file of ["bin/node", "bin/pi-host", "bin/pi-desktop-host-core", "pi-host.js", "agent-runtime/assets/fixture.txt", "SHA256SUMS"]) {+ expect(readFileSync(join(original, file)).equals(readFileSync(join(f.out, file)))).toBe(true);+ }+ const before = statSync(join(original, "bin/node"));+ expect(install().status).toBe(0);+ expect(readlinkSync(join(root, "current"))).toBe(original);+ expect(statSync(join(original, "bin/node")).ino).toBe(before.ino);+ write(join(f.out, "pi-host.js"), 'console.log("updated CLI");');+ const failed = install();+ expect(failed.status).not.toBe(0);+ expect(readlinkSync(join(root, "current"))).toBe(original);+ expect(readFileSync(join(original, "pi-host.js"), "utf8")).toContain("fixture CLI");+ writePackageManifest(f.out);+ expect(install().status).toBe(0);+ const updated = readlinkSync(join(root, "current"));+ expect(updated).not.toBe(original);+ expect(readFileSync(join(original, "pi-host.js"), "utf8")).toContain("fixture CLI");+ const launched = spawnSync(join(root, "current/bin/node"), [join(root, "current/pi-host.js")], { encoding: "utf8" });+ expect(launched.status, launched.stderr).toBe(0);+ expect(launched.stdout.trim()).toBe("updated CLI");+ expect(readdirSync(root).filter((name) => name.startsWith(".stage") || name === ".install-lock")).toEqual([]);+ });+++ it("verifies in place without creating installation state and rejects altered files", () => {+ const f = fixture();+ expect(bundle(f).status).toBe(0);+ const root = join(f.root, "must-not-exist");+ const verify = () => spawnSync("/bin/sh", [join(f.out, "install.sh"), "--verify"], { env: { ...process.env, PI_HOST_INSTALL_DIR: root }, encoding: "utf8" });+ const before = statSync(join(f.out, "bin/node"));+ const result = verify();+ expect(result.status, result.stderr).toBe(0);+ expect(existsSync(root)).toBe(false);+ expect(statSync(join(f.out, "bin/node")).ino).toBe(before.ino);+ write(join(f.out, "pi-host.js"), "tampered");+ expect(verify().status).not.toBe(0);+ expect(existsSync(root)).toBe(false);+ });++ it("uses real shasum when sha256sum and system Node are unavailable", () => {+ const f = fixture();+ expect(bundle(f).status).toBe(0);+ const path = join(f.root, "shell-tools");+ mkdirSync(path);+ for (const tool of ["shasum", "uname", ...(process.platform === "linux" ? ["flock"] : []), "dirname", "mkdir", "mktemp", "cp", "awk", "find", "wc", "tr", "mv", "ln", "rm", "cmp"]) {+ const found = spawnSync("/bin/sh", ["-c", `command -v ${tool}`], { encoding: "utf8" });+ expect(found.status, tool).toBe(0);+ symlinkSync(found.stdout.trim(), join(path, tool));+ }+ const root = join(f.root, "installed");+ const install = () => spawnSync("/bin/sh", [join(f.out, "install.sh")], { env: { ...process.env, PATH: path, PI_HOST_INSTALL_DIR: root }, encoding: "utf8" });+ const result = install();+ expect(result.status, result.stderr).toBe(0);+ const original = readlinkSync(join(root, "current"));+ // An already published damaged version must never be silently repaired in place.+ write(join(original, "pi-host.js"), "damaged installed file");+ expect(install().status).not.toBe(0);+ expect(readlinkSync(join(root, "current"))).toBe(original);+ expect(readFileSync(join(original, "pi-host.js"), "utf8")).toBe("damaged installed file");+ });++ it("preserves a non-symlink current directory on publication failure", () => {+ const f = fixture();+ expect(bundle(f).status).toBe(0);+ const root = join(f.root, "installed");+ write(join(root, "current/keep"), "old current");+ const result = spawnSync("/bin/sh", [join(f.out, "install.sh")], { env: { ...process.env, PI_HOST_INSTALL_DIR: root }, encoding: "utf8" });+ expect(result.status).not.toBe(0);+ expect(statSync(join(root, "current")).isDirectory()).toBe(true);+ expect(readFileSync(join(root, "current/keep"), "utf8")).toBe("old current");+ expect(readdirSync(root).filter((name) => name.startsWith(".stage") || name === ".install-lock")).toEqual([]);+ });+ it.each(["traversal", "duplicate", "extra", "symlink", "missing", "corrupt-node"])("refuses %s package and preserves old current", (kind) => {+ const f = fixture();+ expect(bundle(f).status).toBe(0);+ const root = join(f.root, "installed");+ const old = join(root, "old-version");+ write(join(old, "keep"), "unchanged");+ symlinkSync(old, join(root, "current"));+ const manifest = join(f.out, "SHA256SUMS");+ if (kind === "traversal") write(manifest, `${"0".repeat(64)} ../outside\n`);+ if (kind === "duplicate") write(manifest, readFileSync(manifest, "utf8") + readFileSync(manifest, "utf8").split("\n")[0] + "\n");+ if (kind === "extra") write(join(f.out, "extra"), "unexpected");+ if (kind === "missing") rmSync(join(f.out, "pi-host.js"));+ if (kind === "corrupt-node") write(join(f.out, "bin/node"), "corrupt runtime");+ if (kind === "symlink") { rmSync(join(f.out, "pi-host.js")); symlinkSync(join(old, "keep"), join(f.out, "pi-host.js")); }+ const result = spawnSync("/bin/sh", [join(f.out, "install.sh")], { env: { ...process.env, PI_HOST_INSTALL_DIR: root }, encoding: "utf8" });+ expect(result.status).not.toBe(0);+ expect(readlinkSync(join(root, "current"))).toBe(old);+ expect(readFileSync(join(old, "keep"), "utf8")).toBe("unchanged");+ expect(readdirSync(root).filter((name) => name !== ".install.lock").sort()).toEqual(["current", "old-version"]);+ });});describe("packaging helpers", () => {diff --git a/apps/pi-host/src/workspace-files.test.ts b/apps/pi-host/src/workspace-files.test.tsindex 081ffb82c..9f54da980 100644--- a/apps/pi-host/src/workspace-files.test.ts+++ b/apps/pi-host/src/workspace-files.test.ts@@ -34,4 +34,25 @@ describe("sessionless SSH file views", () => {await expect(files.read({ path: "relative", operation: "list" })).rejects.toMatchObject({ code: "INVALID_ARGUMENT" });await expect(files.read({ path: join(path, "missing"), operation: "list" })).rejects.toMatchObject({ code: "REMOTE_PATH_NOT_FOUND" });});+ it("loads repository instructions with precedence, no parent/global file, and bounded UTF-8 content", async () => {+ const path = await fixture(); const files = createWorkspaceFiles();+ expect(await files.read({ path, operation: "instructions" })).toEqual({ entries: [] });+ await writeFile(join(path, "CLAUDE.md"), "fallback");+ await writeFile(join(path, "AGENTS.md"), "repository");+ await writeFile(join(path, "AGENTS.override.md"), "override");+ expect(await files.read({ path, operation: "instructions" })).toEqual({ entries: [{ source: "AGENTS.override.md", content: "override" }] });+ await writeFile(join(path, "AGENTS.override.md"), "界".repeat(20_000));+ const loaded = await files.read({ path, operation: "instructions" }) as { entries: Array<{ source: string; content: string }> };+ expect(loaded.entries).toHaveLength(1);+ expect(loaded.entries[0]?.content).toContain("PI-Desktop truncated AGENTS.override.md");+ expect(Buffer.byteLength(loaded.entries[0]?.content ?? "")).toBeLessThan(33_000);+ expect(loaded.entries[0]?.content).not.toContain("�");+ });+ it("ignores repository instruction links escaping the explicit root", async () => {+ const path = await fixture(); const outside = await fixture();+ await writeFile(join(outside, "AGENTS.md"), "outside private instructions");+ await symlink(join(outside, "AGENTS.md"), join(path, "AGENTS.override.md"));+ await writeFile(join(path, "AGENTS.md"), "contained");+ expect(await createWorkspaceFiles().read({ path, operation: "instructions" })).toEqual({ entries: [{ source: "AGENTS.md", content: "contained" }] });+ });});diff --git a/apps/pi-host/src/workspace-files.ts b/apps/pi-host/src/workspace-files.tsindex 50ea84a30..045afd012 100644--- a/apps/pi-host/src/workspace-files.ts+++ b/apps/pi-host/src/workspace-files.ts@@ -1,6 +1,7 @@import { realpath, stat } from "node:fs/promises";import { basename, isAbsolute } from "node:path";import { RacpError } from "@pi-desktop/agent-host";+import { loadProjectInstructions } from "@pi-desktop/agent-runtime";import { collectWorkspaceDiff, getWorkspaceFileIndex, isChatRefOutsideRoots, listDir, readOpenableFile, readOpenableImage, resolveChatFileRef } from "@pi-desktop/host-runtime";import type { RacpHostOperations } from "@pi-desktop/racp";@@ -18,6 +19,7 @@ export function createWorkspaceFiles(): NonNullable<RacpHostOperations["workspaccase "image": return await readOpenableImage(ref, root, [], input.mimeType);case "index": return await getWorkspaceFileIndex(root);case "diff": return await collectWorkspaceDiff(root);+ case "instructions": return (await loadProjectInstructions(root)) ?? { entries: [] };case "resolve": {const roots = { project: [{ path: root, name: basename(root), primary: true }] };if (await isChatRefOutsideRoots(ref, roots)) return { match: null, reason: "outside-allowed-roots" };diff --git a/docs/adr/0292-ssh-remote-host-bootstrap.md b/docs/adr/0292-ssh-remote-host-bootstrap.mdindex e5ac728e6..745c51798 100644--- a/docs/adr/0292-ssh-remote-host-bootstrap.md+++ b/docs/adr/0292-ssh-remote-host-bootstrap.md@@ -7,6 +7,12 @@`02-architecture/05-remote-agent-control.md` §5.2,`05-security/02-remote-control-security.md` §3.4,`06-delivery/07-remote-control-rollout.md` §2 R2b+- Amendments: [ADR 0293](0293-ssh-password-authentication.md) permits secure SSH password handling; [ADR 0326](0326-verified-ssh-host-installation.md) supersedes the executable-upload prohibition, remote-only download prerequisite and daily bootstrap lifecycle below.++This record describes the original bootstrap decision, not the current candidate+installation contract. ADR 0326 permits a verified release upload only after+`download-failed`, bundles matching Node, and separates daily startup from pairing.+The historical constraints and alternatives below remain context for that amendment.## Contextdiff --git a/docs/adr/0326-verified-ssh-host-installation.md b/docs/adr/0326-verified-ssh-host-installation.mdnew file mode 100644index 000000000..a0b58663e--- /dev/null+++ b/docs/adr/0326-verified-ssh-host-installation.md@@ -0,0 +1,98 @@+# ADR 0326: Verified SSH Host installation and daily startup++- Status: Accepted for experimental implementation; Linux SSH qualification and release publication pending+- Date: 2026-10-11+- Deciders: PI-Desktop maintainers (user-authorized Remote SSH optimization plan)+- Amends: [ADR 0292](0292-ssh-remote-host-bootstrap.md), specifically the executable-upload prohibition and remote GitHub-access prerequisite; the corresponding D375 deployment choice+- Related: [ADR 0293](0293-ssh-password-authentication.md), [Local Agent remote workspace tools](local-agent-remote-workspace-tools.md), [architecture §5.2](../spec/02-architecture/05-remote-agent-control.md#52-remote-host-over-an-ssh-tunnel-first-remote-topology), [security §3.4](../spec/05-security/02-remote-control-security.md#34-ssh-bootstrap-pairing-first-remote-topology)++## Context++The original bootstrap required system Node 22+ and outbound GitHub access on+the remote machine. Reusing installation/pairing for daily connection also risks+unnecessary downloads, process restarts and credential churn. Users already have+SSH shell authority; a blanket prohibition on executable upload prevents a useful+fallback without protecting against a compromised release source.++## Decision++1. Keep system OpenSSH, its host-key checks, configured identities/agent/jump+ hosts, and RACP-WS over loopback forwarding. Do not introduce SSH stdio RPC,+ a public listener, elevated privileges or a mandatory systemd service.+2. Resolve the matching Desktop version and published Linux x64/arm64 target.+ Obtain the named archive SHA-256 from the trusted GitHub Release over HTTPS.+ Prefer a remote download. Only an explicit `download-failed` permits one+ bounded Desktop download and SSH stdin upload of the same archive. Integrity,+ authentication and version failures never authorize a transfer fallback.+3. Verify the archive before extraction/install on the remote machine. The+ fallback additionally verifies it locally before uploading; its download is+ limited to 512 MiB and ten minutes. Use private temporary directories and+ bounded SSH transfer/output, with cleanup on completion and failure.+4. Bundle native-target Node >=22, the complete Agent runtime and host-core,+ launcher, installer and `SHA256SUMS`. Verify staged files, reject unsafe+ manifest paths/special files, install content-addressed version directories,+ then atomically replace the `current` symlink. Linux kernel-owned locks+ serialize deployment and installation. A failed stage does not overwrite the+ previous installed contents. A legacy real `current` directory is refused,+ not silently deleted or converted.+5. Bootstrap reuse requires an external `.release.sha256` receipt matching the+ version, trusted archive digest and installed manifest digest, plus successful+ read-only `install.sh --verify`. The receipt is outside immutable version+ contents. Legacy bundles without a manifest do not qualify for verified reuse.+6. Separate install/pair from daily readiness. The supervisor starts only the+ installed Host when necessary, prefers bundled Node, uses `--port 0` without+ `--pair`, and preserves Host identity/device credentials. Validate fresh+ loopback readiness, version and saved Host ID before forwarding; validate+ RACP Host identity again at initialization/reconnect. Older descriptors without+ an optional Host ID remain readable. Ordinary disconnect does not kill a Host+ that another client may use.+7. New remote workspace projects keep Agent execution, models, API credentials,+ permissions and sessions on Desktop. Remote tools/files and root repository+ instructions use owner-only workspace services. Local global instruction+ defaults precede remote root instructions; remote HOME and nested instruction+ traversal are not part of this operation. Legacy remote-Agent mode remains.+8. Recovery never replays Write/Edit/Bash. A lost transport reply produces+ `REMOTE_MUTATION_OUTCOME_UNKNOWN`, non-retriable, requiring inspection before+ an explicit user retry. Offline Host selection may request readiness but must+ not turn tool execution into an automatic reconnect/replay path. UI errors+ use approved localized categories, never raw SSH stderr or credentials.++## Trust and compatibility++SHA-256 authenticates bytes relative to the trusted release descriptor; it is+not an independent cryptographic signature. The candidate does not add signed+manifest verification or protect against compromise of the release publisher,+the SSH account, or its installed files/receipt. SSH host authentication, private+credentials and canonical workspace containment remain mandatory.++No database migration or model-key synchronization is introduced. Existing direct+connections, SSH authentication modes and legacy remote-Agent sessions retain+ownership. Legacy Host installations may need explicit reinstall/upgrade to gain+the bundled runtime and workspace capabilities; daily startup is not an updater.++## Alternatives++- Remote-only download: retains the original offline-network failure.+- Always upload: adds unnecessary local transfer and discards the working remote+ path. The narrowly classified fallback is sufficient.+- Trust version alone or a self-modifiable manifest: accepts damaged/different+ bytes; verified reuse needs the release-bound external receipt and file checks.+- Reinstall/re-pair on reconnect: changes credentials and process lifecycle for+ an ordinary connection failure. Separate readiness preserves ownership.++## Consequences and qualification++Desktop may now send verified release executable bytes through the user's SSH+session. This is an explicit, limited amendment to ADR 0292/security §3.4, not+permission to upload arbitrary model-generated executables or bypass checks.+New bundles remove the system-Node prerequisite, not the supported Linux ABI or+basic POSIX/SSH/hash/archive/flock requirements.++This remains Experimental. Shell, packaging, protocol and isolated local-model+fixtures are not real Linux SSH release acceptance. A macOS development host+without a Linux target cannot qualify Linux kernel-lock crash recovery, fresh+x64/arm64 SSH installation, blocked remote GitHub, reboot/process recovery or+password-only login. Those gates are documented in E2E-REMOTE-SSH-OPTIMIZATION.+Published `v0.18.0-beta.6` assets are immutable: publish a new matching Desktop+and Host release rather than replacing that tag's bundles. Full R2 terminal and+reverse-relay acceptance is not implied by this decision.diff --git a/docs/adr/README.md b/docs/adr/README.mdindex fc5ae01c5..ec7cd19b6 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -371,6 +371,7 @@ Each ADR includes:| 0323 | [Make Session Title Generation a Standalone Plugin](0323-plugin-owned-session-titles.md) | Accepted (D652, amended by D654; supersedes ADR 0186) || 0324 | [Make Composer Prompt Enhancement an Optional Plugin](0324-plugin-owned-composer-prompt-enhancement.md) | Accepted (D653; supersedes ADR 0121) || 0325 | [Smooth Windows main-window corner compositing](0325-windows-window-corner-compositing.md) | Proposed (implementation candidate; Windows E2E pending) |+| 0326 | [Verified SSH Host installation and daily startup](0326-verified-ssh-host-installation.md) | Accepted for experimental implementation (amends ADR 0292; Linux SSH qualification and publication pending) || plugin-fetch-redirect-policy | [Host-enforced plugin fetch redirect policy](plugin-fetch-redirect-policy.md) | Accepted (implementation candidate for #1475) || local-agent-remote-workspace-tools | [Local Agent and model requests for remote workspaces](local-agent-remote-workspace-tools.md) | Accepted for implementation |diff --git a/docs/adr/local-agent-remote-workspace-tools.md b/docs/adr/local-agent-remote-workspace-tools.mdindex 018bfad02..784df03c6 100644--- a/docs/adr/local-agent-remote-workspace-tools.md+++ b/docs/adr/local-agent-remote-workspace-tools.md@@ -15,10 +15,12 @@ on Desktop, with the remote machine executing tools only.## DecisionKeep the Agent runtime, provider resolution, credentials, model requests,-transcripts, project names, project instructions, project memory and sessions-on Desktop. Extend the existing Rust-owned logical project-group KV boundary-with a remote workspace binding. An opaque project identity selects the group;-the actual remote path is never interpreted as a local filesystem path.+transcripts, project names, project-group instructions, project memory and+sessions on Desktop. Root repository instructions are read from the remote+workspace and merged after local global defaults, without remote HOME defaults+or nested traversal. Extend the existing Rust-owned logical project-group KV+boundary with a remote workspace binding. An opaque project identity selects+the group; the actual remote path is never interpreted as a local filesystem path.After the normal local permission and execution-admission gates, host-corerelays supported workspace tools through Electron Main to the paired Host.@@ -70,3 +72,10 @@ from a local directory before filesystem access. Execution has cancellation andcleanup owners on both sides, and permission approval stays on Desktop.Validation must include a local model fixture and a real remote tool boundary,plus project rename/restart isolation and cancelled/disconnected calls.++[ADR 0326](0326-verified-ssh-host-installation.md) defines verified install and+separate daily startup. The additive `workspace/files` instructions operation+returns root repository entries only. A lost mutation reply is explicitly+`REMOTE_MUTATION_OUTCOME_UNKNOWN`, non-retriable; it requires inspection, not+automatic re-execution. Real Linux SSH and matching new release publication+remain independent qualification gates.diff --git a/docs/spec/02-architecture/05-remote-agent-control.md b/docs/spec/02-architecture/05-remote-agent-control.mdindex 2f2d37085..71dc21a82 100644--- a/docs/spec/02-architecture/05-remote-agent-control.md+++ b/docs/spec/02-architecture/05-remote-agent-control.md@@ -159,11 +159,18 @@ Bootstrap runs over the user's own SSH session, never over RACP:the `ssh` client through an askpass helper, never as an argument, and isstored encrypted in the desktop's secure storage so the host can reconnectafter a restart.-2. It uploads a small bootstrap script that downloads the `pi-host` bundle- for the remote platform at the desktop's version from GitHub Releases,- verifies the published SHA-256, and installs it under the user's home. A- machine without outbound access to GitHub cannot be bootstrapped in the- first version.+2. It resolves the matching Desktop version and published Linux target, fetches+ the named release SHA-256 over HTTPS, and uploads a small bootstrap script.+ Remote download is preferred. Only `download-failed` permits one bounded,+ locally verified download and SSH upload of that same artifact; integrity or+ SSH authentication failure does not. The remote side verifies the archive+ before installing. Bundles include native Node >=22 and a file manifest, so+ system Node and remote GitHub access are not prerequisites for new bundles.+ Verified content-addressed installs switch `current` atomically under locks.+ Reuse checks the external release/manifest receipt and every installed file.+ [ADR 0326](../../adr/0326-verified-ssh-host-installation.md) explicitly amends+ the original no-executable-upload and remote-only-download restrictions.+ Trust is release SHA-256 over HTTPS, not independent signature verification.3. It starts `pi-host` bound to loopback and receives a single-use pairingtoken over the SSH channel.4. It forwards a local port to the Host's loopback port and connects@@ -171,6 +178,14 @@ Bootstrap runs over the user's own SSH session, never over RACP:device token that the desktop stores in its secure storage.5. The Host records the desktop device as `owner` of that Host.+Daily reconnect is not bootstrap: SSH readiness starts/reuses the installed Host+without reinstalling, `--pair`, or resetting device credentials. It discovers+the current loopback port, checks version and saved Host ID, then rebuilds the+forward; RACP initialization/reconnect also checks Host identity. Older SSH+descriptors without a Host ID remain readable. Disconnect does not kill a Host+that other clients may use. Readiness is used for offline browse/files/shell+discovery; tool execution itself never reconnects and replays a failed call.+Provider configuration is copied only after explicit selection and consent inSettings. Electron Main reads the selected eligible secrets and sends a boundedversioned payload over SSH stdin to `pi-host provider-import`. That CLI forwards@@ -197,6 +212,23 @@ is independently enforced. No failed remote call falls back to the local runner,and no mutation is automatically retried. The opaque local project identity isnever resolved as a directory on either machine.+`workspace/files` with `operation: "instructions"` loads only recognized root+repository instructions, contained by the remote canonical root. Desktop merges+them after its own local global defaults before launching the local Agent. It+does not load remote HOME defaults, local same-named directories, or recursively+traverse nested instructions. Offline paired Hosts remain selectable in the+directory picker and can request readiness. Approved localized error categories+The Settings inventory exposes an additive `RemoteHostSummary.status` of+`connected`, `connecting`, `reconnecting`, `disconnected` or `action-required`;+older summaries without this field continue to render from `connected`. The+status contains no SSH diagnostics or credential material.+replace raw SSH diagnostics and incidental forwarded URLs in the UI.++A lost transport reply for Write/Edit/Bash is reported as+`REMOTE_MUTATION_OUTCOME_UNKNOWN` with `retriable: false`; inspect remote state+before an explicit retry. This does not claim rollback or exactly-once execution+after an uncertain outcome.+Existing remote Agent histories remain reachable through their previous backend.Their session capabilities and opaque history cursors remain enforced; this doesnot grant them local project paths or change their persisted ownership.diff --git a/docs/spec/03-runtime/19-remote-agent-control-protocol.md b/docs/spec/03-runtime/19-remote-agent-control-protocol.mdindex 0d894c9e6..077a77948 100644--- a/docs/spec/03-runtime/19-remote-agent-control-protocol.md+++ b/docs/spec/03-runtime/19-remote-agent-control-protocol.md@@ -623,8 +623,21 @@ Legacy remote-Agent operations above remain unchanged.the calling device's active operation. Closing the originating connectioncancels its outstanding calls. Host restarts invalidate late results.- `workspace/files` accepts `{ path, operation, ref?, mimeType? }`, where- operation is list/read/index/resolve/image/diff. It reads only the canonical- workspace boundary using existing file helpers and no persistent Host session.+ operation is list/read/index/resolve/image/diff/instructions. It reads only the+ canonical workspace boundary using existing helpers and no persistent Host+ session. Existing operations and their payloads remain unchanged; this is an+ additive operation, not a protocol-major change.+ For `instructions`, Desktop sends `{ path, operation: "instructions" }` and+ the Host returns `{ entries: [{ source, content }] }`, or `{ entries: [] }`.+ Root-only selection takes the first readable, nonempty, contained file in+ `AGENTS.override.md`, `AGENTS.md`, `CLAUDE.md`, `.claude/CLAUDE.md` order.+ A file symlink escaping the root is skipped. At most one entry is returned;+ `source` is that recognized relative name, not a remote HOME or absolute path.+ File content is capped at 32 KiB of UTF-8 without splitting a character, with+ an explicit truncation notice. Desktop validates recognized sources, at most+ one entry and at most 33,280 UTF-8 bytes including the notice, then merges+ local global defaults before remote root instructions. Nested traversal and+ remote global defaults are not supported by this operation.`workspaceTools` and `workspaceFiles` are optional advertised capabilities; anolder Host fails with CAPABILITY_UNAVAILABLE/METHOD_NOT_FOUND rather than@@ -634,6 +647,13 @@ limits concurrent tools to 32, retains a bounded 4096-key replay fence, and bounarguments/results to 1 MiB. These services never carry model requests, modelsettings, provider headers, API keys or OAuth tokens.+If Write/Edit/Bash loses its reply with HOST_DISCONNECTED, TIMEOUT,+AGENT_UNAVAILABLE or REMOTE_CONNECTION_FAILED, the Desktop relay reports+`REMOTE_MUTATION_OUTCOME_UNKNOWN` with `retriable: false`. It cannot prove that+the mutation did or did not run; inspect remote state before an explicit retry.+This is a Desktop execution error mapping, not a new wire method or an+exactly-once guarantee. Read/Glob/Grep retain their ordinary failure mapping.+### 6.3 Deferred operationsThe desktop offers these locally. RACP does not expose them yet; the namesdiff --git a/docs/spec/05-security/02-remote-control-security.md b/docs/spec/05-security/02-remote-control-security.mdindex b09c81b25..c4e07b313 100644--- a/docs/spec/05-security/02-remote-control-security.md+++ b/docs/spec/05-security/02-remote-control-security.md@@ -149,11 +149,25 @@ pairing only binds a desktop device to the Host it started.device as `owner` of that Host.- The Host binds loopback only and accepts a device token only from aloopback peer; a non-loopback bind requires TLS and the same device token.-- The bootstrap script, uploaded over SSH, downloads the `pi-host` bundle for- the remote platform at the desktop's version from GitHub Releases, verifies- the SHA-256 published with the release, and installs it under the user's- home; the desktop never uploads executable bytes itself. A machine without- outbound access to GitHub cannot be bootstrapped in the first version.+- Resolve the same-version published target and trusted release SHA-256 over+ HTTPS. Prefer remote download; only `download-failed` permits one bounded+ Desktop download, local verification and SSH upload of the same artifact.+ Authentication, integrity and version failures MUST NOT authorize fallback.+ Remote verification precedes extraction/install on either path. This limited+ executable-upload exception amends the original prohibition under+ [ADR 0326](../../adr/0326-verified-ssh-host-installation.md); it does not permit+ arbitrary executable uploads or bypass SSH host-key checks. SHA-256 is relative+ to the trusted release, not an independent signature-verification scheme.+- New bundles include native Node >=22 and `SHA256SUMS`. Stage privately, reject+ unsafe manifest entries and special files, verify installed files, and switch+ content-addressed `current` atomically under deployment/install locks. Reuse+ requires an external receipt matching version, archive digest and manifest+ digest plus read-only file verification; version equality alone is insufficient.+ System Node and remote GitHub access are not required for new bundles, but+ supported Linux ABI, POSIX/hash/archive tools and Linux `flock` still are.+- Daily readiness MUST NOT reinstall, re-pair or reset credentials. Validate+ loopback readiness/version and saved Host ID before forwarding, then validate+ the RACP identity. A legacy descriptor without Host ID remains readable.- Revoking the device token on the Host, or removing the Host from thedesktop, ends the pairing; a new pairing needs a new SSH bootstrap.- Provider configuration is copied only after explicit selection and consent,@@ -222,6 +236,20 @@ resolution or mutation realpath probes. Trusted extensions still register localmodel providers. Their implicit workspace `pi.exec` is rejected for a remote root;local provider helpers must explicitly supply a local working directory.+Root repository instructions are returned by owner-only `workspace/files`+`operation: "instructions"`, bounded to 32 KiB of UTF-8 file content plus an+explicit truncation notice. Selection is root-only in recognized-name precedence,+and a symlink escaping the root is skipped. Desktop validates the response and+merges it after local global defaults; remote HOME defaults and nested directory+traversal are excluded. Instruction text is untrusted repository data, not a grant+of tool, filesystem or credential authority.++Loss of a Write/Edit/Bash transport reply yields the Desktop-side+`REMOTE_MUTATION_OUTCOME_UNKNOWN` error with `retriable: false`, not an automatic+retry or a rollback claim. Readiness for browse/files does not replay tools.+Remote picker and Settings errors use allowlisted localized categories rather+than raw SSH stderr, tokens, password/private-key paths or forwarded URLs.+## 4. Authorization model### 4.1 Role matrixdiff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex e9d68a16e..04bae3348 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -14638,12 +14638,11 @@ browser milestones are scheduled.while idle, then attempt it while a turn runs. 6) Open the files tab and thediff tab for the remote session. 7) Advertise relay from the desktop, run aturn that calls the desktop MCP tool, then close the desktop during a- second call. 8) Open a terminal on the remote session and run a command.- 9) Kill the SSH session mid-turn with the terminal open, restore it, and- let the desktop reconnect. 10) Inspect the remote tool catalog. 11) Attempt- to connect from a non-loopback address on the remote machine, then with a- reused pairing token. 12) Point the bootstrap at the tampered bundle, then- at the other version, and reconnect.+ second call. 8) Kill the SSH session mid-turn, restore it, and let the desktop+ reconnect. 9) Inspect the remote tool catalog. 10) Attempt to connect from a+ non-loopback address on the remote machine, then with a reused pairing token.+ 11) Point the bootstrap at the tampered bundle, then at the other version,+ and reconnect.- **Expected**: Files change only on the remote machine and the command runsthere; the approval card appears in the desktop with the local vocabulary;the remote host-core binds loopback only; `session/configure` succeeds while@@ -14651,16 +14650,12 @@ browser milestones are scheduled.remote session root and a path outside it returns`PATH_OUTSIDE_WORKSPACE`; the desktop MCP tool executes on the desktop andits result reaches the remote transcript, while the second call fails with- `TOOL_FAILED` and the turn continues; the terminal runs on the remote- machine inside the session root; the turn continues through the SSH drop,- the desktop resumes by cursor without a duplicate, and the terminal output- resumes from the replay ring; the remote catalog lists the relayed MCP tool- but not the workspace-requiring plugin tool; the non-loopback peer and the- reused pairing token are rejected; the tampered bundle is refused before- start with a Settings toast that names the checksum failure rather than a- bare SSH exit code; a refused SSH login surfaces ssh's last stderr line in- that toast; the version mismatch returns `PROTOCOL_MISMATCH` and offers the- re-download; and the local session is untouched throughout.+ `TOOL_FAILED` and the turn continues; reconnect resumes by cursor without a+ duplicate. The remote catalog lists the relayed MCP tool but not the+ workspace-requiring plugin tool. Non-loopback peers and reused pairing tokens+ are rejected. Tampered bundles are refused before start; SSH login failures+ are surfaced safely; version mismatch offers a matching-release recovery.+ The local session is untouched throughout.- **Specs linked**: `02-architecture/05-remote-agent-control.md` §§5.2 and6.3, `03-runtime/19-remote-agent-control-protocol.md` §§6.2, 9.4, and11.1, `05-security/02-remote-control-security.md` §§3.4, 4.3, 5.1, and 7,@@ -14669,6 +14664,42 @@ browser milestones are scheduled.- **Milestone**: Post-MVP (rollout R2)- **Status**: Draft; remote harness with a Linux SSH target required+#### E2E-REMOTE-SSH-OPTIMIZATION: Verified deployment, local Agent and recovery++- **Preconditions**: Isolated Desktop profile and a Linux x64/arm64 SSH target+ with `sshd`, POSIX shell, archive/hash tools and kernel `flock`; no system Node,+ systemd, public listener, production credential or paid model. A controlled+ release fixture serves a matching Host archive and digest.+- **Steps**: Install through SSH with remote download; repeat bootstrap and verify+ immutable installed files are reused. In a separate isolated account, block+ remote release access and verify one bounded Desktop-download/SSH-upload path.+ Corrupt the archive and alter an installed file; verify integrity failures do+ not fall back or replace a working install. Reboot/kill the Host and repeat+ readiness; rotate Host identity and revoke a device token. Create a local+ project bound to the remote workspace, use local model credentials and remote+ `AGENTS.md` with local global instructions, then run Read and permissioned Bash.+ Drop SSH during Write and inspect the remote file before any manual retry.+ Exercise offline project browsing and the Settings connection status labels.+- **Expected**: Bundled Node starts the Host without a system Node or remote+ release access. Reuse validates the external release receipt and installed+ manifest; failed staging leaves the previous `current` intact. Daily readiness+ starts/reuses the same Host without re-pairing, resetting credentials, killing+ another client’s Host or replaying tools. Identity/authentication failures stop+ automatic retry. Local model requests, API keys, sessions and permissions stay+ local; workspace tools/files and root-only repository instructions come from+ the remote canonical root. A lost mutation reply reports+ `REMOTE_MUTATION_OUTCOME_UNKNOWN` and is not replayed or executed locally.+- **Automation**: `remote-host-supervisor.test.mjs`, SSH bootstrap shell,+ packaging, artifact transfer, concurrent readiness/auth lifecycle and UI+ contract suites; `PI_HOST_CORE_BINARY=<candidate binary> node+ scripts/e2e-local-agent-remote-tools.mjs` covers local model/instructions+ through real loopback RACP and Rust Read/Bash, but is not SSH qualification.+- **Acceptance**: Security, Recovery, Quality; release remains gated on the+ real Linux SSH run and a new matching Desktop/Host release. This scenario does+ not claim reverse-relay, interactive-terminal or complete R2 acceptance.+- **Status**: Candidate implementation; Linux SSH and release qualification+ pending.+#### E2E-REMOTE-HOST-ssh-password-authentication- **Preconditions**: Settings → Remote Hosts is available with its Experimentaldiff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.tsindex 78220f856..8ed9297e7 100644--- a/packages/i18n/src/locales/de/index.ts+++ b/packages/i18n/src/locales/de/index.ts@@ -1201,6 +1201,9 @@ sklm: {"empty": "Keine Hosts","statusOnline": "Online","statusOffline": "Offline",+ statusConnecting: "Verbindung wird hergestellt…",+ statusReconnecting: "Verbindung wird wiederhergestellt…",+ statusActionRequired: "Aktion erforderlich","remove": "Entfernen","removing": "Wird entfernt…","removed": "{{label}} entfernt.",diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.tsindex 8238fbc10..96aa72a25 100644--- a/packages/i18n/src/locales/en/index.ts+++ b/packages/i18n/src/locales/en/index.ts@@ -1053,6 +1053,9 @@ sklm: {empty: "No hosts",statusOnline: "Online",statusOffline: "Offline",+ statusConnecting: "Connecting…",+ statusReconnecting: "Reconnecting…",+ statusActionRequired: "Action required",remove: "Remove",removing: "Removing…",removed: "{{label}} removed.",diff --git a/packages/i18n/src/locales/es/index.ts b/packages/i18n/src/locales/es/index.tsindex 80dd0b702..e2e6c1d65 100644--- a/packages/i18n/src/locales/es/index.ts+++ b/packages/i18n/src/locales/es/index.ts@@ -1201,6 +1201,9 @@ sklm: {"empty": "Sin hosts","statusOnline": "En línea","statusOffline": "Sin conexión",+ statusConnecting: "Conectando…",+ statusReconnecting: "Reconectando…",+ statusActionRequired: "Se requiere atención","remove": "Quitar","removing": "Quitando…","removed": "{{label}} quitado.",diff --git a/packages/i18n/src/locales/fr/index.ts b/packages/i18n/src/locales/fr/index.tsindex fabce2df0..c21ac5b00 100644--- a/packages/i18n/src/locales/fr/index.ts+++ b/packages/i18n/src/locales/fr/index.ts@@ -1201,6 +1201,9 @@ sklm: {"empty": "Aucun hôte","statusOnline": "En ligne","statusOffline": "Hors ligne",+ statusConnecting: "Connexion…",+ statusReconnecting: "Reconnexion…",+ statusActionRequired: "Action requise","remove": "Retirer","removing": "Retrait…","removed": "{{label}} retiré.",diff --git a/packages/i18n/src/locales/ko/index.ts b/packages/i18n/src/locales/ko/index.tsindex e2f33e611..be8d63933 100644--- a/packages/i18n/src/locales/ko/index.ts+++ b/packages/i18n/src/locales/ko/index.ts@@ -1209,6 +1209,9 @@ sklm: {empty: "호스트 없음",statusOnline: "온라인",statusOffline: "오프라인",+ statusConnecting: "연결 중…",+ statusReconnecting: "재연결 중…",+ statusActionRequired: "조치 필요",remove: "제거",removing: "제거 중…",removed: "{{label}} 제거됨.",diff --git a/packages/i18n/src/locales/pt-BR/index.ts b/packages/i18n/src/locales/pt-BR/index.tsindex e7866b214..a2d66e415 100644--- a/packages/i18n/src/locales/pt-BR/index.ts+++ b/packages/i18n/src/locales/pt-BR/index.ts@@ -1021,6 +1021,9 @@ export const ptBR = {empty: "Sem hosts",statusOnline: "En linha",statusOffline: "Sem conexão",+ statusConnecting: "Conectando…",+ statusReconnecting: "Reconectando…",+ statusActionRequired: "Ação necessária",remove: "Remover",removing: "Removendo…",removed: "{{label}} removido.",diff --git a/packages/i18n/src/locales/tr/index.ts b/packages/i18n/src/locales/tr/index.tsindex 44caad155..936c91661 100644--- a/packages/i18n/src/locales/tr/index.ts+++ b/packages/i18n/src/locales/tr/index.ts@@ -1203,6 +1203,9 @@ sklm: {empty: "Ana bilgisayar yok",statusOnline: "Çevrimiçi",statusOffline: "Çevrimdışı",+ statusConnecting: "Bağlanıyor…",+ statusReconnecting: "Yeniden bağlanıyor…",+ statusActionRequired: "İşlem gerekli",remove: "Kaldır",removing: "Kaldırılıyor…",removed: "{{label}} kaldırıldı.",diff --git a/packages/i18n/src/locales/zh-CN/index.ts b/packages/i18n/src/locales/zh-CN/index.tsindex 7499f5a22..974c26891 100644--- a/packages/i18n/src/locales/zh-CN/index.ts+++ b/packages/i18n/src/locales/zh-CN/index.ts@@ -1193,6 +1193,9 @@ sklm: {empty: "暂无主机",statusOnline: "在线",statusOffline: "离线",+ statusConnecting: "连接中…",+ statusReconnecting: "正在重连…",+ statusActionRequired: "需要处理",remove: "移除",removing: "移除中…",removed: "已移除 {{label}}。",diff --git a/packages/i18n/src/locales/zh-TW/index.ts b/packages/i18n/src/locales/zh-TW/index.tsindex 45f146c73..b3a4f5107 100644--- a/packages/i18n/src/locales/zh-TW/index.ts+++ b/packages/i18n/src/locales/zh-TW/index.ts@@ -1193,6 +1193,9 @@ sklm: {empty: "尚無主機",statusOnline: "在線",statusOffline: "離線",+ statusConnecting: "連線中…",+ statusReconnecting: "正在重新連線…",+ statusActionRequired: "需要處理",remove: "移除",removing: "移除中…",removed: "已移除 {{label}}。",diff --git a/packages/racp/src/client.ts b/packages/racp/src/client.tsindex c42439cb6..58ea95b36 100644--- a/packages/racp/src/client.ts+++ b/packages/racp/src/client.ts@@ -305,6 +305,11 @@ export class RacpClient {this.transport = null;this.rejectPending(new RacpError("HOST_DISCONNECTED", "reconnect failed", { retriable: true }));transport?.close(1000, "reconnect failed");+ const failure = toRacpError(error, "HOST_DISCONNECTED");+ if (!failure.retriable) {+ this.setState("error", failure);+ return;+ }this.setState("reconnecting");}}@@ -330,6 +335,8 @@ export class RacpClient {function toRacpError(error: unknown, fallbackCode: string): RacpError {if (error instanceof RacpError) return error;- const code = (error as { errorCode?: string })?.errorCode ?? fallbackCode;- return new RacpError(code, error instanceof Error ? error.message : String(error), { retriable: true });+ const fields = error && typeof error === "object" ? error as { errorCode?: string; retriable?: boolean } : undefined;+ const code = fields?.errorCode ?? fallbackCode;+ const retriable = fields?.retriable ?? !["HOST_AUTH_FAILED", "REMOTE_AUTH_FAILED", "HOST_VERSION_MISMATCH", "TOKEN_INVALID", "TOKEN_EXPIRED", "TOKEN_REVOKED"].includes(code);+ return new RacpError(code, error instanceof Error ? error.message : String(error), { retriable });}diff --git a/packages/racp/src/racp.test.ts b/packages/racp/src/racp.test.tsindex af41f3ff8..40736e531 100644--- a/packages/racp/src/racp.test.ts+++ b/packages/racp/src/racp.test.ts@@ -285,6 +285,23 @@ describe("RACP-WS reconnect", () => {expect(states.at(-1)).toBe("error");expect(client.state).toBe("error");});+ it.each(["HOST_AUTH_FAILED", "HOST_VERSION_MISMATCH"])("stops automatic reconnect after non-retriable %s", async (errorCode) => {+ const h = await harness();+ let attempts = 0;+ let ended!: () => void;+ const failed = new Promise<void>((resolve) => { ended = resolve; });+ const { client, link } = await h.connect(OWNER_TOKEN, {+ reconnect: { enabled: true, maxAttempts: 2 }, sleep: async () => undefined,+ onReconnected: async () => { attempts++; throw Object.assign(new Error("action required"), { errorCode, retriable: false }); },+ onStateChange: (state) => { if (state === "error") ended(); },+ });+ try {+ link().drop();+ await failed;+ expect(attempts).toBe(1);+ expect(client.state).toBe("error");+ } finally { await client.close(); }+ });});describe("RACP-WS remote-host profile", () => {diff --git a/packages/racp/src/ws-binding.test.ts b/packages/racp/src/ws-binding.test.tsindex fdf937899..1f074a236 100644--- a/packages/racp/src/ws-binding.test.ts+++ b/packages/racp/src/ws-binding.test.ts@@ -76,6 +76,29 @@ describe("RACP-WS over a loopback socket", () => {}});+ it("stops reconnecting after a real WebSocket upgrade rejects a revoked device", async () => {+ const h = await harness();+ const binding = await bindRacpWebSocket({ server: h.server, authenticator: h.authenticator, port: 0, log: () => undefined });+ const factory = wsClientTransport({ url: `ws://127.0.0.1:${binding.address.port}/v1/racp/ws`, token: OWNER_TOKEN });+ let attempts = 0;+ let drop!: () => void;+ let failed!: () => void;+ const ended = new Promise<void>(resolve => { failed = resolve; });+ const client = new RacpClient({+ transport: async () => { attempts++; const transport = await factory(); drop = () => transport.close(); return transport; },+ client: { name: "test", version: "1" }, reconnect: { enabled: true, maxAttempts: 3 }, sleep: async () => undefined,+ onStateChange: state => { if (state === "error") failed(); },+ });+ try {+ await client.connect();+ await h.store.revokeDevice("dev_owner", "2026-09-18T00:00:00.000Z");+ drop();+ await ended;+ expect(attempts).toBe(2);+ expect(client.state).toBe("error");+ } finally { await client.close(); await binding.close(); }+ });+it("refuses to bind a non-loopback address and plain ws to a non-loopback host", async () => {const h = await harness();await expect(bindRacpWebSocket({ server: h.server, authenticator: h.authenticator, host: "0.0.0.0", port: 0, log: () => undefined })).rejects.toMatchObject({ errorCode: "INVALID_ARGUMENT" });diff --git a/packages/shared/src/racp.test.ts b/packages/shared/src/racp.test.tsindex 23bcd5804..343ec3f35 100644--- a/packages/shared/src/racp.test.ts+++ b/packages/shared/src/racp.test.ts@@ -16,6 +16,7 @@ import {RacpEventEnvelopeSchema,RacpInitializeResultSchema,RacpSessionSnapshotSchema,+ WorkspaceFilesRequestSchema,allowedDecisionsAreCoherent,effectiveRemotePermissionMode,eventEnvelopeSequencingIsValid,@@ -364,3 +365,13 @@ describe("versions and errors", () => {});});});++describe("SSH repository instruction file contract", () => {+ it("accepts the additive operation and preserves existing file operations", () => {+ for (const operation of ["instructions", "list", "read", "index", "resolve", "image", "diff"]) {+ expect(Value.Check(WorkspaceFilesRequestSchema, { path: "/repo", operation })).toBe(true);+ }+ expect(Value.Check(WorkspaceFilesRequestSchema, { path: "/repo", operation: "instructions", globalHome: true })).toBe(false);+ expect(Value.Check(WorkspaceFilesRequestSchema, { path: "/repo", operation: "unknown" })).toBe(false);+ });+});diff --git a/packages/shared/src/racp.ts b/packages/shared/src/racp.tsindex 10e91a701..516d39086 100644--- a/packages/shared/src/racp.ts+++ b/packages/shared/src/racp.ts@@ -105,7 +105,7 @@ export type RacpRequestContext = Static<typeof RacpRequestContextSchema>;export const WorkspaceFilesRequestSchema = Type.Object({path: Type.String({ minLength: 1, maxLength: 4096 }),- operation: Type.Union([Type.Literal("list"), Type.Literal("read"), Type.Literal("index"), Type.Literal("resolve"), Type.Literal("image"), Type.Literal("diff")]),+ operation: Type.Union([Type.Literal("list"), Type.Literal("read"), Type.Literal("index"), Type.Literal("resolve"), Type.Literal("image"), Type.Literal("diff"), Type.Literal("instructions")]),ref: Type.Optional(Type.String({ maxLength: 4096 })),mimeType: Type.Optional(Type.String({ maxLength: 256 })),}, { additionalProperties: false });diff --git a/packages/shared/src/types/remote-host.ts b/packages/shared/src/types/remote-host.tsindex 7a6a62594..dff99a82e 100644--- a/packages/shared/src/types/remote-host.ts+++ b/packages/shared/src/types/remote-host.ts@@ -59,13 +59,19 @@ export type RemoteHostSshMetadata = {remotePort: number;/** Release version the bootstrap installed, checked against `APP_VERSION`. */version: string;+ /** Identity enrolled during bootstrap; absent on older descriptors. */+ hostId?: string;};+export type RemoteHostConnectionStatus = "connected" | "connecting" | "reconnecting" | "disconnected" | "action-required";+export type RemoteHostSummary = {hostKey: string;label: string;url: string;connected: boolean;+ /** Additive display state; absent on summaries produced by older desktop versions. */+ status?: RemoteHostConnectionStatus;/** Absent on records written before the SSH bootstrap existed → `direct`. */transport?: RemoteHostTransport;};diff --git a/scripts/e2e-local-agent-remote-tools.mjs b/scripts/e2e-local-agent-remote-tools.mjsindex ee51eb96a..bce920178 100644--- a/scripts/e2e-local-agent-remote-tools.mjs+++ b/scripts/e2e-local-agent-remote-tools.mjs@@ -14,10 +14,12 @@ const { HostProcess, createHostSessionPort } = await import("../packages/host-ruconst { AgentHost } = await import("../packages/agent-host/dist/index.js");const { bindRacpWebSocket, RacpServer, MemoryCredentialStore, DeviceTokenAuthenticator, hashToken, newDeviceToken } = await import("../packages/racp/dist/index.js");const { createWorkspaceTools } = await import("../apps/pi-host/dist/workspace-tools.js");+const { createWorkspaceFiles } = await import("../apps/pi-host/dist/workspace-files.js");const { createHostOperations } = await import("../apps/pi-host/dist/host-operations.js");const OWNER_TOKEN = newDeviceToken();const { createRemoteHostsBoot } = await import("../apps/desktop/electron/main/bootstrap/remote-hosts.ts");const { createRemoteWorkspaceToolRelay } = await import("../apps/desktop/electron/main/remote/remote-workspace-tools.ts");+const { loadRemoteWorkspaceInstructions } = await import("../apps/desktop/electron/main/remote/remote-workspace-instructions.ts");const { createBackendRouter } = await import("../apps/desktop/electron/main/remote/backend-router.ts");assert.ok(process.env.PI_HOST_CORE_BINARY, "PI_HOST_CORE_BINARY must name the current candidate Rust binary");@@ -25,6 +27,8 @@ const root = await mkdtemp(join(process.env.PI_SCRATCH_DIR ?? tmpdir(), "local-aconst remoteRoot = join(root, "remote-workspace");await mkdir(remoteRoot); await mkdir(join(root, "desktop"));await writeFile(join(remoteRoot, "README.md"), "REMOTE_READ_FIXTURE\n");+await writeFile(join(remoteRoot, "AGENTS.md"), "REMOTE_REPOSITORY_INSTRUCTIONS_FIXTURE\n");+await writeFile(join(remoteRoot, "CLAUDE.md"), "LOWER_PRIORITY_INSTRUCTIONS_MUST_NOT_LOAD\n");const KEY = "local-model-fixture-key-never-forwarded";let modelCalls = 0;let modelError;@@ -43,6 +47,10 @@ const model = createServer(async (req, res) => {let body = ""; for await (const chunk of req) body += chunk;const input = JSON.parse(body);assert.equal(input.model, "local-fixture");+ const context = JSON.stringify(input.messages);+ assert.ok(context.includes("REMOTE_REPOSITORY_INSTRUCTIONS_FIXTURE"), "RACP repository instructions enter local model context");+ assert.ok(context.includes("LOCAL_GLOBAL_INSTRUCTIONS_FIXTURE"), "local global defaults remain local model context");+ assert.ok(!context.includes("LOWER_PRIORITY_INSTRUCTIONS_MUST_NOT_LOAD"), "repository precedence is preserved");modelCalls++;res.writeHead(200, { "content-type": "text/event-stream" });const frame = (delta, finish_reason = null) => res.write(`data: ${JSON.stringify({ id: `local-${modelCalls}`, object: "chat.completion.chunk", created: 1, model: input.model, choices: [{ index: 0, delta, finish_reason }] })}\n\n`);@@ -76,11 +84,14 @@ try {const authenticator = new DeviceTokenAuthenticator(credentials);const operations = createHostOperations({ getHost: () => host, runtime: { isBusy: () => false, async compact() { throw new Error("no remote model"); } } });operations.workspaceTools = { ...tools, async execute(input, owner) { wireCalls.push(structuredClone(input)); return tools.execute(input, owner); } };+ operations.workspaceFiles = createWorkspaceFiles();h = { server: new RacpServer({ agentHost, operations, authenticator, hostId: "tool-host", serverVersion: "fixture", log: () => {} }), remotePrompts: () => remotePrompts };binding = await bindRacpWebSocket({ server: h.server, authenticator, host: "127.0.0.1", port: 0, log: () => {} });boot = createRemoteHostsBoot({ dataDir: join(root, "desktop"), router: createBackendRouter(), clientInfo: { name: "local-agent-fixture", version: "fixture" }, emit: () => {}, encryption: { isAvailable: () => true, encryptString: value => Buffer.from(value), decryptString: value => value.toString() } });assert.equal((await boot.addHost({ hostKey: "fixture", label: "Fixture", url: `ws://127.0.0.1:${binding.address.port}/v1/racp/ws`, deviceToken: OWNER_TOKEN })).connected, true);const shell = await boot.workspaceCommandShell("fixture");+ const projectInstructions = await loadRemoteWorkspaceInstructions(boot.workspaceFiles,+ { hostKey: "fixture", path: remoteRoot }, { entries: [{ source: "local-global", content: "LOCAL_GLOBAL_INSTRUCTIONS_FIXTURE" }] });localHost = new HostProcess({ binaryPath: resolve(process.env.PI_HOST_CORE_BINARY), dataDir: join(root, "local-host"), onStderr: () => {} });await localHost.handshake();const created = await localHost.call("project.group.createRemote", { name: "Locally named remote project", remote: { hostKey: "fixture", path: remoteRoot } });@@ -98,6 +109,7 @@ try {const done = new Promise((resolveDone, rejectDone) => { ended = envelope => { if (envelope.event.type === "error") rejectDone(new Error(JSON.stringify(envelope.event))); if (envelope.event.type === "agent_end") resolveDone(); }; });runtime = new DesktopAgentRuntime({sessionId: localSession.session.id, mode: "agent", thinkingLevel: "off", commandShell: shell,+ projectInstructions,remoteWorkspace: { hostKey: "fixture", path: remoteRoot },provider: { id: "local-provider", name: "Local fixture", modelId: "local-fixture", baseUrl: `http://127.0.0.1:${model.address().port}/v1`, apiStyle: "chat_completions", apiKey: KEY, authKind: "api_key", supportsReasoning: false, supportedThinkingLevels: ["off"] },host: { call: (method, params) => localHost.call(method, params), onNotification: handler => localHost.onNotification(handler) },@@ -121,7 +133,7 @@ try {await assert.rejects(boot.executeWorkspaceTool({ ...wireCalls[0], hostKey: "fixture" }), "duplicate tool id cannot replay");await boot.removeHost("fixture");await assert.rejects(boot.executeWorkspaceTool({ ...wireCalls[0], toolCallId: "after-disconnect", hostKey: "fixture" }), { errorCode: "AGENT_UNAVAILABLE" });- console.log("PASS local model/key + local Rust project/permission relay + real RACP/Rust Read/Bash, no remote providers/projects/sessions, no replay/fallback");+ console.log("PASS local model/key/instructions + local Rust project/permission relay + real RACP/Rust Read/Bash, no remote providers/projects/sessions, no replay/fallback");} finally {clearTimeout(deadline);await runtime?.dispose(); relay?.dispose(); await localHost?.dispose(); await boot?.closeAll(); h?.server.close(); await binding?.close(); await host?.dispose();