diff --git a/docs/en/guide/remote/ssh.mdx b/docs/en/guide/remote/ssh.mdx index 4893d89a6..ac9919376 100644 --- a/docs/en/guide/remote/ssh.mdx +++ b/docs/en/guide/remote/ssh.mdx @@ -134,6 +134,10 @@ needed. The status bar then shows **WSL: ``**. Opening a folder under `\\wsl.localhost\\` also opens it through the distribution. **Browse** is not available for WSL. +The **Ports** tool window is available in a WSL window too. Because the distribution shares this machine's +`localhost`, a forwarded port is reachable here on the same port; the window lists, opens and remembers ports as it +does for SSH. + ## Other uses of SSH configurations - **Run targets** (**Settings › Build, Execution, Deployment › Run Targets**) run a configuration on an SSH host. See diff --git a/docs/zh/guide/remote/ssh.mdx b/docs/zh/guide/remote/ssh.mdx index 496a5a03f..f41a239ca 100644 --- a/docs/zh/guide/remote/ssh.mdx +++ b/docs/zh/guide/remote/ssh.mdx @@ -106,6 +106,8 @@ Shell。IDE 内置的 SSH 客户端会使用配置里保存的密码、密钥或 打开 `\\wsl.localhost\\` 下的文件夹时,也会自动通过该发行版打开。WSL 方式不支持**浏览**。 +WSL 窗口中也可以使用**端口**工具窗口。由于发行版与本机的 `localhost` 相通,转发的端口在本机可用同一端口访问;端口的列表、在浏览器中打开和记忆方式与 SSH 相同。 + ## SSH 配置的其他用途 - **运行目标**(**设置 › 构建、执行、部署 › 运行目标**)可以在 SSH 主机上执行运行配置,见[运行配置](/zh/guide/run)。 diff --git a/src-tauri/src/remote_dev.rs b/src-tauri/src/remote_dev.rs index 60d9803bb..1351a2adb 100644 --- a/src-tauri/src/remote_dev.rs +++ b/src-tauri/src/remote_dev.rs @@ -88,10 +88,13 @@ pub struct Connection { /// A forwarded port's host (`None`: the remote host itself) and remote port. type ForwardKey = (Option, u16); -/// A forwarded port: through the SSH connection, or `docker exec` in a dev container. +/// A forwarded port: through the SSH connection, `docker exec` in a dev container, or — for +/// WSL — nothing, the distribution's `localhost` already being this machine's. enum Forward { Ssh(ide_ssh::Tunnel), Container(ide_remote::container_tunnel::Tunnel), + /// The remote port, reachable here on the same port without a tunnel. + Wsl(u16), } impl Forward { @@ -99,6 +102,7 @@ impl Forward { match self { Self::Ssh(t) => t.port(), Self::Container(t) => t.port(), + Self::Wsl(port) => *port, } } } @@ -954,20 +958,48 @@ pub async fn remote_forward_port( Ok(port) } +/// How a remote port reaches this machine: through the SSH connection, an exec-based +/// container tunnel, or — for WSL — nothing, the distribution's `localhost` being this +/// machine's. `None`: not reachable (another host only from a dev container). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum ForwardRoute { + Ssh, + Container, + Wsl, +} + +fn forward_route(target: &RemoteTarget, host: Option<&str>) -> Option { + match (target, host) { + (RemoteTarget::Ssh { .. }, None) => Some(ForwardRoute::Ssh), + (RemoteTarget::Ssh { .. }, Some(_)) => None, + (RemoteTarget::DevContainer { .. }, _) => Some(ForwardRoute::Container), + (RemoteTarget::Wsl { .. }, None) => Some(ForwardRoute::Wsl), + (RemoteTarget::Wsl { .. }, Some(_)) => None, + } +} + /// Forwards `remote_port` of `host` (`None`: the remote host itself) to the same local port -/// when it is free, else to a free one. Another host is reached from a dev container only. +/// when it is free, else to a free one. A WSL distribution shares this machine's loopback, so +/// its port is already reachable on the same port here. Another host is reached from a dev +/// container only. async fn open_forward(c: &Connection, host: Option<&str>, remote_port: u16) -> IdeResult { - if let (Some(session), None) = (c.session.clone(), host) { - let tunnel = ide_ssh::Tunnel::listen_on(session, Some(remote_port), "localhost", remote_port).await?; - return Ok(Forward::Ssh(tunnel)); + let unsupported = || IdeError::unavailable("Forwarding ports is not supported here yet"); + match forward_route(&c.target, host) { + Some(ForwardRoute::Ssh) => { + let session = c.session.clone().ok_or_else(unsupported)?; + let tunnel = ide_ssh::Tunnel::listen_on(session, Some(remote_port), "localhost", remote_port).await?; + Ok(Forward::Ssh(tunnel)) + } + Some(ForwardRoute::Container) => { + let exec = c.exec.clone().ok_or_else(unsupported)?; + let host = host.unwrap_or("localhost"); + Ok(Forward::Container( + ide_remote::container_tunnel::Tunnel::listen(exec, remote_port, host, remote_port).await?, + )) + } + Some(ForwardRoute::Wsl) => Ok(Forward::Wsl(remote_port)), + None => Err(unsupported()), } - if let Some(exec) = c.exec.clone() { - let host = host.unwrap_or("localhost"); - return Ok(Forward::Container( - ide_remote::container_tunnel::Tunnel::listen(exec, remote_port, host, remote_port).await?, - )); - } - Err(IdeError::unavailable("Forwarding ports is not supported in a WSL project yet")) } /// `web_url` answers with the remote host's built-in web server, on its loopback: the URL's @@ -1284,6 +1316,19 @@ mod tests { assert!(parse_remote_location(r"\\wsl.localhost\Ubuntu\home\me\app").is_none()); } + #[test] + fn a_port_is_routed_by_the_target_and_its_host() { + let ssh = RemoteTarget::Ssh { config: "box".into() }; + let wsl = RemoteTarget::Wsl { distro: "Ubuntu".into() }; + let container = RemoteTarget::DevContainer { folder: "/work/app".into(), config: String::new() }; + assert_eq!(forward_route(&ssh, None), Some(ForwardRoute::Ssh)); + assert_eq!(forward_route(&ssh, Some("selenium")), None); + assert_eq!(forward_route(&container, None), Some(ForwardRoute::Container)); + assert_eq!(forward_route(&container, Some("selenium")), Some(ForwardRoute::Container)); + assert_eq!(forward_route(&wsl, None), Some(ForwardRoute::Wsl)); + assert_eq!(forward_route(&wsl, Some("selenium")), None); + } + #[test] fn a_command_missing_on_a_server_of_another_version_says_which_versions() { let missing = || IdeError::unavailable("-32601: command web_url is not available remotely"); diff --git a/src/features/remote-dev/index.ts b/src/features/remote-dev/index.ts index 8da2ee21d..ceaaac7bd 100644 --- a/src/features/remote-dev/index.ts +++ b/src/features/remote-dev/index.ts @@ -16,13 +16,14 @@ import { closeConnectDialog, openConnectDialog } from "./model"; import { restorePorts, usePorts } from "./ports"; import { installReconnect, reconnectNow } from "./reconnect"; -/** Forwarded ports are available while this window is connected to an SSH host or a dev container. */ +/** Forwarded ports are available while this window is connected to an SSH host, a WSL distribution or a dev container. */ function trackPortsWindow(): () => void { let off: (() => void) | null = null; let session = useRemote.getState().session; const sync = () => { const next = useRemote.getState().session; - const connected = next?.target.kind === "ssh" || next?.target.kind === "devContainer"; + const connected = + next?.target.kind === "ssh" || next?.target.kind === "wsl" || next?.target.kind === "devContainer"; if (connected && (next !== session || !off)) { usePorts.setState({ ports: [] }); void restorePorts(); diff --git a/src/features/remote-dev/ports.test.tsx b/src/features/remote-dev/ports.test.tsx index 167eb9ff2..c2d9f22aa 100644 --- a/src/features/remote-dev/ports.test.tsx +++ b/src/features/remote-dev/ports.test.tsx @@ -138,14 +138,53 @@ it("forwards and remembers ports of a dev container, per folder and configuratio useRemote.setState({ session: null }); }); -it("doesn't forward ports of a WSL project yet", async () => { +it("forwards and remembers ports of a WSL distribution, per distro and folder", async () => { const { useRemote } = await import("@/platform/remote"); - ipc.remoteForwardPort.mockClear(); - useRemote.setState({ - session: { target: { kind: "wsl", distro: "u" }, root: "/home/u", host: "u", os: "linux", commands: [] }, + const { forwardPort, savedPorts } = await import("./ports"); + const wsl = (distro: string, root: string) => ({ + target: { kind: "wsl" as const, distro }, + root, + host: distro, + os: "linux", + commands: [], }); - expect(await forwardPort(8080)).toBeNull(); - expect(ipc.remoteForwardPort).not.toHaveBeenCalled(); + ipc.remoteForwardPort.mockClear(); + useRemote.setState({ session: wsl("Ubuntu", "/home/u/app") }); + expect(await forwardPort(8080)).toEqual({ remotePort: 8080, localPort: 8080, host: null }); + expect(ipc.remoteForwardPort).toHaveBeenCalledWith(8080); + expect(savedPorts()).toEqual([8080]); + useRemote.setState({ session: wsl("Ubuntu", "/home/u/other") }); + expect(savedPorts()).toEqual([]); + useRemote.setState({ session: wsl("Debian", "/home/u/app") }); + expect(savedPorts()).toEqual([]); + // An SSH configuration of the same name has its own list. + useRemote.setState({ + session: { target: { kind: "ssh", config: "Ubuntu" }, root: "/home/u/app", host: "h", os: "linux", commands: [] }, + }); + expect(savedPorts()).toEqual([]); + useRemote.setState({ session: null }); +}); + +it("forwards the ports saved for a WSL distribution again after reconnecting", async () => { + const { useRemote } = await import("@/platform/remote"); + const { forwardPort, restorePorts, savedPorts } = await import("./ports"); + useRemote.setState({ + session: { + target: { kind: "wsl", distro: "Ubuntu" }, + root: "/home/u/app", + host: "Ubuntu", + os: "linux", + commands: [], + }, + }); + await forwardPort(3000); + expect(savedPorts()).toEqual([3000]); + // Reconnected: the new connection forwards nothing yet. + forwarded.length = 0; + ipc.remoteForwardPort.mockClear(); + await restorePorts(); + expect(ipc.remoteForwardPort).toHaveBeenCalledWith(3000); + expect(usePorts.getState().ports).toEqual([{ remotePort: 3000, localPort: 53000, host: null }]); useRemote.setState({ session: null }); }); @@ -199,16 +238,40 @@ it("does not display a previous session's delayed port response", async () => { useRemote.setState({ session: null }); }); -it("reloads ports when switching directly between connected sessions", async () => { +it.each([ + [ + "SSH", + (folder: string) => ({ + target: { kind: "ssh" as const, config: folder }, + root: "/srv/app", + host: "h", + os: "linux", + commands: [], + }), + ], + [ + "WSL", + (folder: string) => ({ + target: { kind: "wsl" as const, distro: folder }, + root: "/home/u/app", + host: folder, + os: "linux", + commands: [], + }), + ], + [ + "dev container", + (folder: string) => ({ + target: { kind: "devContainer" as const, folder, config: "" }, + root: "/workspaces/app", + host: "app", + os: "linux", + commands: [], + }), + ], +])("reloads ports on connect and when switching between connected %s sessions", async (_kind, session) => { const { useRemote } = await import("@/platform/remote"); const { activate } = await import("./index"); - const session = (folder: string) => ({ - target: { kind: "devContainer" as const, folder, config: "" }, - root: "/workspaces/app", - host: "app", - os: "linux", - commands: [], - }); useRemote.setState({ session: session("/first") }); forwarded.push({ remotePort: 8000, localPort: 8000, host: null }); const dispose = activate(); diff --git a/src/features/remote-dev/ports.ts b/src/features/remote-dev/ports.ts index b545af024..8edd8a5a1 100644 --- a/src/features/remote-dev/ports.ts +++ b/src/features/remote-dev/ports.ts @@ -1,6 +1,7 @@ /** - * Remote ports forwarded to this machine, remembered per host (or dev container) and folder and - * forwarded again on reconnect. A dev container also forwards its `forwardPorts` on its own. + * Remote ports forwarded to this machine, remembered per SSH host, WSL distribution or dev + * container and folder, and forwarded again on reconnect. A dev container also forwards its + * `forwardPorts` on its own. */ import { create } from "zustand"; import type { ForwardedPort } from "@/bindings"; @@ -16,6 +17,8 @@ function savedKey(): string | null { switch (session?.target.kind) { case "ssh": return `${SAVED_KEY}${session.target.config}:${session.root}`; + case "wsl": + return `${SAVED_KEY}wsl:${session.target.distro}:${session.root}`; case "devContainer": return `${SAVED_KEY}devcontainer:${JSON.stringify([session.target.folder, session.target.config])}`; default: @@ -67,14 +70,6 @@ export function parsePort(text: string): number | null { } export async function forwardPort(port: number): Promise { - if (useRemote.getState().session?.target.kind === "wsl") { - notifications().notify({ - group: "remote", - level: "error", - title: tx("Forwarding ports is not supported in a WSL project yet"), - }); - return null; - } try { const forwarded = await call(commands.remoteForwardPort(port)); await refreshPorts(true); diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index f58b64528..aa007f28b 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -696,7 +696,6 @@ "WSL distribution:": "WSL distribution:", "WSL distribution": "WSL distribution", "Project runs on {label}": "Project runs on {label}", - "Forwarding ports is not supported in a WSL project yet": "Forwarding ports is not supported in a WSL project yet", "PHPStan check failed": "PHPStan check failed", "PHPStan ended with {status} and no report": "PHPStan ended with {status} and no report", "Cannot run {program}: {error}": "Cannot run {program}: {error}", diff --git a/src/platform/locales/text/ko.json b/src/platform/locales/text/ko.json index 7b4d8e4fe..7b62c7221 100644 --- a/src/platform/locales/text/ko.json +++ b/src/platform/locales/text/ko.json @@ -4482,7 +4482,6 @@ "WSL distribution:": "WSL 배포판:", "WSL distribution": "WSL 배포판", "Project runs on {label}": "프로젝트가 {label}에서 실행됩니다", - "Forwarding ports is not supported in a WSL project yet": "WSL 프로젝트에서는 아직 포트 포워딩을 지원하지 않습니다", "No SSH configurations": "SSH 구성 없음", "Project directory:": "프로젝트 디렉터리:", "Remote Development…": "원격 개발…", diff --git a/src/platform/locales/text/tr.json b/src/platform/locales/text/tr.json index 617a1411f..c3849720d 100644 --- a/src/platform/locales/text/tr.json +++ b/src/platform/locales/text/tr.json @@ -617,7 +617,6 @@ "WSL distribution:": "WSL dağıtımı:", "WSL distribution": "WSL dağıtımı", "Project runs on {label}": "Proje {label} üzerinde çalışıyor", - "Forwarding ports is not supported in a WSL project yet": "WSL projelerinde bağlantı noktası yönlendirme henüz desteklenmiyor", "PHPStan check failed": "PHPStan denetimi başarısız", "PHPStan ended with {status} and no report": "PHPStan {status} durumuyla, rapor oluşturmadan sonlandı", "Cannot run {program}: {error}": "{program} çalıştırılamıyor: {error}", diff --git a/src/platform/locales/text/zh-TW.json b/src/platform/locales/text/zh-TW.json index 65073ea6d..c4f7227fd 100644 --- a/src/platform/locales/text/zh-TW.json +++ b/src/platform/locales/text/zh-TW.json @@ -5380,7 +5380,6 @@ "WSL distribution:": "WSL 發行版:", "WSL distribution": "WSL 發行版", "Project runs on {label}": "專案執行於 {label}", - "Forwarding ports is not supported in a WSL project yet": "WSL 專案暫不支援埠轉發", "No SSH configurations": "沒有 SSH 組態", "Project directory:": "專案目錄:", "Remote Development…": "遠端開發…", diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index dec2aed77..75f5af9fe 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -5457,7 +5457,6 @@ "WSL distribution:": "WSL 发行版:", "WSL distribution": "WSL 发行版", "Project runs on {label}": "项目运行于 {label}", - "Forwarding ports is not supported in a WSL project yet": "WSL 项目暂不支持端口转发", "No SSH configurations": "没有 SSH 配置", "Project directory:": "项目目录:", "Remote Development…": "远程开发…",