Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
fix(remote-host): auto-realign mismatched SSH Hosts
vastsa63ddb5864fe9
diff --git a/apps/desktop/electron/main/bootstrap/remote-hosts.ts b/apps/desktop/electron/main/bootstrap/remote-hosts.tsindex 354ce0e21..95fd2e3ca 100644--- a/apps/desktop/electron/main/bootstrap/remote-hosts.ts+++ b/apps/desktop/electron/main/bootstrap/remote-hosts.ts@@ -14,6 +14,7 @@ import type { HostRpcPort } from "@pi-desktop/agent-host";import type { BackendRouter } from "../remote/backend-router.js";import { makeRemoteSessionId, parseRemoteSessionId } from "../remote/backend-router.js";import { createRacpRemoteHostClient, exchangePairingToken, type RacpRemoteHostClient } from "../remote/racp-remote-host-client.js";+import { createRemoteHostRealigner, type RemoteHostRealignResult } from "../remote/remote-host-realign.js";import { createSshBootstrap, type SshBootstrapDeps } from "../remote/ssh-bootstrap.js";import { createSshTunnelManager, type SshTunnelManager } from "../remote/ssh-tunnel.js";import { createRemoteHostConnection, type RemoteHostConnection } from "../remote/remote-host-connection.js";@@ -90,6 +91,30 @@ function requiresUserAction(error: unknown): boolean {.includes(fields.errorCode ?? fields.code ?? "");}+/** The one failure that a version realignment can fix (ADR 0327). */+function isHostVersionMismatch(error: unknown): boolean {+ if (!error || typeof error !== "object") return false;+ const fields = error as { errorCode?: string; code?: string };+ return (fields.errorCode ?? fields.code ?? "") === "HOST_VERSION_MISMATCH";+}++/**+ * A paired Host can run the right release and still predate the additive+ * workspace services a remote project needs — the bundle is reused by release+ * receipt, not by the capabilities it happens to contain. The handshake is the+ * only place that is observable, so it is checked once per connect rather than+ * on every `workspace/*` call. Adapters that report no capabilities (tests,+ * legacy callers) are left alone.+ */+function assertWorkspaceCapabilities(adapter: RacpRemoteHostClient): void {+ const capabilities = adapter.workspaceCapabilities?.();+ if (!capabilities || (capabilities.workspaceTools && capabilities.workspaceFiles)) return;+ throw Object.assign(+ new Error("the remote Host predates the workspace tools and files this Desktop release requires"),+ { errorCode: "HOST_VERSION_MISMATCH", retriable: false },+ );+}+export function createRemoteHostsBoot(options: BootRemoteHostsOptions): RemoteHostsBoot {const log = options.log ?? (() => undefined);const registry = createRemoteHostRegistry({ dataDir: options.dataDir, encryption: options.encryption, log });@@ -165,6 +190,19 @@ export function createRemoteHostsBoot(options: BootRemoteHostsOptions): RemoteHolog, ...options.sshBootstrap,});+ /**+ * Re-provision one paired Host onto this desktop's release, in place. It+ * reuses the verified bootstrap the pairing path uses, so the artifact must+ * still match the published SHA-256 and pass the installed manifest check;+ * only the trigger differs (ADR 0327).+ */+ const realigner = createRemoteHostRealigner({+ version: options.clientInfo.version,+ bootstrap: (request, execOptions) => bootstrap.bootstrap(request, execOptions),+ upsert: (record) => registry.upsert(record),+ log,+ });+function closeHost(host: OpenHost): Promise<void> {const existing = hostClosings.get(host);if (existing) return existing;@@ -183,13 +221,20 @@ export function createRemoteHostsBoot(options: BootRemoteHostsOptions): RemoteHoopened.delete(key);if (host) await closeHost(host);}- async function openHost(record: RemoteHostRecord): Promise<OpenHost> {+ async function openHostOnce(record: RemoteHostRecord): Promise<OpenHost> {assertOpen();const ssh = sshMetadataOf(record);if (record.metadata?.transport === "ssh" && !ssh) {throw Object.assign(new Error("invalid SSH host metadata"), { errorCode: "INVALID_ARGUMENT" });}- const url = ssh ? (await tunnels.open(record.hostKey, ssh, record.sshSecret)).url : record.url;+ // Readiness compares the running Host against the release this desktop+ // expects, not the version recorded at pairing time: a stale descriptor+ // must not mask a Host that is behind, which is the case realignment+ // repairs.+ const expected = ssh ? { ...ssh, version: options.clientInfo.version } : undefined;+ const url = expected+ ? (await tunnels.open(record.hostKey, expected, record.sshSecret)).url+ : record.url;if (closed) { await tunnels.close(record.hostKey); throw unavailable(); }const adapter = buildAdapter({ ...record, url });const connection = createRemoteHostConnection({@@ -209,6 +254,7 @@ export function createRemoteHostsBoot(options: BootRemoteHostsOptions): RemoteHoopened.set(record.hostKey, live);await adapter.connect();assertOpen();+ assertWorkspaceCapabilities(adapter);await connection.open();assertOpen();opened.set(record.hostKey, live);@@ -224,6 +270,61 @@ export function createRemoteHostsBoot(options: BootRemoteHostsOptions): RemoteHoopeningHosts.delete(live);}}++ /**+ * Re-provision a paired Host onto this desktop's release and re-pair it in+ * place. `force` is the user's explicit reconnect, which must not be silently+ * throttled. Returns the refreshed record, or `null` when the attempt was not+ * allowed or did not succeed.+ */+ async function realignHost(record: RemoteHostRecord, force: boolean): Promise<RemoteHostRecord | null> {+ const decision = realigner.decide(record, { force });+ if (decision !== "attempt") {+ log("info", "remote host realignment not attempted", {+ hostKey: record.hostKey, decision, version: options.clientInfo.version,+ });+ return null;+ }+ log("info", "remote host realignment started", {+ hostKey: record.hostKey, version: options.clientInfo.version,+ });+ assertOpen();+ await closeLive(record.hostKey);+ await tunnels.close(record.hostKey);+ assertOpen();+ const controller = new AbortController();+ const task = realigner.realign(record, { force, signal: controller.signal });+ bootstraps.set(controller, task);+ let result: RemoteHostRealignResult | null;+ try { result = await task; }+ finally { bootstraps.delete(controller); }+ if (!result) return null;+ try {+ assertOpen();+ await tunnels.adopt(record.hostKey, result.outcome.ssh, result.outcome.forward);+ } catch (error) {+ // `adopt` never took ownership, so this call still owns the forward.+ await result.outcome.forward.close().catch(() => undefined);+ throw error;+ }+ return result.record;+ }++ /**+ * Open one host, and when it is refused for its version, bring it up to this+ * release and open it again. A second failure is surfaced unchanged: a+ * realignment that cannot help must never hide the reason the user sees.+ */+ async function openHost(record: RemoteHostRecord, forceRealign = false): Promise<OpenHost> {+ try {+ return await openHostOnce(record);+ } catch (error) {+ if (closed || !isHostVersionMismatch(error)) throw error;+ const realigned = await realignHost(record, forceRealign);+ if (!realigned) throw error;+ return await openHostOnce(realigned);+ }+ }function summaryOf(record: RemoteHostRecord): RemoteHostSummary {const state = opened.get(record.hostKey)?.adapter.state();const status: RemoteHostConnectionStatus = state === "connected" || state === "connecting" || state === "reconnecting"@@ -392,7 +493,9 @@ export function createRemoteHostsBoot(options: BootRemoteHostsOptions): RemoteHoif (!record) throw unavailable();await closeLive(key);await tunnels.close(key);- await openHost(record);+ // An explicit reconnect is the user asking again, so it may realign a+ // Host the automatic throttling has already given up on for this release.+ await openHost(record, true);return summaryOf(record);}),async bootstrapHost(request) {diff --git a/apps/desktop/electron/main/remote/racp-remote-host-client.ts b/apps/desktop/electron/main/remote/racp-remote-host-client.tsindex 42a1dc2f1..37dfcba3c 100644--- a/apps/desktop/electron/main/remote/racp-remote-host-client.ts+++ b/apps/desktop/electron/main/remote/racp-remote-host-client.ts@@ -96,9 +96,23 @@ export type RacpRemoteHostClient = {/** Open the transport and initialize the RACP session. */connect(): Promise<void>;/** Close the transport; safe to call before {@link connect} and after failure. */+ /**+ * Workspace capabilities the live handshake advertised, or `undefined`+ * before `connection/initialize` completes. Callers use the distinction to+ * tell "not known yet" from "this Host does not offer them", which is the+ * same-version mismatch the desktop must realign (ADR 0327).+ */+ workspaceCapabilities?(): RemoteWorkspaceCapabilities | undefined;+ /** Close the transport; safe to call before {@link connect} and after failure. */close(): Promise<void>;};+/** The two additive services a remote workspace install must advertise. */+export type RemoteWorkspaceCapabilities = {+ workspaceTools: boolean;+ workspaceFiles: boolean;+};+/*** The adapter multiplexes {@link RacpClient.onEvent} — a single-slot callback* — into the `subscribe()` API {@link RemoteHostConnection} expects. Fan-out@@ -127,8 +141,16 @@ 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 workspaceCapabilities = (): RemoteWorkspaceCapabilities | undefined => {const capabilities = racp.initialized?.capabilities;+ if (!capabilities) return undefined;+ return {+ workspaceTools: capabilities.workspaceTools === true,+ workspaceFiles: capabilities.workspaceFiles === true,+ };+ };+ const requireWorkspace = (capability?: keyof RemoteWorkspaceCapabilities) => {+ const capabilities = workspaceCapabilities();const supported = capability ? capabilities?.[capability] === true: capabilities?.workspaceTools === true && capabilities?.workspaceFiles === true;if (!supported) {@@ -207,6 +229,7 @@ export function createRacpRemoteHostClient(return {client,state: () => visibleState,+ workspaceCapabilities,async connect() {closed = false;await racp.connect();diff --git a/apps/desktop/electron/main/remote/remote-host-realign.ts b/apps/desktop/electron/main/remote/remote-host-realign.tsnew file mode 100644index 000000000..61c6544cb--- /dev/null+++ b/apps/desktop/electron/main/remote/remote-host-realign.ts@@ -0,0 +1,218 @@+/**+ * Version realignment for paired SSH hosts (spec `02-architecture/05-remote-agent-control.md`+ * §5.2, ADR 0327).+ *+ * A paired Host is pinned to the desktop release that installed it: the bundle+ * carries the desktop's version, is reused only when the release receipt and+ * every installed file still match, and answers the readiness probe with its+ * own version. When the desktop moves ahead — or when the installed bundle+ * predates a capability the desktop now requires, which is a *same*-version+ * mismatch — the Host is refused with `HOST_VERSION_MISMATCH`. Until now that+ * left the user with an "upgrade the remote Host" toast and no way to act on+ * it short of removing and re-adding the host, losing the pairing.+ *+ * This module owns the missing step: re-run the same verified SSH bootstrap+ * with the stored SSH descriptor and the encrypted login password, so the+ * remote machine ends up on the desktop's release and is re-paired in place.+ * The trust anchor is unchanged — the artifact is still fetched on the remote+ * side from the desktop's release tag and verified against the published+ * SHA-256 before it is installed.+ *+ * Automatic attempts are throttled per host and desktop release. The result is+ * persisted as non-secret registry metadata, so an unsuccessful Host is not+ * restarted again on every app launch; failures cool down before retry. A user+ * action that explicitly asks for a reconnect bypasses the throttle.+ */+import type { RemoteHostBootstrapRequest, RemoteHostSshMetadata } from "@pi-desktop/shared";+import { sshMetadataOf } from "./remote-host-metadata.js";+import type { RemoteHostRecord } from "./remote-host-registry.js";+import type { SshBootstrapOutcome } from "./ssh-bootstrap.js";++/**+ * How long a failed automatic attempt suppresses the next one. The desktop+ * release is part of the throttle key, so shipping a new version retries+ * immediately; this window only covers transient failures at the same release.+ */+export const REALIGN_RETRY_AFTER_MS = 10 * 60 * 1000;++/**+ * `attempt` is the only decision that may start remote work. The others are+ * reported so the caller can log *why* nothing happened without inventing a+ * user-visible failure for a state the user cannot act on either.+ */+export type RealignDecision =+ | "attempt"+ | "no-ssh-descriptor"+ | "no-credentials"+ | "aligned"+ | "cooldown";++export type RemoteHostRealignerOptions = {+ /** Desktop release the remote Host must match. */+ version: string;+ /** The verified SSH bootstrap, injected so tests never spawn `ssh`. */+ bootstrap: (+ request: RemoteHostBootstrapRequest,+ options?: { signal?: AbortSignal },+ ) => Promise<SshBootstrapOutcome>;+ /** Persist the re-paired record before the caller reconnects with it. */+ upsert: (record: RemoteHostRecord) => Promise<void>;+ now?: () => number;+ log?: (level: "info" | "warn", message: string, data?: unknown) => void;+};++export type RemoteHostRealignResult = {+ /** The refreshed record: new loopback URL, device token, and SSH descriptor. */+ record: RemoteHostRecord;+ /** Live forward the bootstrap opened; the caller adopts or closes it. */+ outcome: SshBootstrapOutcome;+};++export type RemoteHostRealigner = {+ /** Pure decision; `force` is the user asking for an explicit reconnect. */+ decide(record: RemoteHostRecord, options?: { force?: boolean }): RealignDecision;+ /** `null` means nothing was attempted or the attempt failed; callers then+ * surface the original readiness failure unchanged. */+ realign(+ record: RemoteHostRecord,+ options?: { force?: boolean; signal?: AbortSignal },+ ): Promise<RemoteHostRealignResult | null>;+};++/** Rebuild the request the original pairing used, minus its single-use secret. */+function bootstrapRequestFor(+ record: RemoteHostRecord,+ ssh: RemoteHostSshMetadata,+ password: string | undefined,+): RemoteHostBootstrapRequest {+ return {+ // The pairing identity is reused on purpose: this is the same Host, being+ // brought up to the desktop's release, not a second machine.+ hostKey: record.hostKey,+ label: record.label,+ host: ssh.host,+ ...(ssh.port !== undefined ? { port: ssh.port } : {}),+ ...(ssh.user ? { user: ssh.user } : {}),+ ...(ssh.identityFile ? { identityFile: ssh.identityFile } : {}),+ ...(password ? { password } : {}),+ // A fresh loopback port: the replacement Host is a new process, and pinning+ // the previous port could collide with the predecessor it replaces.+ remotePort: 0,+ };+}++type RealignAttempt = { version: string; at: number; succeeded: boolean };+const REALIGNMENT_METADATA_KEY = "piHostRealignment";++/** Read a bounded, non-secret realignment receipt from the extensible record metadata. */+function persistedAttempt(record: RemoteHostRecord): RealignAttempt | undefined {+ const value = record.metadata?.[REALIGNMENT_METADATA_KEY];+ if (!value || typeof value !== "object") return undefined;+ const candidate = value as Record<string, unknown>;+ if (typeof candidate.version !== "string" || !candidate.version.trim()+ || typeof candidate.at !== "number" || !Number.isFinite(candidate.at)+ || typeof candidate.succeeded !== "boolean") return undefined;+ return { version: candidate.version, at: candidate.at, succeeded: candidate.succeeded };+}++function withPersistedAttempt(record: RemoteHostRecord, attempt: RealignAttempt): RemoteHostRecord {+ return {+ ...record,+ metadata: { ...(record.metadata ?? {}), [REALIGNMENT_METADATA_KEY]: attempt },+ };++}+export function createRemoteHostRealigner(+ options: RemoteHostRealignerOptions,+): RemoteHostRealigner {+ const log = options.log ?? (() => undefined);+ const now = options.now ?? Date.now;+ const attempts = new Map<string, RealignAttempt>();++ const decide = (+ record: RemoteHostRecord,+ { force = false }: { force?: boolean } = {},+ ): RealignDecision => {+ const ssh = sshMetadataOf(record);+ if (!ssh) return "no-ssh-descriptor";+ // A password-authenticated descriptor whose secret is gone cannot be+ // replayed: `BatchMode=yes` would fail later with a worse message than the+ // version mismatch the user is already looking at.+ if (ssh.auth === "password" && !record.sshSecret) return "no-credentials";+ if (force) return "attempt";+ const attempt = attempts.get(record.hostKey) ?? persistedAttempt(record);+ if (!attempt || attempt.version !== options.version) return "attempt";+ if (attempt.succeeded) return "aligned";+ return now() - attempt.at < REALIGN_RETRY_AFTER_MS ? "cooldown" : "attempt";+ };++ return {+ decide,+ async realign(record, { force = false, signal } = {}) {+ if (decide(record, { force }) !== "attempt") return null;+ const ssh = sshMetadataOf(record);+ if (!ssh) return null;+ let outcome: SshBootstrapOutcome | undefined;+ try {+ outcome = await options.bootstrap(+ bootstrapRequestFor(record, ssh, record.sshSecret),+ { ...(signal ? { signal } : {}) },+ );+ const sshSecret = outcome.sshSecret ?? record.sshSecret;+ const success: RealignAttempt = { version: options.version, at: now(), succeeded: true };+ const next: RemoteHostRecord = {+ hostKey: record.hostKey,+ label: record.label,+ url: outcome.url,+ deviceToken: outcome.deviceToken,+ // The password the bootstrap just used stays the stored one. It is+ // only dropped when neither side has one, so a key-authenticated+ // record keeps exactly the shape it had before.+ ...(sshSecret ? { sshSecret } : {}),+ metadata: {+ ...(record.metadata ?? {}),+ transport: "ssh",+ ssh: outcome.ssh,+ [REALIGNMENT_METADATA_KEY]: success,+ },+ };+ await options.upsert(next);+ attempts.set(record.hostKey, success);+ log("info", "remote host realigned to the desktop release", {+ hostKey: record.hostKey,+ version: outcome.ssh.version,+ });+ return { record: next, outcome };+ } catch (error) {+ const failed: RealignAttempt = { version: options.version, at: now(), succeeded: false };+ if (!signal?.aborted) attempts.set(record.hostKey, failed);+ // The re-paired record never reached the caller, so this call still+ // owns the forward the bootstrap opened.+ if (outcome) {+ try {+ await outcome.forward.close();+ } catch (closeError) {+ log("warn", "realignment forward close failed", { error: String(closeError) });+ }+ }+ // Persist the failure throttle across app restarts. A cancelled+ // bootstrap during shutdown is not a failed upgrade attempt.+ if (!signal?.aborted) {+ try {+ await options.upsert(withPersistedAttempt(record, failed));+ } catch (persistError) {+ log("warn", "realignment throttle receipt could not be persisted", {+ hostKey: record.hostKey,+ error: String(persistError),+ });+ }+ }+ log("warn", "remote host realignment failed", {+ hostKey: record.hostKey,+ error: String(error),+ });+ return null;+ }+ },+ };+}diff --git a/apps/desktop/electron/main/remote/remote-host-supervisor.ts b/apps/desktop/electron/main/remote/remote-host-supervisor.tsindex 498234910..de2acbd73 100644--- a/apps/desktop/electron/main/remote/remote-host-supervisor.ts+++ b/apps/desktop/electron/main/remote/remote-host-supervisor.ts@@ -3,6 +3,12 @@ import { REMOTE_DEPLOY_LOCK_SCRIPT } from "./remote-deploy-lock.js";import type { SshTransport } from "./ssh-transport.js";export type RemoteHostSupervisorOptions = {+ /**+ * Release the running Host must report. It is the release this desktop+ * expects — not the version recorded when the host was paired — so a Host+ * left behind by an upgrade is refused here and handed to realignment+ * (ADR 0327).+ */version: string;expectedHostId?: string;readyTimeoutSec?: number;@@ -105,12 +111,14 @@ export function parseRemoteHostReady(stdout: string, options: RemoteHostSupervistypeof 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");- }+ // Identity is a trust boundary and takes precedence: a different Host must+ // never be mistaken for an older release that can be automatically replaced.if (options.expectedHostId !== undefined && hostId !== options.expectedHostId) {throw failure("Remote Host identity changed", "HOST_AUTH_FAILED");}+ if (version.replace(/^v/, "") !== options.version.replace(/^v/, "")) {+ throw failure("the running remote Host does not match the release this Desktop expects", "HOST_VERSION_MISMATCH");+ }return { hostId, host, port, version };}diff --git a/apps/desktop/test/remote-host-realign.test.mjs b/apps/desktop/test/remote-host-realign.test.mjsnew file mode 100644index 000000000..1b5b15885--- /dev/null+++ b/apps/desktop/test/remote-host-realign.test.mjs@@ -0,0 +1,401 @@+import assert from "node:assert/strict";+import test from "node:test";+import { mkdtemp, readFile, rm } from "node:fs/promises";+import { register } from "node:module";+import { tmpdir } from "node:os";+import { dirname, join } from "node:path";+import { fileURLToPath, pathToFileURL } from "node:url";++const here = dirname(fileURLToPath(import.meta.url));+register(pathToFileURL(join(here, "helpers/ts-import-hooks.mjs")));++const { createRemoteHostRealigner, REALIGN_RETRY_AFTER_MS } = await import(+ "../electron/main/remote/remote-host-realign.ts"+);+const { createRemoteHostsBoot } = await import(+ "../electron/main/bootstrap/remote-hosts.ts"+);+const { createSshTunnelManager } = await import(+ "../electron/main/remote/ssh-tunnel.ts"+);+const { createBackendRouter } = await import(+ "../electron/main/remote/backend-router.ts"+);++const DESKTOP_VERSION = "0.18.0";+const OLD_VERSION = "0.17.0";++function reversibleEncryption() {+ return {+ isAvailable: () => true,+ encryptString: (plain) => Buffer.from(`enc:${plain}`),+ decryptString: (buf) => {+ const text = buf.toString("utf8");+ if (!text.startsWith("enc:")) throw new Error("cannot decrypt");+ return text.slice("enc:".length);+ },+ };+}++async function tmpDir() {+ const dir = await mkdtemp(join(tmpdir(), "remote-realign-"));+ return { dir, cleanup: () => rm(dir, { recursive: true, force: true }) };+}++/** A record for a host that was paired over SSH at `version`. */+function sshRecord({ version = OLD_VERSION, sshSecret = "login-secret", auth = "password", ssh: sshOverrides = {} } = {}) {+ // `null` is the explicit "the stored secret is gone" case: an omitted+ // argument keeps the default, so `undefined` cannot express it.+ const storedSecret = sshSecret === null ? undefined : sshSecret;+ return {+ hostKey: "ssh-box",+ label: "Box",+ url: "ws://127.0.0.1:4999/v1/racp/ws",+ deviceToken: "paired-token",+ ...(storedSecret ? { sshSecret: storedSecret } : {}),+ metadata: {+ transport: "ssh",+ ssh: {+ host: "box.local",+ user: "root",+ ...(auth === "password" ? { auth: "password" } : {}),+ remotePort: 4000,+ version,+ hostId: "host-id",+ ...sshOverrides,+ },+ },+ };+}++function readyLine(version, port, hostId = "host-id") {+ return `PI_HOST_READY ${JSON.stringify({ hostId, host: "127.0.0.1", port, version })}`;+}++function fakeAdapter({ capabilities, failConnect } = {}) {+ const listeners = new Set();+ let state = "disconnected";+ const adapter = {+ state: () => state,+ async connect() {+ if (failConnect) throw failConnect;+ state = "connected";+ },+ async close() {+ state = "disconnected";+ listeners.clear();+ },+ client: {+ request: async (method, params) => {+ if (method === "session/list") return { sessions: [] };+ if (method === "events/subscribe") {+ return {+ subscriptionId: `sub-${params.sessionId ?? "host"}`,+ starting: { epoch: "e1", sequence: 1 },+ replayComplete: true,+ };+ }+ return { ok: true };+ },+ subscribe(listener) {+ listeners.add(listener);+ return () => listeners.delete(listener);+ },+ },+ };+ // Only present when a test wants the handshake capabilities observed: the+ // boot layer treats a missing reporter as "not known", never as "missing".+ if (capabilities) adapter.workspaceCapabilities = () => capabilities;+ return adapter;+}++/* ------------------------------------------------------------------ */+/* Decision and record-replacement unit coverage */+/* ------------------------------------------------------------------ */++test("realignment is refused for hosts it cannot replay and throttled per release", () => {+ let now = 1_000;+ const realigner = createRemoteHostRealigner({+ version: DESKTOP_VERSION,+ bootstrap: async () => {+ throw new Error("not used");+ },+ upsert: async () => undefined,+ now: () => now,+ });++ assert.equal(realigner.decide({ hostKey: "direct", label: "D", url: "wss://d", deviceToken: "t" }), "no-ssh-descriptor");+ assert.equal(realigner.decide(sshRecord({ sshSecret: null })), "no-credentials");+ assert.equal(realigner.decide(sshRecord({ auth: "key", sshSecret: null })), "attempt");+ assert.equal(realigner.decide(sshRecord(), { force: true }), "attempt");+ assert.equal(realigner.decide(sshRecord()), "attempt");+});++test("a same-release failure cooldown survives restarts and a new release retries immediately", async () => {+ let now = 5_000;+ const attempts = [];+ let persisted = sshRecord();+ const createRealigner = (version) => createRemoteHostRealigner({+ version,+ bootstrap: async (request) => {+ attempts.push(request);+ throw new Error("release not published yet");+ },+ upsert: async (record) => { persisted = record; },+ now: () => now,+ });++ const realigner = createRealigner(DESKTOP_VERSION);+ assert.equal(await realigner.realign(persisted), null, "a failed attempt resolves to null");+ assert.equal(persisted.metadata.piHostRealignment.succeeded, false);+ assert.equal(realigner.decide(persisted), "cooldown", "the same release must not retry immediately");++ const restarted = createRealigner(DESKTOP_VERSION);+ assert.equal(restarted.decide(persisted), "cooldown", "the persisted failure survives an app restart");+ now += REALIGN_RETRY_AFTER_MS;+ assert.equal(restarted.decide(persisted), "attempt", "a transient failure may be retried later");+ assert.equal(createRealigner("0.19.0").decide(persisted), "attempt", "a new desktop release retries immediately");+ assert.equal(attempts.length, 1);+});++test("a realignment replaces the record with the re-paired host and closes a failed forward", async () => {+ const stored = [];+ const closed = [];+ const remote = { host: "box.local", remotePort: 4100, version: DESKTOP_VERSION, hostId: "new-host", auth: "password", user: "root" };+ const realigner = createRemoteHostRealigner({+ version: DESKTOP_VERSION,+ bootstrap: async (request) => {+ assert.equal(request.hostKey, "ssh-box");+ assert.equal(request.label, "Box");+ assert.equal(request.password, "login-secret", "the stored SSH secret is replayed");+ assert.equal(request.remotePort, 0, "the replacement host picks its own loopback port");+ return {+ hostKey: request.hostKey,+ label: request.label,+ url: "ws://127.0.0.1:5400/v1/racp/ws",+ deviceToken: "fresh-token",+ ssh: remote,+ forward: { localPort: 5400, close: async () => closed.push("forward") },+ steps: [],+ };+ },+ upsert: async (record) => stored.push(record),+ });++ const result = await realigner.realign(sshRecord());+ assert.equal(result.record.url, "ws://127.0.0.1:5400/v1/racp/ws");+ assert.equal(result.record.deviceToken, "fresh-token");+ assert.equal(result.record.sshSecret, "login-secret");+ assert.deepEqual(result.record.metadata.ssh, remote);+ assert.equal(result.record.metadata.transport, "ssh");+ assert.deepEqual(stored, [result.record], "the refreshed record is persisted before the caller reconnects");+ assert.deepEqual(closed, []);+ assert.equal(realigner.decide(sshRecord()), "aligned", "an aligned release is not attempted again");+ assert.equal(result.record.metadata.piHostRealignment.succeeded, true);+ const restarted = createRemoteHostRealigner({+ version: DESKTOP_VERSION,+ bootstrap: async () => { throw new Error("the successful marker must prevent another install"); },+ upsert: async () => undefined,+ });+ assert.equal(restarted.decide(result.record), "aligned", "a successful release marker survives app restart");++ const failing = createRemoteHostRealigner({+ version: DESKTOP_VERSION,+ bootstrap: async () => ({+ hostKey: "ssh-box",+ label: "Box",+ url: "ws://127.0.0.1:5400/v1/racp/ws",+ deviceToken: "fresh-token",+ ssh: remote,+ forward: { localPort: 5400, close: async () => closed.push("orphan") },+ steps: [],+ }),+ upsert: async () => {+ throw new Error("disk full");+ },+ });+ assert.equal(await failing.realign(sshRecord()), null);+ assert.deepEqual(closed, ["orphan"], "a forward the caller never adopts is closed here");+});++/* ------------------------------------------------------------------ */+/* Boot-level: the user path from a stale paired host back to ready */+/* ------------------------------------------------------------------ */++/** Fake SSH side shared by the tunnel probe and the bootstrap script. */+function sshFixture() {+ const state = { remoteVersion: OLD_VERSION, bootstraps: 0, probes: 0, ports: 5400 };+ const tunnels = {+ exec: async () => ({ code: 0, stdout: "Linux\nx86_64\n", stderr: "" }),+ execWithInput: async () => {+ state.probes += 1;+ return { code: 0, stdout: readyLine(state.remoteVersion, 4000), stderr: "" };+ },+ forward: async ({ localPort }) => ({ localPort, close: async () => undefined }),+ dispose: () => undefined,+ };+ const bootstrap = {+ exec: async () => ({ code: 0, stdout: "Linux\nx86_64\n", stderr: "" }),+ execWithInput: async () => {+ state.bootstraps += 1;+ // The verified install lands the desktop's release and restarts the host.+ state.remoteVersion = DESKTOP_VERSION;+ state.ports += 1;+ return {+ code: 0,+ stderr: "",+ stdout: `${readyLine(DESKTOP_VERSION, state.ports)}\nPI_HOST_PAIRING_TOKEN ${JSON.stringify({ token: "ppt1.fixture", expiresAt: 1893456000000 })}`,+ };+ },+ forward: async ({ localPort }) => ({ localPort, close: async () => undefined }),+ dispose: () => undefined,+ };+ return { state, tunnels: () => tunnels, bootstrap: () => bootstrap };+}++function bootFor(dir, fixture, { capabilities, router } = {}) {+ let port = 6100;+ return createRemoteHostsBoot({+ dataDir: dir,+ encryption: reversibleEncryption(),+ router: router ?? createBackendRouter(),+ emit: () => undefined,+ clientInfo: { name: "test", version: DESKTOP_VERSION },+ buildAdapter: () => fakeAdapter({ capabilities }),+ tunnels: createSshTunnelManager({+ reservePort: async () => (port += 1),+ buildTransport: () => fixture.tunnels(),+ }),+ sshBootstrap: {+ buildTransport: () => fixture.bootstrap(),+ fetchChecksum: async () => `${"a".repeat(64)} pi-host-${DESKTOP_VERSION}-linux-x64.tar.gz`,+ reservePort: async () => (port += 1),+ exchangePairing: async () => "realigned-device-token",+ },+ log: () => undefined,+ });+}++test("a host left behind by an upgrade is realigned on connect and re-paired in place", async () => {+ const { dir, cleanup } = await tmpDir();+ const fixture = sshFixture();+ const boot = bootFor(dir, fixture);+ try {+ await boot.registry.upsert(sshRecord());+ const connected = await boot.open();+ assert.equal(connected, 1, "the host is reachable after the automatic realignment");+ assert.equal(fixture.state.bootstraps, 1);+ assert.equal(fixture.state.remoteVersion, DESKTOP_VERSION);++ const [summary] = await boot.list();+ assert.equal(summary.connected, true);+ assert.equal(summary.transport, "ssh");++ // The re-paired credentials and descriptor are the ones now on disk.+ const file = JSON.parse(await readFile(join(dir, "remote-hosts.json"), "utf8"));+ const stored = file.hosts[0];+ assert.equal(stored.metadata.ssh.version, DESKTOP_VERSION);+ assert.equal(stored.metadata.ssh.hostId, "host-id");+ assert.notEqual(stored.url, "ws://127.0.0.1:4999/v1/racp/ws", "the record follows the re-opened forward");++ // A second open reuses the live connection instead of re-provisioning.+ await boot.open();+ assert.equal(fixture.state.bootstraps, 1, "an aligned host is never re-provisioned again");+ } finally {+ await boot.closeAll();+ await cleanup();+ }+});++test("a host that stays unusable after realignment warns once and keeps the mismatch visible", async () => {+ const { dir, cleanup } = await tmpDir();+ const fixture = sshFixture();+ fixture.state.remoteVersion = DESKTOP_VERSION;+ const boot = bootFor(dir, fixture, { capabilities: { workspaceTools: false, workspaceFiles: false } });+ try {+ await boot.registry.upsert(sshRecord({ version: DESKTOP_VERSION }));+ await assert.rejects(boot.ensureReady("ssh-box"), { errorCode: "HOST_VERSION_MISMATCH" });+ assert.equal(fixture.state.bootstraps, 1, "the same-version capability gap is realigned once");+ assert.equal((await boot.list())[0].status, "action-required");++ await assert.rejects(boot.ensureReady("ssh-box"), { errorCode: "HOST_VERSION_MISMATCH" });+ assert.equal(fixture.state.bootstraps, 1, "an aligned release is not re-provisioned on every retry");++ await boot.closeAll();+ const restarted = bootFor(dir, fixture, { capabilities: { workspaceTools: false, workspaceFiles: false } });+ try {+ await assert.rejects(restarted.ensureReady("ssh-box"), { errorCode: "HOST_VERSION_MISMATCH" });+ assert.equal(fixture.state.bootstraps, 1, "the persisted success marker prevents a restart loop");++ // The user asking explicitly still gets a fresh attempt.+ await assert.rejects(restarted.reconnectHost("ssh-box"), { errorCode: "HOST_VERSION_MISMATCH" });+ assert.equal(fixture.state.bootstraps, 2);+ } finally {+ await restarted.closeAll();+ }+ } finally {+ await boot.closeAll();+ await cleanup();+ }+});++test("a password host whose stored secret is gone is never replayed over SSH", async () => {+ const { dir, cleanup } = await tmpDir();+ const fixture = sshFixture();+ fixture.state.remoteVersion = DESKTOP_VERSION;+ const boot = bootFor(dir, fixture, { capabilities: { workspaceTools: false, workspaceFiles: false } });+ try {+ await boot.registry.upsert(sshRecord({ version: DESKTOP_VERSION, sshSecret: null }));+ await assert.rejects(boot.ensureReady("ssh-box"), { errorCode: "HOST_VERSION_MISMATCH" });+ assert.equal(fixture.state.bootstraps, 0, "without the secret there is nothing to replay");+ } finally {+ await boot.closeAll();+ await cleanup();+ }+});++test("realignment leaves a direct-paired host untouched", async () => {+ const { dir, cleanup } = await tmpDir();+ const fixture = sshFixture();+ const failure = Object.assign(new Error("version"), { errorCode: "HOST_VERSION_MISMATCH" });+ const boot = createRemoteHostsBoot({+ dataDir: dir,+ encryption: reversibleEncryption(),+ router: createBackendRouter(),+ emit: () => undefined,+ clientInfo: { name: "test", version: DESKTOP_VERSION },+ buildAdapter: () => fakeAdapter({ failConnect: failure }),+ tunnels: createSshTunnelManager({+ reservePort: async () => 6200,+ buildTransport: () => fixture.tunnels(),+ }),+ sshBootstrap: {+ buildTransport: () => fixture.bootstrap(),+ exchangePairing: async () => "unused",+ },+ log: () => undefined,+ });+ try {+ await boot.registry.upsert({ hostKey: "direct", label: "Direct", url: "wss://direct", deviceToken: "t" });+ await assert.rejects(boot.ensureReady("direct"), { errorCode: "HOST_VERSION_MISMATCH" });+ assert.equal(fixture.state.bootstraps, 0, "a URL-paired host has no SSH descriptor to replay");+ } finally {+ await boot.closeAll();+ await cleanup();+ }+});++test("an unexpected Host identity is never treated as an upgrade mismatch", async () => {+ const { dir, cleanup } = await tmpDir();+ const fixture = sshFixture();+ fixture.state.remoteVersion = OLD_VERSION;+ const boot = bootFor(dir, fixture);+ try {+ await boot.registry.upsert(sshRecord({ ssh: { hostId: "expected-host" } }));+ await assert.rejects(boot.ensureReady("ssh-box"), { errorCode: "HOST_AUTH_FAILED" });+ assert.equal(fixture.state.bootstraps, 0, "a different Host identity must never be re-paired automatically");+ } finally {+ await boot.closeAll();+ await cleanup();+ }+});diff --git a/apps/desktop/test/remote-host-supervisor.test.mjs b/apps/desktop/test/remote-host-supervisor.test.mjsindex d0b4f1b2d..96937175a 100644--- a/apps/desktop/test/remote-host-supervisor.test.mjs+++ b/apps/desktop/test/remote-host-supervisor.test.mjs@@ -24,6 +24,7 @@ test("readiness validates loopback, integral port, identity and version without}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(() => parseRemoteHostReady(line({ ...ready, version: "older" }), { version: VERSION, expectedHostId: "other" }), { errorCode: "HOST_AUTH_FAILED", retriable: false }, "identity mismatch must not authorize automatic upgrade");assert.throws(() => buildRemoteHostSupervisorScript(0));});diff --git a/docs/adr/0327-remote-host-version-realignment.md b/docs/adr/0327-remote-host-version-realignment.mdnew file mode 100644index 000000000..c2d0db528--- /dev/null+++ b/docs/adr/0327-remote-host-version-realignment.md@@ -0,0 +1,111 @@+# ADR 0327: Automatic remote Host version realignment++- Status: Accepted for experimental implementation (amends ADR 0326 item 6: daily startup is still not an installer, but a version mismatch is now repaired instead of only reported)+- Date: 2026-10-12+- Deciders: PI-Desktop maintainers (user-authorized fix for a paired Host that could not be upgraded)+- Related: [ADR 0326](0326-verified-ssh-host-installation.md), [ADR 0292](0292-ssh-remote-host-bootstrap.md), [ADR 0293](0293-ssh-password-authentication.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++A paired Host is pinned to the desktop release that installed it. The bundle is+reused only when its external receipt and every installed file still match, and+the daily readiness probe refuses a Host whose reported version differs from the+one the desktop expects.++Two gaps made that refusal a dead end:++1. The probe compared the running Host against the version **recorded when the+ host was paired**, not against the desktop release. A descriptor written by an+ older desktop made the comparison wrong in both directions: a Host that had+ been upgraded was still refused, and a Host that was behind could pass on a+ stale record until a later capability check failed.+2. Nothing in the product could upgrade a paired Host. The only remedy was to+ remove the host and pair it again, which discards a working SSH descriptor and+ its encrypted credential.++The visible result was a "upgrade the remote Host to a matching Desktop release"+toast with no action behind it — the exact reported failure. A related case+compounds it: an installed bundle can report the *same* version and still predate+an additive capability the desktop now requires (remote workspace tools and+files), because reuse is keyed on the release receipt, not on capabilities. That+mismatch is observable only in the RACP handshake.++## Decision++1. Readiness compares the running Host against the release **this desktop**+ expects, never against the version recorded at pairing time. A saved Host ID+ is validated first: an identity mismatch remains `HOST_AUTH_FAILED` and never+ authorizes automatic realignment. A stale descriptor can no longer mask a+ Host that is behind.+2. After `connection/initialize`, the live handshake capabilities are checked+ once per connection. A Host that advertises no workspace tools/files — or+ reports no capabilities at all and is therefore not knowable — fails closed+ with `HOST_VERSION_MISMATCH`, the same typed failure the UI already explains.+3. On `HOST_VERSION_MISMATCH`, the boot layer re-runs the **same verified SSH+ bootstrap** the pairing path uses, from the stored SSH descriptor and the+ encrypted login password, then adopts the forward it opened and reconnects+ with the refreshed record (new loopback URL, new device token, new Host ID).+ No new trust anchor, download path, or install script is introduced.+4. Automatic attempt receipts are persisted as non-secret Host registry metadata,+ keyed by the desktop release, so an app restart does not reboot a Host again+ after a successful realignment. A failed attempt cools down for ten minutes+ before another automatic try; an explicit user reconnect bypasses the+ throttle. This prevents an unreachable Host or unpublished release from+ repeatedly restarting a remote process on every launch or user action.+5. A Host that cannot be realigned is left alone: a direct URL pairing has no SSH+ descriptor, and a password descriptor whose stored secret is gone is never+ replayed. Both keep the existing mismatch message.+6. A realignment that does not help surfaces the **original** mismatch unchanged,+ and the host stays `action-required`. Automatic repair never hides the reason+ the user sees.+7. Credential, sandbox and ownership boundaries are unchanged: the secret is read+ only from the encrypted record, never returned to the renderer, never logged,+ and the remote artifact is still fetched against the published SHA-256.++## Trust and compatibility++No new trust decision. The desktop still installs only a release artifact that+matches its own version and the published digest, and the remote side still+verifies it before installing. A compromised release publisher or SSH account+remains out of scope, exactly as in ADR 0326.++The visible cost is deliberate: realigning a Host restarts its remote process, so+another client of that Host is briefly disconnected. This occurs only after a+version/capability mismatch, not ordinary connection failures. Once a release is+successfully realigned, its persisted marker prevents further automatic restarts+for that release; an explicit user reconnect remains an opt-in retry.++Record compatibility is additive: the refreshed record keeps its shape, and a+key-authenticated record keeps exactly the fields it had. No database migration,+no RACP protocol change, and no change to direct (non-SSH) pairings is involved.+A Host on a release that has not been published yet still fails and the user still+sees the upgrade message. Persisted receipts suppress restart loops (with a+cooldown after failures), but cannot create a missing release artifact.+Publishing a matching Desktop and Host release is the remaining step, and ADR+0326's note that published tags are immutable stands.++## Alternatives++- Manual "upgrade Host" button only: leaves the reported failure unfixed, because+ the user's next folder selection still fails until they act.+- Compare against the recorded descriptor version (status quo): a stale record+ makes the check wrong in both directions.+- Re-pair on every reconnect: churns credentials and restarts a remote process+ for ordinary connection failures. Realignment is triggered by a version+ mismatch only.+- Trust the version alone and skip the capability check: a same-version bundle+ without workspace services would connect and then fail every `workspace/*`+ call, which is what the user saw.++## Consequences and qualification++A desktop release now drags its paired Hosts forward on first use, without the+user re-adding them. Operators who must pin a Host's release can keep using a+direct URL pairing, which this decision never touches.++Qualification is limited to automated coverage: the boot-level tests in+`apps/desktop/test/remote-host-realign.test.mjs` exercise the decision table, the+record replacement, the failed-forward cleanup and the full stale-host path with+injected SSH transports. A real Linux SSH host is required for acceptance, and+the scenario is recorded in E2E-REMOTE-SSH-OPTIMIZATION; a macOS development host+cannot qualify it.diff --git a/docs/adr/README.md b/docs/adr/README.mdindex ec7cd19b6..9f7da18d9 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -372,6 +372,7 @@ Each ADR includes:| 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) |+| 0327 | [Automatic remote Host version realignment](0327-remote-host-version-realignment.md) | Accepted for experimental implementation (amends ADR 0326 item 6; Linux SSH qualification 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/spec/02-architecture/05-remote-agent-control.md b/docs/spec/02-architecture/05-remote-agent-control.mdindex 71dc21a82..ea4e58f0c 100644--- a/docs/spec/02-architecture/05-remote-agent-control.md+++ b/docs/spec/02-architecture/05-remote-agent-control.md@@ -186,6 +186,20 @@ descriptors without a Host ID remain readable. Disconnect does not kill a Hostthat other clients may use. Readiness is used for offline browse/files/shelldiscovery; tool execution itself never reconnects and replays a failed call.+**Version realignment.** A paired Host is pinned to the release that installed+it, so a desktop upgrade leaves it behind. Readiness therefore compares the+running Host against *this desktop's* release — never against the version+recorded at pairing time — and the RACP handshake is checked for the additive+workspace services a remote project needs. On a mismatch the desktop re-runs the+same verified SSH install from the stored SSH descriptor and the encrypted login+password, adopts the forward it opened, and re-pairs in place (ADR 0327).+Automatic attempts are limited to one per release per host with a cooldown after+a failure, an explicit user reconnect may retry, and a realignment that does not+help surfaces the original mismatch instead of hiding it. A direct URL pairing,+and a password descriptor whose stored secret is gone, are never touched, and the+artifact is still fetched from the desktop's release and verified against the+published SHA-256 before installation.+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 forwardsdiff --git a/docs/spec/05-security/02-remote-control-security.md b/docs/spec/05-security/02-remote-control-security.mdindex c4e07b313..fb83d0c0e 100644--- a/docs/spec/05-security/02-remote-control-security.md+++ b/docs/spec/05-security/02-remote-control-security.md@@ -165,9 +165,19 @@ pairing only binds a desktop device to the Host it started.digest plus read-only file verification; version equality alone is insufficient.System Node and remote GitHub access are not required for new bundles, butsupported 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.+- Daily readiness MUST NOT reinstall, re-pair or reset credentials — unless the+ running Host cannot serve this desktop release at all, which triggers the+ version realignment below. Validate loopback readiness/version and saved Host+ ID before forwarding, then validate the RACP identity. A legacy descriptor+ without Host ID remains readable.+- One version realignment per desktop release per host MAY re-run that same+ verified bootstrap from the stored SSH descriptor and the encrypted login+ password ([ADR 0327](../../adr/0327-remote-host-version-realignment.md)). The+ secret is read only from the encrypted record, is never returned to the+ renderer and never logged, a password host whose stored secret is gone is never+ replayed, a failed attempt waits out a cooldown before the next automatic try,+ and an explicit user reconnect may retry immediately. The artifact trust path+ is unchanged: same release, same published SHA-256, same remote verification.- 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,diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex c8d903125..49dd42b47 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -14699,6 +14699,9 @@ browser milestones are scheduled.`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.+ Repoint the fixture release so the paired Host no longer matches the desktop,+ then select a remote folder and verify the Host is realigned over the same+ verified install, re-paired in place and connected without removing it.- **Expected**: Bundled Node starts the Host without a system Node or remoterelease access. Reuse validates the external release receipt and installedmanifest; failed staging leaves the previous `current` intact. Daily readiness@@ -14707,8 +14710,13 @@ browser milestones are scheduled.automatic retry. Local model requests, API keys, sessions and permissions staylocal; workspace tools/files and root-only repository instructions come fromthe 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,+ `REMOTE_MUTATION_OUTCOME_UNKNOWN` and is not replayed or executed locally. A+ Host that falls behind the desktop release is realigned over the same verified+ install and re-paired in place — once per release per host, and again on an+ explicit user reconnect — while a Host that still cannot serve this desktop+ keeps the upgrade message instead of looping or dropping the pairing.+- **Automation**: `remote-host-realign.test.mjs`,+ `remote-host-supervisor.test.mjs`, SSH bootstrap shell,packaging, artifact transfer, concurrent readiness/auth lifecycle and UIcontract suites; `PI_HOST_CORE_BINARY=<candidate binary> nodescripts/e2e-local-agent-remote-tools.mjs` covers local model/instructionsdiff --git a/docs/zh-CN/spec/02-architecture/05-remote-agent-control.md b/docs/zh-CN/spec/02-architecture/05-remote-agent-control.mdindex 98f5c5e58..9b6c6b9f9 100644--- a/docs/zh-CN/spec/02-architecture/05-remote-agent-control.md+++ b/docs/zh-CN/spec/02-architecture/05-remote-agent-control.md@@ -84,6 +84,9 @@ provider 配置由引导步骤经 SSH 通道写入,是 Host 本地配置,绝Host 只绑定 loopback;只有绑定地址与对端地址都是 loopback且出示有效设备 token时才接受明文 `ws://`,因为 SSH 通道已提供机密性,SSH 登录也已证明对该机器的shell 访问。非 loopback 绑定仍要求 TLS 与设备 token。首版无法引导没有 GitHub 出网能力的机器。+已配对 Host 的版本落后于桌面时,桌面会复用同一套经校验的 SSH 引导把它升级到桌面版本,并在原处重新配对(ADR 0327);+就绪检查比对的是桌面期望的版本,而不是配对时记录的版本,连接后还会核对远端是否提供远程工作区所需的服务。+自动升级每个桌面版本每台 Host 只尝试一次,失败后冷却,用户手动重连可再试,升级无效时仍显示原来的升级提示。### 4.3 自托管 Gateway(不排期)diff --git a/packages/shared/src/changelog-de.ts b/packages/shared/src/changelog-de.tsindex 14a32ed63..063b75724 100644--- a/packages/shared/src/changelog-de.ts+++ b/packages/shared/src/changelog-de.ts@@ -18,6 +18,7 @@ export const deEntries: ChangelogEntry[] = ["Plugins können Netzwerkweiterleitungen prüfen oder ablehnen; bestehende Fetch-Aufrufe folgen Weiterleitungen weiterhin standardmäßig.","Stoppen Sie einen laufenden Unteragenten direkt über seine Karte oder Detailansicht oder alle Unteragenten der aktuellen Sitzung, ohne den Hauptagenten zu stoppen.","Sehen Sie die gesamte Sitzungsdauer, die kumulierte Modellantwortzeit und deren Anteil an der Sitzung im Kontextverbrauchsfenster.",+ "Ein gekoppelter entfernter Host, der hinter der Desktop-Version zurückbleibt, aktualisiert sich jetzt über dieselbe verifizierte SSH-Installation und wird an Ort und Stelle neu gekoppelt, statt Sie nur zum Aktualisieren aufzufordern.",],},{diff --git a/packages/shared/src/changelog-en.ts b/packages/shared/src/changelog-en.tsindex ae882ff57..f52eb8ee5 100644--- a/packages/shared/src/changelog-en.ts+++ b/packages/shared/src/changelog-en.ts@@ -18,6 +18,7 @@ export const enEntries: ChangelogEntry[] = ["Plugins can inspect or refuse network redirects; existing fetch calls still follow redirects by default.","Stop a running subagent directly from its card or detail panel, or stop all subagents in the current session without stopping the coordinator.","See total session time beside cumulative model response time and its share of the session.",+ "A paired remote Host that falls behind the desktop release now upgrades itself through the same verified SSH install and re-pairs in place, instead of only asking you to upgrade it.",],},{diff --git a/packages/shared/src/changelog-es.ts b/packages/shared/src/changelog-es.tsindex 75f4fb845..7c33aa0fb 100644--- a/packages/shared/src/changelog-es.ts+++ b/packages/shared/src/changelog-es.ts@@ -18,6 +18,7 @@ export const esEntries: ChangelogEntry[] = ["Los plugins pueden inspeccionar o rechazar redirecciones de red; las llamadas fetch existentes siguen las redirecciones de forma predeterminada.","Detén un subagente en ejecución desde su tarjeta o panel de detalles, o todos los de la sesión actual, sin detener al coordinador.","Consulta la duración total de la sesión, el tiempo acumulado de respuesta del modelo y su proporción en el panel de uso del contexto.",+ "Un Host remoto emparejado que se queda atrás respecto a la versión de escritorio ahora se actualiza mediante la misma instalación SSH verificada y se vuelve a emparejar en el mismo lugar, en lugar de solo pedirle que lo actualice.",],},{diff --git a/packages/shared/src/changelog-fr.ts b/packages/shared/src/changelog-fr.tsindex 2081ffabf..a7f3d1006 100644--- a/packages/shared/src/changelog-fr.ts+++ b/packages/shared/src/changelog-fr.ts@@ -18,6 +18,7 @@ export const frEntries: ChangelogEntry[] = ["Les plugins peuvent inspecter ou refuser les redirections réseau ; les appels fetch existants continuent de les suivre par défaut.","Arrêtez un sous-agent en cours depuis sa carte ou ses détails, ou tous ceux de la session en cours, sans arrêter le coordinateur.","Consultez la durée totale de la session, le temps de réponse cumulé du modèle et sa part dans le panneau d'utilisation du contexte.",+ "Un Host distant appairé qui reste en retard sur la version du bureau se met désormais à niveau via la même installation SSH vérifiée et se réappaire sur place, au lieu de simplement vous demander de le mettre à jour.",],},{diff --git a/packages/shared/src/changelog-ko.ts b/packages/shared/src/changelog-ko.tsindex 64559bf0e..77e6a67c4 100644--- a/packages/shared/src/changelog-ko.ts+++ b/packages/shared/src/changelog-ko.ts@@ -18,6 +18,7 @@ export const koEntries: ChangelogEntry[] = ["플러그인은 네트워크 리디렉션을 검사하거나 거부할 수 있으며, 기존 fetch 호출은 기본적으로 계속 리디렉션을 따릅니다.","카드나 상세 패널에서 실행 중인 하위 에이전트를 개별적으로 또는 현재 세션의 모든 하위 에이전트를 중지해도 주 에이전트는 계속 실행됩니다.","컨텍스트 사용량 패널에서 총 세션 시간, 누적 모델 응답 시간과 세션 내 비율을 확인하세요.",+ "데스크톱 버전보다 뒤처진 페어링된 원격 Host가 이제 동일한 검증된 SSH 설치로 스스로 업그레이드하고 그 자리에서 다시 페어링됩니다.",],},{diff --git a/packages/shared/src/changelog-pt-BR.ts b/packages/shared/src/changelog-pt-BR.tsindex 4a59ca0f4..64b1c63b5 100644--- a/packages/shared/src/changelog-pt-BR.ts+++ b/packages/shared/src/changelog-pt-BR.ts@@ -18,6 +18,7 @@ export const ptBREntries: ChangelogEntry[] = ["Plugins podem inspecionar ou recusar redirecionamentos de rede; chamadas fetch existentes continuam seguindo redirecionamentos por padrão.","Pare um subagente em execução pelo cartão ou painel de detalhes, ou todos os subagentes da sessão atual, sem parar o coordenador.","Veja o tempo total da sessão, o tempo acumulado de resposta do modelo e sua proporção no painel de uso de contexto.",+ "Um Host remoto emparelhado que fica atrás da versão do desktop agora se atualiza pela mesma instalação SSH verificada e se emparelha novamente no mesmo lugar, em vez de apenas pedir que você o atualize.",],},{diff --git a/packages/shared/src/changelog-tr.ts b/packages/shared/src/changelog-tr.tsindex 267f69c22..bd8b4cdf5 100644--- a/packages/shared/src/changelog-tr.ts+++ b/packages/shared/src/changelog-tr.ts@@ -18,6 +18,7 @@ export const trEntries: ChangelogEntry[] = ["Eklentiler ağ yönlendirmelerini inceleyebilir veya reddedebilir; mevcut fetch çağrıları varsayılan olarak yönlendirmeleri izlemeyi sürdürür.","Çalışan bir alt ajanı kartından veya ayrıntı panelinden ya da geçerli oturumdaki tüm alt ajanları koordinatörü durdurmadan durdurabilirsiniz.","Bağlam kullanımı panelinde toplam oturum süresini, birikimli model yanıt süresini ve oturum içindeki payını görün.",+ "Masaüstü sürümünün gerisinde kalan eşleştirilmiş bir uzak Host artık aynı doğrulanmış SSH kurulumuyla kendini günceller ve yerinde yeniden eşleştirilir.",],},{diff --git a/packages/shared/src/changelog-zh-CN.ts b/packages/shared/src/changelog-zh-CN.tsindex 45eaea186..22a7004fc 100644--- a/packages/shared/src/changelog-zh-CN.ts+++ b/packages/shared/src/changelog-zh-CN.ts@@ -18,6 +18,7 @@ export const zhCNEntries: ChangelogEntry[] = ["插件可查询支持的重定向模式,并选择检查或拒绝网络重定向;现有请求默认仍会跟随重定向。","可从卡片或详情停止正在运行的子智能体,也可停止当前会话中的全部子智能体,主智能体会继续运行。","在上下文用量面板查看会话总耗时、模型响应累计耗时及其占比。",+ "与桌面版本不一致的远程 Host 现在会通过同样经过校验的 SSH 安装自动升级,并在原处重新配对,而不再只是提示你升级。",],},{diff --git a/packages/shared/src/changelog-zh-TW.ts b/packages/shared/src/changelog-zh-TW.tsindex 3427a4feb..838ce5436 100644--- a/packages/shared/src/changelog-zh-TW.ts+++ b/packages/shared/src/changelog-zh-TW.ts@@ -18,6 +18,7 @@ export const zhTWEntries: ChangelogEntry[] = ["外掛可查詢支援的重新導向模式,並選擇檢查或拒絕網路重新導向;現有請求預設仍會跟隨重新導向。","可從卡片或詳情停止執行中的子智能體,也可停止目前工作階段的全部子智能體,主智能體會繼續執行。","在上下文用量面板查看工作階段總耗時、模型回應累計耗時及其占比。",+ "與桌面版本不一致的遠端 Host 現在會透過同樣經過驗證的 SSH 安裝自動升級,並在原處重新配對,而不再只是提示你升級。",],},{