diff --git a/crates/ide-core/src/event.rs b/crates/ide-core/src/event.rs index 976a018a1..684861632 100644 --- a/crates/ide-core/src/event.rs +++ b/crates/ide-core/src/event.rs @@ -38,6 +38,11 @@ pub enum IdeEvent { WindowGroupsChanged, /// A window entered or left full screen, itself or as a member of a full-screen window group. WindowFullscreenChanged, + /// This remote window's connection to its host ended on its own (network loss, the host or + /// its server went away); the window's project is unreachable until it reconnects. + RemoteConnectionLost { + host: String, + }, ProjectTrustChanged { root: crate::IpcPath, trusted: bool, diff --git a/crates/ide-host/src/rpc.rs b/crates/ide-host/src/rpc.rs index b1e9e17e9..3d4c2858c 100644 --- a/crates/ide-host/src/rpc.rs +++ b/crates/ide-host/src/rpc.rs @@ -309,13 +309,14 @@ pub fn event_sink(peer: Arc>, window: Option) -> ide_core /// Whether a desktop shows an `event` notification of its server in the window. A server reports /// on its project; what this machine answers or owns itself (MCP approvals, app updates, window -/// groups) never comes from it. +/// groups, its own connection to the server) never comes from it. pub fn client_accepts(event: &IdeEvent) -> bool { match event { IdeEvent::McpRequest { .. } | IdeEvent::McpRequestClosed { .. } | IdeEvent::WindowGroupsChanged | IdeEvent::WindowFullscreenChanged + | IdeEvent::RemoteConnectionLost { .. } | IdeEvent::UpdateStatusChanged { .. } | IdeEvent::UpdateAvailable { .. } => false, IdeEvent::DbSourcesChanged diff --git a/src-tauri/src/remote_dev.rs b/src-tauri/src/remote_dev.rs index 3a7f40234..cf75c6088 100644 --- a/src-tauri/src/remote_dev.rs +++ b/src-tauri/src/remote_dev.rs @@ -603,11 +603,19 @@ pub async fn remote_connect( let peer = connection.peer.clone(); let auth_plugins = state.plugins.clone(); let auth_window = label.clone(); + let app = window.app_handle().clone(); tauri::async_runtime::spawn(async move { peer.closed().await; auth_plugins.forget_remote_loopbacks(&auth_window); - if let Some(connection) = weak.upgrade() { - connection.forwards.lock().clear(); + let Some(connection) = weak.upgrade() else { return }; + connection.forwards.lock().clear(); + // Still the window's connection: not a disconnect or a replacement, so the window learns + // its project is unreachable instead of failing every command with "connection closed". + let current = app.state::().remote_dev.get(&auth_window); + if current.is_some_and(|c| Arc::ptr_eq(&c, &connection)) { + tracing::warn!("{}: the connection to openidea-server was lost", connection.host); + TauriSink { app, window: Some(auth_window) } + .emit(ide_core::IdeEvent::RemoteConnectionLost { host: connection.host.clone() }); } }); let plugins = state.plugins.clone(); @@ -957,7 +965,7 @@ pub async fn remote_invoke( let call = Invoke { window: label, cmd, args }; let mut result = invoke_reply(&c.peer, call, std::time::Duration::from_secs(30)) .await - .map_err(|e| older_server_error(e, &c.server_version, &c.host))?; + .map_err(|e| lost_connection_error(older_server_error(e, &c.server_version, &c.host), &c))?; if web_url && let Some(url) = result.as_str() { result = Value::String(forward_web_url(&c, url).await?); } @@ -1018,6 +1026,12 @@ fn older_server_error(e: IdeError, server_version: &str, host: &str) -> IdeError )) } +/// A request that failed because the transport is gone says so, instead of the bare JSON-RPC +/// "connection closed". +fn lost_connection_error(e: IdeError, c: &Connection) -> IdeError { + if c.peer.is_closed() { IdeError::unavailable(format!("Lost the connection to {}", c.host)) } else { e } +} + // Conversation reads are snapshots; a silent host must not leave them pending forever. async fn invoke_reply(peer: &Peer, call: Invoke, entries_timeout: std::time::Duration) -> IdeResult { let reply = peer.request("invoke", &call, None); diff --git a/src/bindings.ts b/src/bindings.ts index ce9903daf..69c737b74 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -6381,7 +6381,12 @@ export type IdeEvent = /** Project window membership or selection changed. */ { type: "windowGroupsChanged" } | /** A window entered or left full screen, itself or as a member of a full-screen window group. */ -{ type: "windowFullscreenChanged" } | { type: "projectTrustChanged"; root: IpcPath; trusted: boolean } | +{ type: "windowFullscreenChanged" } | +/** + * This remote window's connection to its host ended on its own (network loss, the host or + * its server went away); the window's project is unreachable until it reconnects. + */ +{ type: "remoteConnectionLost"; host: string } | { type: "projectTrustChanged"; root: IpcPath; trusted: boolean } | /** Files or directories changed on disk (after debouncing, ignore rules applied). */ { type: "fsChanged"; created: IpcPath[]; modified: IpcPath[]; removed: IpcPath[]; /** Subtrees whose ignore rules changed, after the matchers were rebuilt. */ diff --git a/src/features/remote-dev/RemoteDev.module.css b/src/features/remote-dev/RemoteDev.module.css index c8122c9cd..623f4d498 100644 --- a/src/features/remote-dev/RemoteDev.module.css +++ b/src/features/remote-dev/RemoteDev.module.css @@ -72,3 +72,8 @@ margin-left: auto; font-variant-numeric: tabular-nums; } +.lost { + display: inline-flex; + align-items: center; + gap: var(--space-1); +} diff --git a/src/features/remote-dev/RemoteStatus.tsx b/src/features/remote-dev/RemoteStatus.tsx index 421429721..55cc10817 100644 --- a/src/features/remote-dev/RemoteStatus.tsx +++ b/src/features/remote-dev/RemoteStatus.tsx @@ -2,7 +2,8 @@ import { executeAction } from "@/platform/actions"; import { tx } from "@/platform/i18n"; import type { RemoteSession } from "@/platform/ipc"; import { useRemote } from "@/platform/remote"; -import { BarButton } from "@/ui"; +import { BarButton, Icon, Spinner } from "@/ui"; +import styles from "./RemoteDev.module.css"; const BADGE: Record = { ssh: "SSH", @@ -17,8 +18,28 @@ export function remoteBadge(session: Pick): st export function RemoteStatus() { const session = useRemote((s) => s.session); + const lost = useRemote((s) => s.lost !== null); + const reconnecting = useRemote((s) => s.reconnecting); if (!session) return null; const label = remoteBadge(session); + if (lost) + return ( + void executeAction("remote.reconnect")} + > + + {reconnecting ? : } + {label} + + + ); return ( void { @@ -54,6 +55,7 @@ function trackPortsWindow(): () => void { export function activate(): () => void { const disposers = [ trackPortsWindow(), + installReconnect(), registerOverlay({ id: "remote.connect", component: ConnectHost }), registerStatusItem({ id: "remote.location", @@ -72,6 +74,15 @@ export function activate(): () => void { keywords: ["ssh", "remote", "server", "gateway", "connect", "host"], run: () => openConnectDialog(), }, + { + id: "remote.reconnect", + title: "Reconnect to Remote Host", + description: "Connects this window to its remote project again after the connection was lost.", + category: "File", + keywords: ["ssh", "remote", "reconnect", "connection", "lost"], + when: "remoteConnectionLost", + run: () => reconnectNow(), + }, { id: "remote.disconnect", title: "Disconnect from Remote Host", diff --git a/src/features/remote-dev/reconnect.test.ts b/src/features/remote-dev/reconnect.test.ts new file mode 100644 index 000000000..fbafa5246 --- /dev/null +++ b/src/features/remote-dev/reconnect.test.ts @@ -0,0 +1,106 @@ +import { afterEach, beforeEach, expect, it, vi } from "vitest"; +import type { RemoteSession } from "@/platform/ipc"; + +const listeners = vi.hoisted(() => new Map void>()); +const reconnectRemote = vi.hoisted(() => vi.fn<() => Promise>()); +const notify = vi.hoisted(() => vi.fn()); +const dirty = vi.hoisted(() => ({ ids: [] as number[] })); +const confirm = vi.hoisted(() => vi.fn(async () => true)); + +vi.mock("@/platform/ipc", async (orig) => ({ + ...(await orig()), + onIdeEvent: (type: string, handler: (event: { host: string }) => void) => { + listeners.set(type, handler); + return () => listeners.delete(type); + }, +})); +vi.mock("@/platform/remote", async (orig) => ({ + ...(await orig()), + reconnectRemote, +})); +vi.mock("@/workbench/contributions", async (orig) => ({ + ...(await orig()), + notifications: () => ({ notify, expire: vi.fn() }), + maybeEditorService: () => ({ dirtyDocumentIds: () => dirty.ids }), +})); +vi.mock("@/workbench/messages", () => ({ confirm })); + +import { getContext } from "@/platform/context"; +import { useRemote } from "@/platform/remote"; +import { installReconnect, reconnectNow, RETRY_DELAYS_MS } from "./reconnect"; + +const session: RemoteSession = { + target: { kind: "ssh", config: "box" }, + root: "/srv/app", + host: "box", + os: "linux", + commands: [], +}; + +let waits: number[]; +let uninstall: () => void; + +beforeEach(() => { + waits = []; + dirty.ids = []; + useRemote.setState({ session, lost: null, reconnecting: false }); + uninstall = installReconnect(async (ms) => { + waits.push(ms); + }); +}); + +afterEach(() => { + uninstall(); + vi.clearAllMocks(); +}); + +const lose = () => listeners.get("remoteConnectionLost")!({ host: "box" }); +const settle = () => new Promise((resolve) => setTimeout(resolve, 0)); + +it("marks the window lost and reconnects in the background", async () => { + reconnectRemote.mockRejectedValueOnce(new Error("Network is unreachable")).mockResolvedValueOnce(); + lose(); + expect(useRemote.getState().lost).toBe("box"); + expect(getContext().remoteConnectionLost).toBe(true); + await settle(); + expect(waits).toEqual(RETRY_DELAYS_MS.slice(0, 2)); + expect(reconnectRemote).toHaveBeenCalledTimes(2); + expect(notify).not.toHaveBeenCalled(); +}); + +it("offers Reconnect once every attempt failed", async () => { + reconnectRemote.mockRejectedValue(new Error("Connection refused")); + lose(); + await settle(); + expect(reconnectRemote).toHaveBeenCalledTimes(RETRY_DELAYS_MS.length); + expect(notify).toHaveBeenCalledOnce(); + const n = notify.mock.calls[0]![0]; + expect(n).toMatchObject({ level: "error", title: "Lost the connection to box", body: "Connection refused" }); + + reconnectRemote.mockResolvedValueOnce(); + n.actions[0].run(); + await settle(); + expect(reconnectRemote).toHaveBeenCalledTimes(RETRY_DELAYS_MS.length + 1); + expect(confirm).not.toHaveBeenCalled(); +}); + +it("leaves the reload to the user while edits are unsaved, and asks first", async () => { + dirty.ids = [3, 4]; + lose(); + await settle(); + expect(reconnectRemote).not.toHaveBeenCalled(); + expect(notify).toHaveBeenCalledWith(expect.objectContaining({ title: "Lost the connection to box" })); + + confirm.mockResolvedValueOnce(false); + await reconnectNow(); + expect(confirm).toHaveBeenCalledOnce(); + expect(reconnectRemote).not.toHaveBeenCalled(); +}); + +it("ignores a lost connection of a window that is no longer remote", async () => { + useRemote.setState({ session: null }); + lose(); + await settle(); + expect(useRemote.getState().lost).toBeNull(); + expect(reconnectRemote).not.toHaveBeenCalled(); +}); diff --git a/src/features/remote-dev/reconnect.ts b/src/features/remote-dev/reconnect.ts new file mode 100644 index 000000000..3789dd811 --- /dev/null +++ b/src/features/remote-dev/reconnect.ts @@ -0,0 +1,89 @@ +/** + * A remote window whose connection ends on its own (network loss, sleep, the host or its server + * went away): marks it lost, reconnects a few times in the background, then offers Reconnect. + */ +import { onIdeEvent } from "@/platform/ipc"; +import { setContext } from "@/platform/context"; +import { tx } from "@/platform/i18n"; +import { reconnectRemote, useRemote } from "@/platform/remote"; +import { maybeEditorService, notifications } from "@/workbench/contributions"; +import { confirm } from "@/workbench/messages"; + +/** Waits before each automatic attempt, as VS Code Remote and Gateway retry with back-off. */ +export const RETRY_DELAYS_MS = [2_000, 5_000, 15_000]; +const KEY = "remote.connection"; + +let generation = 0; + +const errorText = (e: unknown) => (e instanceof Error ? e.message : String(e)); +const unsaved = () => maybeEditorService()?.dirtyDocumentIds?.().length ?? 0; + +function notifyLost(host: string, error?: unknown) { + notifications().notify({ + key: KEY, + group: "remote", + level: "error", + title: tx`Lost the connection to ${host}`, + body: error === undefined ? undefined : errorText(error), + actions: [{ label: tx("Reconnect"), run: () => void reconnectNow() }], + }); +} + +/** Reconnect to Remote Host: asks first when reopening the project would drop unsaved edits. */ +export async function reconnectNow(): Promise { + const { lost, reconnecting } = useRemote.getState(); + if (!lost || reconnecting) return; + const count = unsaved(); + if ( + count > 0 && + !(await confirm({ + title: tx("Reconnect to Remote Host"), + message: tx`Reconnecting opens the project again. Unsaved changes in ${count} files can't be saved to ${lost} and will be lost.`, + ok: tx("Reconnect"), + icon: "warning", + })) + ) + return; + generation++; + notifications().expire?.(KEY); + try { + await reconnectRemote(); + } catch (e) { + notifyLost(lost, e); + } +} + +async function retry(host: string, run: number, wait: (ms: number) => Promise) { + // Reopening the project would drop edits that can no longer be saved: leave that to the user. + if (unsaved() > 0) return notifyLost(host); + let last: unknown; + for (const ms of RETRY_DELAYS_MS) { + await wait(ms); + if (run !== generation || useRemote.getState().lost !== host) return; + try { + await reconnectRemote(); + return; + } catch (e) { + last = e; + } + } + if (run === generation) notifyLost(host, last); +} + +export function installReconnect( + wait: (ms: number) => Promise = (ms) => new Promise((resolve) => setTimeout(resolve, ms)), +): () => void { + const offEvent = onIdeEvent("remoteConnectionLost", (e) => { + if (!useRemote.getState().session) return; + useRemote.setState({ lost: e.host }); + void retry(e.host, ++generation, wait); + }); + const offState = useRemote.subscribe((s, prev) => { + if (s.lost !== prev.lost) setContext("remoteConnectionLost", s.lost !== null); + }); + return () => { + generation++; + offEvent(); + offState(); + }; +} diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index fe612c5fb..36a45e297 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -2147,5 +2147,13 @@ "Body line {0} is longer than {1} characters": "Body line {0} is longer than {1} characters", "Add blank line": "Add blank line", "Cannot paste this path safely: its name contains control characters.": "Cannot paste this path safely: its name contains control characters.", - "Cannot paste the dropped files": "Cannot paste the dropped files" + "Cannot paste the dropped files": "Cannot paste the dropped files", + "Lost the connection to {host}": "Lost the connection to {host}", + "Reconnect": "Reconnect", + "Reconnect to Remote Host": "Reconnect to Remote Host", + "Connects this window to its remote project again after the connection was lost.": "Connects this window to its remote project again after the connection was lost.", + "Reconnecting opens the project again. Unsaved changes in {count} files can't be saved to {host} and will be lost.": "Reconnecting opens the project again. Unsaved changes in {count} files can't be saved to {host} and will be lost.", + "Reconnecting to {host}…": "Reconnecting to {host}…", + "Lost the connection to {host}. Click to reconnect.": "Lost the connection to {host}. Click to reconnect.", + "{label} (disconnected)": "{label} (disconnected)" } diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index 9418a61b2..b1c37a520 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -8534,5 +8534,13 @@ "Don't Add the Current File": "不附带当前文件", "Add {rel} and the selection to your requests": "在请求中附带 {rel} 和选区", "Cannot paste this path safely: its name contains control characters.": "无法安全粘贴此路径:名称包含控制字符。", - "Cannot paste the dropped files": "无法粘贴拖入的文件" + "Cannot paste the dropped files": "无法粘贴拖入的文件", + "Lost the connection to {host}": "与 {host} 的连接已断开", + "Reconnect": "重新连接", + "Reconnect to Remote Host": "重新连接远程主机", + "Connects this window to its remote project again after the connection was lost.": "连接断开后,让此窗口重新连接到其远程项目。", + "Reconnecting opens the project again. Unsaved changes in {count} files can't be saved to {host} and will be lost.": "重新连接会重新打开项目。{count} 个文件中未保存的更改无法保存到 {host},将会丢失。", + "Reconnecting to {host}…": "正在重新连接到 {host}…", + "Lost the connection to {host}. Click to reconnect.": "与 {host} 的连接已断开。点击重新连接。", + "{label} (disconnected)": "{label}(已断开)" } diff --git a/src/platform/remote.ts b/src/platform/remote.ts index b7032424d..f635bd40b 100644 --- a/src/platform/remote.ts +++ b/src/platform/remote.ts @@ -15,6 +15,7 @@ import { isTauri, type ChannelFrame, type RemoteProgress, + type RemoteProject, type RemoteSession, type RemoteTarget, } from "./ipc"; @@ -25,9 +26,13 @@ import { useProject } from "./project"; interface RemoteState { session: RemoteSession | null; + /** The host the connection was lost to (the window's project is unreachable), else null. */ + lost: string | null; + /** A reconnection to the lost host is in progress. */ + reconnecting: boolean; } -export const useRemote = create(() => ({ session: null })); +export const useRemote = create(() => ({ session: null, lost: null, reconnecting: false })); let routed = new Set(); let nextChannel = 1; @@ -124,14 +129,14 @@ const route: InvokeRoute = (cmd, args, options) => { */ export function enableRemote(session: RemoteSession) { routed = new Set(session.commands); - useRemote.setState({ session }); + useRemote.setState({ session, lost: null, reconnecting: false }); setInvokeRoute(route); } export function disableRemote() { routed = new Set(); setInvokeRoute(null); - useRemote.setState({ session: null }); + useRemote.setState({ session: null, lost: null, reconnecting: false }); } export function isRemoteWindow(): boolean { @@ -162,6 +167,34 @@ export const useRemoteProgress = create<{ progress: RemoteProgress | null; locat location: null, })); +/** Routes this window to the server `remoteConnect` answered with and shows its project. */ +async function attachRemote(r: RemoteProject, path: string): Promise { + enableRemote({ target: r.target, root: r.root, host: r.host, os: r.os, commands: r.commands }); + if (takeLegacyRemoteTrust(r.target, path, r.host)) { + const status = await call(commands.projectTrustStatus(r.root)); + if (!status.decided) await call(commands.projectTrustSet(r.root, true, false)); + if (!(await call(commands.remoteTrustStatus())).decided) await call(commands.remoteTrustSet(true)); + } + try { + await confirmProjectTrust(r.root); + } catch (error) { + await commands.closeProject(); + disableRemote(); + throw error; + } + const current = await commands.projectCurrent(); + if (current) r.project = current; + r.project.settings = await clientSettings(r.project.settings); + useProject.setState({ project: r.project, settings: r.project.settings }); + rememberRemote({ + target: r.target, + path: r.root, + name: r.project.displayName || r.project.name, + host: r.host, + openedAtMs: Date.now(), + }); +} + /** * Opens `path` of `target` (an SSH host or a WSL distribution) in this window. A dev container's * project folder is the one in the container: `path` is then only a label. @@ -185,30 +218,7 @@ export async function connectRemote(target: RemoteTarget, path: string) { await commands.remoteDisconnect().catch(() => {}); throw new IpcError({ kind: "cancelled", message: "Remote connection cancelled" }); } - enableRemote({ target: r.target, root: r.root, host: r.host, os: r.os, commands: r.commands }); - if (takeLegacyRemoteTrust(r.target, path, r.host)) { - const status = await call(commands.projectTrustStatus(r.root)); - if (!status.decided) await call(commands.projectTrustSet(r.root, true, false)); - if (!(await call(commands.remoteTrustStatus())).decided) await call(commands.remoteTrustSet(true)); - } - try { - await confirmProjectTrust(r.root); - } catch (error) { - await commands.closeProject(); - disableRemote(); - throw error; - } - const current = await commands.projectCurrent(); - if (current) r.project = current; - r.project.settings = await clientSettings(r.project.settings); - useProject.setState({ project: r.project, settings: r.project.settings }); - rememberRemote({ - target: r.target, - path: r.root, - name: r.project.displayName || r.project.name, - host: r.host, - openedAtMs: Date.now(), - }); + await attachRemote(r, path); return r; } finally { if (useRemoteProgress.getState().location === location) { @@ -218,6 +228,24 @@ export async function connectRemote(target: RemoteTarget, path: string) { } } +/** + * Connects this window to its remote project again after the connection was lost. The new server + * has none of the old one's documents, terminals or sessions, so the window opens its project + * again (editors come back from their saved tabs), as reopening the remote project would. + */ +export async function reconnectRemote(): Promise { + const session = useRemote.getState().session; + if (!session) return; + useRemote.setState({ reconnecting: true }); + try { + const r = await call(commands.remoteConnect(session.target, session.root, new Channel())); + useProject.setState({ project: null }); + await attachRemote(r, session.root); + } finally { + useRemote.setState({ reconnecting: false }); + } +} + export async function disconnectRemote() { if (!isRemoteWindow()) return; await commands.closeProject();