diff --git a/.agents/notes/proposed/architecture/2026-10-24-remote-development-workspace-host.md b/.agents/notes/proposed/architecture/2026-10-24-remote-development-workspace-host.md index 265c4fe45..31f9a41e3 100644 --- a/.agents/notes/proposed/architecture/2026-10-24-remote-development-workspace-host.md +++ b/.agents/notes/proposed/architecture/2026-10-24-remote-development-workspace-host.md @@ -106,7 +106,7 @@ Linux 静态版用 Rust 自带的 `rust-lld` 链接,在 macOS 和 Linux 上都 - **路径**:协议里的路径是远端主机上的绝对路径。这一层是文件系统和进程的适配器,工具链、终端和调试器都需要真实的主机路径;以工作区为根的相对标识在这一层之上构造。 - **错误**:错误码稳定(例如 `NOT_FOUND`、`CONFLICT`、`DIRECTORY_NOT_EMPTY`),客户端按错误码分支。`message` 只给人看,OS 错误号放在 `details` 里。 - **兼容**:不兼容的修改才提升协议版本号。新增方法通过 `features` 列表声明,客户端先查列表再调用。 -- **只走标准输入输出**:服务不监听任何 TCP 端口,所以共享主机上的其他用户连不进来。端口转发以后也走这条流。 +- **只走标准输入输出**:服务的协议通道不监听任何 TCP 端口,所以共享主机上的其他用户连不进协议。端口转发也走这条流。唯一的例外是 #2231 §8 设计的主机侧转发规则(T3 主机端口到其他服务器、T4 反向转发,尚未实现):服务只在用户建立并确认的规则存在期间按规则打开监听,默认只绑定主机回环地址(#2231 S20、S27、S29)。 ### 文件和进程的语义 @@ -178,7 +178,7 @@ inotify 的坑:目录是逐个注册的,新建目录要在收到创建事件 - **终端**:用伪终端(PTY)运行,被启动的程序成为新会话的首进程,并把这个终端设为控制终端,和 SSH 登录时完全一样。所以作业控制、`Ctrl-C`、窗口大小变化(内核会发 `SIGWINCH`)都符合用户习惯。默认程序是用户的登录 shell,按 POSIX 惯例在 `argv[0]` 前加 `-`,sh、bash、zsh、fish、csh 都认。关闭终端相当于关掉终端窗口:向它的整个会话发 `SIGHUP`,2 秒后还在的发 `SIGKILL`。 - **登录环境**:经 SSH 或 `docker exec` 执行的命令,拿到的环境往往很少,nvm、SDKMAN、Homebrew 加进 `PATH` 的路径都不在里面。服务会用用户自己的 shell 以交互式登录 shell 启动一次,让它运行 `lithe-remote-server --print-environment`,读取它最终得到的环境,并在会话内缓存。用服务自己的二进制输出环境,可以避开 GNU 和 BSD `env` 的参数差异;每次尝试最多等 10 秒,profile 卡住(例如启动 tmux)也不会挂住服务;交互式失败就退回非交互登录 shell,再失败就用服务自己的环境,并在 `diagnostics` 里说明原因。`process.spawn` 指定 `environment: login` 就会用这个环境作为基础。 - **复制**:`fs.copy` 拒绝把文件复制到它自己身上(同一路径、经过符号链接的任一方向、或者是硬链接),也拒绝在解析链接之后把目录复制进它自己。覆盖写入会在读取源文件之前先截断目标,第一版因此会把源文件清空。socket、FIFO 和设备文件从不复制:作为复制对象本身时返回 `UNSUPPORTED`,在目录树里时跳过并计数,因为打开 FIFO 读取可能永远阻塞。 -- **端口**:隧道把远端的 TCP 端口或 Unix socket(Docker、数据库的 socket)接到协议流里。客户端的 `PortForward` 在本地监听,每个连接开一条隧道,所以浏览器访问 `127.0.0.1:<本地端口>` 就能到达只监听在远端回环地址上的服务。本地客户端发完请求后半关闭时(HTTP/1.0、`nc -N`),转发用 `tunnel.shutdownWrite`:先把排队的数据写完,再只关闭写入端,远端的响应照常返回;`tunnel.close` 只用于中止。`ports.listening` 列出远端正在监听的端口,为以后的自动转发做准备。 +- **端口**:隧道把远端的 TCP 端口或 Unix socket(Docker、数据库的 socket)接到协议流里。客户端的 `PortForward` 在本地监听,每个连接开一条隧道,所以浏览器访问 `127.0.0.1:<本地端口>` 就能到达只监听在远端回环地址上的服务。本地客户端发完请求后半关闭时(HTTP/1.0、`nc -N`),转发用 `tunnel.shutdownWrite`:先把排队的数据写完,再只关闭写入端,远端的响应照常返回;`tunnel.close` 只用于中止。`ports.listening` 列出远端正在监听的端口,桌面端的“端口”工具窗口用它列出主机上的端口,默认不自动转发。转发目标的输入(端口、`主机:端口`、网址)由 Core 的 `remote.parseForwardAddress` 解析。转发按“在哪一侧监听、由哪一侧连接哪个目标”建模为四类规则(#2231 §8 D10):T1 本机到主机回环、T2 本机到主机能访问的其他服务器(已实现);T3 主机端口到其他服务器、T4 反向转发(已设计,未实现)。T3 在主机上完成转发,数据不绕回本机;T4 默认关闭。 ### 后续阶段 @@ -289,7 +289,7 @@ M2 接入“打开远程文件夹”时,SSH 连接的配置界面参考用户 - 不要在功能代码里拼 `ssh host 'mvn package'`。所有远端执行都走 `process.spawn`。 - 不要为了“远程 Mac”在客户端写 `if os == macos`。缺少的事实应该补进能力描述。 -- 不要让服务监听 TCP 端口,也不要把服务装到其他用户可写的目录。 +- 不要让服务为自己的协议监听 TCP 端口,也不要把服务装到其他用户可写的目录。主机侧转发规则的监听只按用户确认的规则打开(见“协议的几条硬规则”)。 - 不要在 SSH 跳转后面传入用户提供的任意字符串(例如带 `'` 的路径)。把它放进协议请求里,不要放在命令行里。 ## 考虑过的备选方案 diff --git a/desktop/internal/core/errors.go b/desktop/internal/core/errors.go index 6bb752765..99a40476d 100644 --- a/desktop/internal/core/errors.go +++ b/desktop/internal/core/errors.go @@ -68,6 +68,12 @@ const ( CodeTimedOut ErrorCode = "timed_out" // CodeConnectionClosed means a long-lived connection named by the request is closed. CodeConnectionClosed ErrorCode = "connection_closed" + // CodeForwardTargetNotConfirmed means remote.startForward named a target outside the host's + // loopback interface the user did not confirm (S28); nothing was forwarded. + CodeForwardTargetNotConfirmed ErrorCode = "forward_target_not_confirmed" + // CodeForwardLimitReached means the session already runs as many forwards as Core allows; + // details carry the maximum. + CodeForwardLimitReached ErrorCode = "forward_limit_reached" // CodeRemoteServerInvalid means the remote server build for the host's platform could not be // read, or its SHA-256 is not the one the application's manifest names; nothing was sent to // the host. diff --git a/desktop/internal/core/remote_forward.go b/desktop/internal/core/remote_forward.go new file mode 100644 index 000000000..ca4925961 --- /dev/null +++ b/desktop/internal/core/remote_forward.go @@ -0,0 +1,132 @@ +package core + +import "context" + +// RemoteForward is one forward of a session: a listener on this computer's loopback interface +// whose connections Core carries over the session to a port as the host sees it. Only this +// computer's processes can reach the listener (S27), and the host never reaches back (S29). +type RemoteForward struct { + // ID names the forward to RemoteStopForward; it is unique within the session. + ID uint64 `json:"id"` + // LocalHost and LocalPort are where the forward listens on this computer; LocalHost is + // always a loopback address. + LocalHost string `json:"localHost"` + LocalPort uint16 `json:"localPort"` + // RequestedLocalPort is the local port the forward was asked for, absent when any was + // accepted; LocalPortChanged reports that it was taken and the system chose LocalPort. + RequestedLocalPort *uint16 `json:"requestedLocalPort,omitempty"` + LocalPortChanged bool `json:"localPortChanged"` + // TargetHost and TargetPort are the forward's target as the host resolves it, and + // LoopbackTarget reports that the target is on the host's own loopback interface. + TargetHost string `json:"targetHost"` + TargetPort uint16 `json:"targetPort"` + LoopbackTarget bool `json:"loopbackTarget"` + // Connections is the number of connections the forward carries now. + Connections uint64 `json:"connections"` +} + +// RemoteForwardTarget is what RemoteStartForward forwards to. +type RemoteForwardTarget struct { + // Host is an IP address, with or without brackets for IPv6, or a name the host resolves, + // such as localhost; Port is the port there. + Host string `json:"targetHost"` + Port uint16 `json:"targetPort"` + // LocalPort is the local port to listen on; 0 lets the system choose one. A taken port is + // replaced by one the system chooses, which the forward reports as LocalPortChanged. + LocalPort uint16 `json:"localPort,omitempty"` + // AllowNonLoopback records that the user confirmed a target outside the host's loopback + // interface; without it such a target fails with CodeForwardTargetNotConfirmed (S28). + AllowNonLoopback bool `json:"allowNonLoopbackTarget,omitempty"` +} + +// RemoteListeningPort is a TCP port listening on the host. +type RemoteListeningPort struct { + // Address is the bound address as the host reports it, such as 127.0.0.1, :: or 0.0.0.0. + Address string `json:"address"` + Port uint16 `json:"port"` + // PID and Process are the process that holds the socket and its command name, which Linux + // shortens to 15 bytes; both are absent for a process the server's user cannot inspect. + PID uint32 `json:"pid,omitempty"` + Process string `json:"process,omitempty"` +} + +// RemoteStartForward forwards a local port to target over the session sessionID. created is +// false when a forward to the same target already ran: forward is then that forward, unchanged. +// A target outside the host's loopback interface that the user did not confirm fails with +// CodeForwardTargetNotConfirmed, a session at its limit with CodeForwardLimitReached, an invalid +// target with CodeInvalidRequest and a broken or unknown session with CodeConnectionClosed. +func (c *Client) RemoteStartForward(ctx context.Context, sessionID string, target RemoteForwardTarget) (forward RemoteForward, created bool, err error) { + var result struct { + Forward RemoteForward `json:"forward"` + Created bool `json:"created"` + } + err = c.Execute(ctx, "remote.startForward", struct { + SessionID string `json:"sessionId"` + RemoteForwardTarget + }{sessionID, target}, &result) + if err != nil { + return RemoteForward{}, false, err + } + return result.Forward, result.Created, nil +} + +// RemoteStopForward stops the forward id of the session sessionID and closes its connections; +// stopped is false when the session has no such forward. +func (c *Client) RemoteStopForward(ctx context.Context, sessionID string, id uint64) (stopped bool, err error) { + var result struct { + Stopped bool `json:"stopped"` + } + err = c.Execute(ctx, "remote.stopForward", struct { + SessionID string `json:"sessionId"` + ForwardID uint64 `json:"forwardId"` + }{sessionID, id}, &result) + return result.Stopped, err +} + +// RemoteForwards lists the running forwards of the session sessionID by id. A session that ends +// stops all of them. +func (c *Client) RemoteForwards(ctx context.Context, sessionID string) ([]RemoteForward, error) { + var result struct { + Forwards []RemoteForward `json:"forwards"` + } + err := c.Execute(ctx, "remote.forwards", struct { + SessionID string `json:"sessionId"` + }{sessionID}, &result) + return result.Forwards, err +} + +// RemoteListeningPorts lists the TCP ports listening on the host of the session sessionID, +// sorted by address and port. +func (c *Client) RemoteListeningPorts(ctx context.Context, sessionID string) ([]RemoteListeningPort, error) { + var result struct { + Ports []RemoteListeningPort `json:"ports"` + } + err := c.RemoteHostRequest(ctx, sessionID, "ports.listening", nil, &result) + return result.Ports, err +} + +// RemoteForwardAddress is an address the user typed into the Ports window, as a forward target: +// TargetHost and TargetPort are what the host dials, TargetHost without brackets and a name in +// lower case. Scheme and Path come only from an address written as a URL, which the window opens +// the same way: Scheme in lower case, and Path what follows the host and port, its query and +// fragment included, empty when that is empty or "/". +type RemoteForwardAddress struct { + TargetHost string `json:"targetHost"` + TargetPort uint16 `json:"targetPort"` + Scheme string `json:"scheme,omitempty"` + Path string `json:"path,omitempty"` +} + +// RemoteParseForwardAddress reads text, a port alone (on localhost), host:port with brackets +// around an IPv6 host, or a URL, whose scheme gives the port when it names none (80 for http and +// ws, 443 for https and wss). A refused address fails with CodeInvalidRequest, and +// RemoteConnectionFieldError names the field text and the reason: empty, tooLong, malformed, +// scheme, credentials (a user name or password, refused rather than kept), host or port. Nothing +// is resolved or contacted, and no session is needed. +func (c *Client) RemoteParseForwardAddress(ctx context.Context, text string) (RemoteForwardAddress, error) { + var address RemoteForwardAddress + err := c.Execute(ctx, "remote.parseForwardAddress", struct { + Text string `json:"text"` + }{text}, &address) + return address, err +} diff --git a/desktop/internal/core/remote_helpers_test.go b/desktop/internal/core/remote_helpers_test.go index 6541707f6..e131c0369 100644 --- a/desktop/internal/core/remote_helpers_test.go +++ b/desktop/internal/core/remote_helpers_test.go @@ -94,6 +94,36 @@ func TestRemoteParseAddressSplitsTheFields(t *testing.T) { } } +// A port, host:port or URL typed into the Ports window becomes a forward target; a URL keeps its +// scheme and path and gives its default port, and a user name or password is refused by reason. +func TestRemoteParseForwardAddressReadsPortsAndURLs(t *testing.T) { + client := NewClient() + ctx := testContext(t) + cases := map[string]RemoteForwardAddress{ + "3000": {TargetHost: "localhost", TargetPort: 3000}, + "10.0.0.5:9000": {TargetHost: "10.0.0.5", TargetPort: 9000}, + "[::1]:5432": {TargetHost: "::1", TargetPort: 5432}, + "HTTPS://Build.Example/app?x=1": {TargetHost: "build.example", TargetPort: 443, Scheme: "https", Path: "/app?x=1"}, + "http://localhost:3000/": {TargetHost: "localhost", TargetPort: 3000, Scheme: "http"}, + } + for text, want := range cases { + if got, err := client.RemoteParseForwardAddress(ctx, text); err != nil || got != want { + t.Errorf("address %q = %+v, err = %v, want %+v", text, got, err, want) + } + } + for text, reason := range map[string]string{ + "https://dev:secret@build.example": "credentials", + "postgres://build.example": "port", + "not a port": "malformed", + "70000": "port", + } { + _, err := client.RemoteParseForwardAddress(ctx, text) + if field, got, ok := RemoteConnectionFieldError(err); !ok || field != "text" || got != reason { + t.Errorf("address #%d: field %q, reason %q, want text and %q", len(text), field, got, reason) + } + } +} + // The effective values name where each comes from: the connection, the SSH configuration or the // default. func TestRemoteEffectiveSettingsNameTheirSources(t *testing.T) { diff --git a/desktop/internal/core/remote_session_test.go b/desktop/internal/core/remote_session_test.go index d71be2d36..534fe0329 100644 --- a/desktop/internal/core/remote_session_test.go +++ b/desktop/internal/core/remote_session_test.go @@ -117,6 +117,18 @@ func TestRemoteSessionCommandsOfAnUnknownSession(t *testing.T) { if _, saved, err := client.RemoteWriteFile(ctx, "no-such-session", "/srv/repo/README.md", []byte("text"), &RemoteFileVersion{Size: 4, ModifiedMs: &modified}); saved || !errors.As(err, &coreErr) || coreErr.Code != CodeConnectionClosed { t.Fatalf("writeFile = %v, %v, want connection_closed", saved, err) } + if _, created, err := client.RemoteStartForward(ctx, "no-such-session", RemoteForwardTarget{Host: "127.0.0.1", Port: 8080}); created || !errors.As(err, &coreErr) || coreErr.Code != CodeConnectionClosed { + t.Fatalf("startForward = %v, %v, want connection_closed", created, err) + } + if stopped, err := client.RemoteStopForward(ctx, "no-such-session", 1); stopped || !errors.As(err, &coreErr) || coreErr.Code != CodeConnectionClosed { + t.Fatalf("stopForward = %v, %v, want connection_closed", stopped, err) + } + if _, err := client.RemoteForwards(ctx, "no-such-session"); !errors.As(err, &coreErr) || coreErr.Code != CodeConnectionClosed { + t.Fatalf("forwards = %v, want connection_closed", err) + } + if _, err := client.RemoteListeningPorts(ctx, "no-such-session"); !errors.As(err, &coreErr) || coreErr.Code != CodeConnectionClosed { + t.Fatalf("ports.listening = %v, want connection_closed", err) + } } // A context without its remote workspace sends requests that compute from their payload as diff --git a/desktop/internal/i18n/messages.go b/desktop/internal/i18n/messages.go index 9124ababf..25602d4e5 100644 --- a/desktop/internal/i18n/messages.go +++ b/desktop/internal/i18n/messages.go @@ -134,6 +134,8 @@ type ToolMessages struct { Debug string Notifications string Background string + // Ports names the tool window of a remote workspace that lists the host's ports and forwards. + Ports string // ToolWindows names the stripe button that lists the stripe buttons the user hid. ToolWindows string // DragHint tells assistive technology that a toolbar item can be dragged elsewhere. diff --git a/desktop/internal/i18n/shared.generated.go b/desktop/internal/i18n/shared.generated.go index 4c26057b7..efbb51bb7 100644 --- a/desktop/internal/i18n/shared.generated.go +++ b/desktop/internal/i18n/shared.generated.go @@ -1759,6 +1759,57 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.remote.openOther": "Open another…", "desktop.remote.port": "Port", "desktop.remote.portPlaceholder": "Auto (SSH config, otherwise 22)", + "desktop.remote.ports.add": "Forward Port", + "desktop.remote.ports.addCredentials": "The address can't include a user name or password.", + "desktop.remote.ports.addInvalid": "Enter a port from 1 to 65535, host:port, or a URL such as http://localhost:3000.", + "desktop.remote.ports.addLabel": "Port to Forward", + "desktop.remote.ports.addPlaceholder": "Port, host:port or URL", + "desktop.remote.ports.changeLocal": "Change Local Port…", + "desktop.remote.ports.columnLocal": "Local Address", + "desktop.remote.ports.columnProcess": "Process", + "desktop.remote.ports.columnRemote": "Remote Port", + "desktop.remote.ports.columnSource": "Source", + "desktop.remote.ports.columnStatus": "Status", + "desktop.remote.ports.confirmBody": "{target} is not the loopback address of {name}. Forwarding it lets every program on this computer reach that address through the host. Continue only if you trust it.", + "desktop.remote.ports.confirmCancel": "Cancel", + "desktop.remote.ports.confirmForward": "Forward", + "desktop.remote.ports.confirmTitle": "Forward to Another Address?", + "desktop.remote.ports.copyAddress": "Copy Local Address", + "desktop.remote.ports.disconnected": "Not connected. Forwards end with the connection; forward the ports again after reconnecting.", + "desktop.remote.ports.empty": "No ports are listening on the host. Type a port above to forward it anyway.", + "desktop.remote.ports.forward": "Forward", + "desktop.remote.ports.forwardLocal": "Forward to Local Port…", + "desktop.remote.ports.help": "A forwarded port listens only on this computer's loopback address (127.0.0.1). Every program on this computer can connect to it, not just Lithe. The host cannot reach this computer through it.", + "desktop.remote.ports.invalidTarget": "The host or port is not valid.", + "desktop.remote.ports.limit": "This connection already forwards {maximum} ports, the most allowed. Stop one first.", + "desktop.remote.ports.loading": "Reading the host's listening ports…", + "desktop.remote.ports.localApply": "Forward", + "desktop.remote.ports.localBody": "Forward {remote} on {name} to this port of this computer's loopback address. If another program uses it, a free port is used instead and the row says so.", + "desktop.remote.ports.localCancel": "Cancel", + "desktop.remote.ports.localChanged": "Port {requested} is in use on this computer, so {port} is used instead.", + "desktop.remote.ports.localInvalid": "Enter a port number from 1 to 65535.", + "desktop.remote.ports.localLabel": "Local port", + "desktop.remote.ports.localTitle": "Local Port", + "desktop.remote.ports.openBrowser": "Open in Browser", + "desktop.remote.ports.process": "{process} (PID {pid})", + "desktop.remote.ports.processUnknown": "Unknown", + "desktop.remote.ports.readFailed": "Could not read the host's listening ports: {reason}", + "desktop.remote.ports.remoteListening": "Listening on {addresses}", + "desktop.remote.ports.remoteMore": "{address} +{count}", + "desktop.remote.ports.remoteUrlListening": "{url}, listening on {addresses}", + "desktop.remote.ports.remove": "Remove", + "desktop.remote.ports.sourceListening": "Listening", + "desktop.remote.ports.sourceManual": "Added", + "desktop.remote.ports.statusFailed": "Failed: {reason}", + "desktop.remote.ports.statusForwarded": "Forwarded", + "desktop.remote.ports.statusForwarding": "Forwarding…", + "desktop.remote.ports.statusLabel": "Forwarded Ports", + "desktop.remote.ports.statusNotForwarded": "Not forwarded", + "desktop.remote.ports.statusStopping": "Stopping…", + "desktop.remote.ports.statusTooltip": "{count} forwarded. Click to open Ports.", + "desktop.remote.ports.stop": "Stop Forwarding", + "desktop.remote.ports.stopAll": "Stop All Forwards", + "desktop.remote.ports.title": "Ports", "desktop.remote.probe.authenticationFailed": "Authentication failed: the server did not accept the keys or password offered.", "desktop.remote.probe.connected": "Connected: {system} {machine}", "desktop.remote.probe.cpu": "CPUs", @@ -5405,6 +5456,57 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.remote.openOther": "打开其他…", "desktop.remote.port": "端口", "desktop.remote.portPlaceholder": "自动(SSH 配置,否则 22)", + "desktop.remote.ports.add": "转发端口", + "desktop.remote.ports.addCredentials": "地址不能包含用户名或密码。", + "desktop.remote.ports.addInvalid": "请输入 1–65535 的端口、“主机:端口”,或 http://localhost:3000 这样的网址。", + "desktop.remote.ports.addLabel": "要转发的端口", + "desktop.remote.ports.addPlaceholder": "端口、主机:端口或网址", + "desktop.remote.ports.changeLocal": "更改本机端口…", + "desktop.remote.ports.columnLocal": "本机地址", + "desktop.remote.ports.columnProcess": "进程", + "desktop.remote.ports.columnRemote": "远端端口", + "desktop.remote.ports.columnSource": "来源", + "desktop.remote.ports.columnStatus": "状态", + "desktop.remote.ports.confirmBody": "{target} 不是 {name} 自身的回环地址。转发后,本机上的所有程序都能经由主机访问这个地址。请确认你信任它后再继续。", + "desktop.remote.ports.confirmCancel": "取消", + "desktop.remote.ports.confirmForward": "转发", + "desktop.remote.ports.confirmTitle": "转发到其他地址?", + "desktop.remote.ports.copyAddress": "复制本机地址", + "desktop.remote.ports.disconnected": "未连接。转发随连接一起结束,重新连接后需要再次转发。", + "desktop.remote.ports.empty": "主机上没有正在监听的端口。也可以在上方输入端口直接转发。", + "desktop.remote.ports.forward": "转发", + "desktop.remote.ports.forwardLocal": "转发到指定本机端口…", + "desktop.remote.ports.help": "转发的端口只监听本机的回环地址(127.0.0.1)。本机上的所有程序都能连接,不只是 Lithe;主机无法通过它反向访问本机。", + "desktop.remote.ports.invalidTarget": "主机或端口无效。", + "desktop.remote.ports.limit": "此连接已转发 {maximum} 个端口,达到上限,请先停止一个。", + "desktop.remote.ports.loading": "正在读取主机上的监听端口…", + "desktop.remote.ports.localApply": "转发", + "desktop.remote.ports.localBody": "把 {name} 上的 {remote} 转发到本机回环地址的这个端口。如果它已被其他程序占用,会改用一个空闲端口,并在这一行注明。", + "desktop.remote.ports.localCancel": "取消", + "desktop.remote.ports.localChanged": "本机端口 {requested} 已被占用,改用 {port}。", + "desktop.remote.ports.localInvalid": "请输入 1 到 65535 之间的端口号。", + "desktop.remote.ports.localLabel": "本机端口", + "desktop.remote.ports.localTitle": "本机端口", + "desktop.remote.ports.openBrowser": "在浏览器中打开", + "desktop.remote.ports.process": "{process}(PID {pid})", + "desktop.remote.ports.processUnknown": "未知", + "desktop.remote.ports.readFailed": "无法读取主机上的监听端口:{reason}", + "desktop.remote.ports.remoteListening": "监听地址:{addresses}", + "desktop.remote.ports.remoteMore": "{address} +{count}", + "desktop.remote.ports.remoteUrlListening": "{url},监听地址:{addresses}", + "desktop.remote.ports.remove": "移除", + "desktop.remote.ports.sourceListening": "监听发现", + "desktop.remote.ports.sourceManual": "手动添加", + "desktop.remote.ports.statusFailed": "失败:{reason}", + "desktop.remote.ports.statusForwarded": "已转发", + "desktop.remote.ports.statusForwarding": "正在转发…", + "desktop.remote.ports.statusLabel": "已转发的端口", + "desktop.remote.ports.statusNotForwarded": "未转发", + "desktop.remote.ports.statusStopping": "正在停止…", + "desktop.remote.ports.statusTooltip": "已转发 {count} 个端口,点击打开“端口”窗口。", + "desktop.remote.ports.stop": "停止转发", + "desktop.remote.ports.stopAll": "停止全部转发", + "desktop.remote.ports.title": "端口", "desktop.remote.probe.authenticationFailed": "身份验证失败:服务器没有接受提供的密钥或密码。", "desktop.remote.probe.connected": "已连接:{system} {machine}", "desktop.remote.probe.cpu": "CPU 数", diff --git a/desktop/internal/i18n/shell_messages.go b/desktop/internal/i18n/shell_messages.go index 0a55155c5..b978deec5 100644 --- a/desktop/internal/i18n/shell_messages.go +++ b/desktop/internal/i18n/shell_messages.go @@ -18,6 +18,7 @@ func toolMessages(language Language) ToolMessages { Debug: Shared(language, "native.debug"), Notifications: Shared(language, "notifications.title"), Background: Shared(language, "desktop.tools.background"), + Ports: Shared(language, "desktop.remote.ports.title"), ToolWindows: Shared(language, "native.toolWindows"), DragHint: Shared(language, "desktop.tools.dragHint"), } diff --git a/desktop/internal/workbench/app.go b/desktop/internal/workbench/app.go index 8b033cef9..806f09972 100644 --- a/desktop/internal/workbench/app.go +++ b/desktop/internal/workbench/app.go @@ -234,6 +234,11 @@ type Kernel interface { RemoteRunWatch(ctx context.Context, sessionID, root string, excludeNames []string, events core.RemoteWatchEvents) error RemoteTerminalWrite(ctx context.Context, sessionID string, terminalID uint64, data []byte) (bool, error) RemoteTerminalResize(ctx context.Context, sessionID string, terminalID uint64, columns, rows uint16) error + RemoteStartForward(ctx context.Context, sessionID string, target core.RemoteForwardTarget) (core.RemoteForward, bool, error) + RemoteStopForward(ctx context.Context, sessionID string, id uint64) (bool, error) + RemoteForwards(ctx context.Context, sessionID string) ([]core.RemoteForward, error) + RemoteListeningPorts(ctx context.Context, sessionID string) ([]core.RemoteListeningPort, error) + RemoteParseForwardAddress(ctx context.Context, text string) (core.RemoteForwardAddress, error) GitCreateTag(ctx context.Context, root, name, revision, message string) error GitRebasePreview(ctx context.Context, root, base string) (core.RebasePreview, error) GitRebaseStart(ctx context.Context, root string, preview core.RebasePreview, steps []core.RebaseStep) (*core.RebaseSession, error) @@ -1826,6 +1831,7 @@ func (a *App) disposeProject(p *project) { a.problems.reset() a.toolchainRoot.Store(nil) a.project = nil + a.chrome.setRemote(false) a.ideAPISetProject(nil) a.focus = focusTarget{} a.dnd.tool.Cancel() diff --git a/desktop/internal/workbench/catalog.go b/desktop/internal/workbench/catalog.go index 98492289e..88294586d 100644 --- a/desktop/internal/workbench/catalog.go +++ b/desktop/internal/workbench/catalog.go @@ -164,6 +164,10 @@ const ( itemDebug = "debug" itemNotifications = "notifications" itemBackground = "background" + // itemPorts is the Ports tool window of a remote workspace (remote_ports.go). It is in the + // catalog of every window so its place is kept, but it is shown only in a remote workspace + // (chromeState.apply). + itemPorts = "ports" // itemToolWindows is the "…" button that lists the stripe buttons the user hid. It is in // the catalog so it can be moved like any stripe button, but it is shown only while a // button is hidden (chromeState.apply). @@ -212,6 +216,9 @@ type item struct { // vcs is the plugin version control provider whose window the item shows (vcs.go); nil for // any other item. vcs *vcsWindow + // remote reports that the item exists only in a remote workspace: in any other window its + // button is left out, its tool window does not open and no command shows it. + remote bool } // stripeLucideStroke is the stroke, in Lucide's 24 unit view box, of a Lucide icon drawn in a @@ -247,6 +254,7 @@ var catalog = []item{ {id: itemTests, zone: zoneBottomLeft, icon: stripeLucide(icons.CircleCheck), label: func(m *i18n.Messages) string { return m.Tools.Tests }, panel: true}, {id: itemSecurity, zone: zoneBottomLeft, icon: stripeLucide(icons.ShieldCheck), label: func(m *i18n.Messages) string { return m.Tools.Security }, panel: true}, {id: itemDebug, zone: zoneBottomLeft, icon: &toolicons.Debug, label: func(m *i18n.Messages) string { return m.Tools.Debug }, panel: true}, + {id: itemPorts, zone: zoneBottomLeft, icon: stripeLucide(icons.ArrowLeftRight), label: func(m *i18n.Messages) string { return m.Tools.Ports }, panel: true, remote: true}, {id: itemBuild, zone: zoneRightTop, icon: &toolicons.Build, label: func(m *i18n.Messages) string { return m.Tools.Build }, panel: true}, {id: itemNotifications, zone: zoneRightTop, icon: &toolicons.Notifications, label: func(m *i18n.Messages) string { return m.Tools.Notifications }, panel: true}, @@ -313,6 +321,9 @@ type chromeState struct { hiddenMark []bool // open is the catalog index of the open tool window of each slot, -1 for none. open [slotCount]int + // remote is set while the window's project is a remote workspace, whose items (item.remote) + // are shown only then. + remote bool // ids is the identity each button was declared with in the last paint, which the drag // maps its source back to a catalog index by. @@ -438,7 +449,8 @@ func defaultLayout() core.ChromeLayout { // skipped; the kernel never returns them. A hidden button keeps its zone but is left out of // the zone's shown buttons, and so is the "…" button while no button is hidden: it would list // nothing. An open item that is not a tool window, such as the background button an earlier -// layout saved as open, takes no slot. +// layout saved as open, takes no slot. An item of a remote workspace keeps its zone outside +// one but is neither shown, listed as hidden nor open. func (c *chromeState) apply(layout core.ChromeLayout) { c.layout = layout for z := range c.items { @@ -466,6 +478,9 @@ func (c *chromeState) apply(layout core.ChromeLayout) { continue } c.zones[index] = z + if !c.present(index) { + continue + } if c.hiddenMark[index] { c.hidden = append(c.hidden, index) continue @@ -480,7 +495,7 @@ func (c *chromeState) apply(layout core.ChromeLayout) { } for _, id := range layout.Open { index, known := c.index[id] - if !known || !c.catalog[index].panel { + if !known || !c.catalog[index].panel || !c.present(index) { continue } if s, ok := c.zoneOf(index).slot(); ok { @@ -489,6 +504,20 @@ func (c *chromeState) apply(layout core.ChromeLayout) { } } +// present reports whether catalog item index exists in the window now: an item of a remote +// workspace exists only while the project is one. +func (c *chromeState) present(index int) bool { return c.remote || !c.catalog[index].remote } + +// setRemote shows the items of a remote workspace while remote is set, and leaves them out +// otherwise, keeping the arrangement. +func (c *chromeState) setRemote(remote bool) { + if c.remote == remote { + return + } + c.remote = remote + c.apply(c.layout) +} + // zoneOf returns the zone catalog item index sits in now, whether its button is shown or // hidden. func (c *chromeState) zoneOf(index int) zone { return c.zones[index] } diff --git a/desktop/internal/workbench/chrome_view.go b/desktop/internal/workbench/chrome_view.go index f4fbfa3d7..e9bb84ee3 100644 --- a/desktop/internal/workbench/chrome_view.go +++ b/desktop/internal/workbench/chrome_view.go @@ -519,6 +519,7 @@ func (a *App) statusBar(c ui.C) { ui.Row(c).FillWidth().Height(statusBarHeight).Shrink(0).Background(a.chromeFill()). Items(ui.Center).PadX(chromeEdge).Children(func() { a.remoteStatus(c) + a.remotePortsStatusItem(c) a.statusPathView(c) zone := ui.Row(c).Items(ui.Center).Gap(chromeStatusGap).Children(func() { for _, i := range a.chrome.items[zoneStatus] { diff --git a/desktop/internal/workbench/commands.go b/desktop/internal/workbench/commands.go index 139ecedb4..9870556ab 100644 --- a/desktop/internal/workbench/commands.go +++ b/desktop/internal/workbench/commands.go @@ -164,7 +164,7 @@ func (a *App) commands() []command { // Every tool window, plugin ones included, can be shown by name. for index, it := range a.chrome.catalog { - if !it.panel { + if !it.panel || !a.chrome.present(index) { continue } id := it.id diff --git a/desktop/internal/workbench/remote_ports.go b/desktop/internal/workbench/remote_ports.go new file mode 100644 index 000000000..6fd7daab3 --- /dev/null +++ b/desktop/internal/workbench/remote_ports.go @@ -0,0 +1,851 @@ +package workbench + +import ( + "context" + "encoding/json" + "errors" + "net" + "net/netip" + "slices" + "strconv" + "strings" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/ui" +) + +// This file is the Ports tool window of a remote workspace (#2231 R1): the TCP ports listening on +// the host, the ports the user added by hand, and the forwards Core runs to them over the +// workspace's session. Nothing is forwarded until the user asks: the window only lists the ports, +// and the user chooses which to forward and on which local port. A forward listens on this +// computer's loopback address only (S27), and the host never reaches back through it (S29); a +// target outside the host's loopback interface is forwarded only after the user confirms it (S28). +// Forwards belong to the session: when it ends, Core stops them, and the window shows the ports +// unforwarded again. +// +// A port is added by typing it alone, as host:port or as a URL; Core reads the address +// (remote.parseForwardAddress), and the row keeps a URL's scheme and path, to show the row as typed +// and to open and copy the forwarded address the same way. Each row shows the address the host +// serves the port on, its IP address included. +// +// The window reads the host's listening ports and the session's forwards while it is shown, every +// remotePortsInterval, and stops reading once it is hidden; nothing reads them in the background. + +const ( + // remotePortsInterval is the pause between two readings of the shown window. + remotePortsInterval = 3 * time.Second + // remotePortsTimeout bounds one reading, and one start or stop of a forward. + remotePortsTimeout = 15 * time.Second +) + +// remotePortKey names a row of the window: a port of the host's own loopback address, which a +// server listening on every interface also serves, has host ""; a port bound to one other address +// of the host, another loopback address such as 127.0.0.2 included, has that address. +type remotePortKey struct { + host string + port uint16 +} + +// remotePortHost is the row host of address, as remotePortKey keeps it: "" for localhost, +// 127.0.0.1, ::1 and the every-interface addresses, the canonical text of any other IP address, +// and any other name in lower case. +func remotePortHost(address string) string { + address = strings.TrimSuffix(strings.TrimPrefix(address, "["), "]") + if ip, err := netip.ParseAddr(address); err == nil { + ip = ip.Unmap() + if ip.IsUnspecified() || ip == netip.AddrFrom4([4]byte{127, 0, 0, 1}) || ip == netip.IPv6Loopback() { + return "" + } + return ip.String() + } + address = strings.ToLower(address) + if address == "localhost" { + return "" + } + return address +} + +// forwardKey is the row of forward, by the target Core forwards to. +func forwardKey(forward core.RemoteForward) remotePortKey { + return remotePortKey{host: remotePortHost(forward.TargetHost), port: forward.TargetPort} +} + +// remotePortAdded is a port the user added, as Core read the address typed: host is the host as +// typed, localhost for a port alone, and scheme and path are the URL's, "" for an address that is +// not a URL and for a URL without a path. The same row typed again replaces them. +type remotePortAdded struct { + key remotePortKey + host string + scheme string + path string +} + +// remotePortRow is one row of the window. +type remotePortRow struct { + key remotePortKey + // listening holds the host's listening sockets of the row, empty for a port that only the + // user added. + listening []core.RemoteListeningPort + // added is the address the user added the port with, nil for a port the user did not add. + added *remotePortAdded + // forward is the row's running forward, nil while there is none. + forward *core.RemoteForward +} + +// target is the host the row's forward is started to: the row's own address, or the loopback +// address of the family the host's server listens on, or the host typed for a port added by hand, +// or the target of the row's running forward. +func (row remotePortRow) target() string { + if row.key.host != "" { + return row.key.host + } + for _, port := range row.listening { + if ip, err := netip.ParseAddr(port.Address); err == nil && ip.Unmap().Is4() { + return "127.0.0.1" + } + } + switch { + case len(row.listening) > 0: + return "::1" + case row.added != nil: + return row.added.host + case row.forward != nil: + return row.forward.TargetHost + } + return "localhost" +} + +// addresses are the distinct addresses the host listens on for the row, as address:port, IPv4 +// first and otherwise in the host's order. +func (row remotePortRow) addresses() []string { + var v4, v6 []string + port := strconv.Itoa(int(row.key.port)) + for _, listening := range row.listening { + address := net.JoinHostPort(listening.Address, port) + if slices.Contains(v4, address) || slices.Contains(v6, address) { + continue + } + if ip, err := netip.ParseAddr(listening.Address); err == nil && !ip.Unmap().Is4() { + v6 = append(v6, address) + } else { + v4 = append(v4, address) + } + } + return append(v4, v6...) +} + +// url reports whether the user added the row as a URL. +func (row remotePortRow) url() bool { + return row.added != nil && row.added.scheme != "" +} + +// browserURL is the address Open in Browser opens for the row's forward: the URL the user added, +// with this computer's local address in place of the host's, or http on the local address. ok is +// false for a row without a forward and for a URL a browser does not open, such as ws or postgres. +func (row remotePortRow) browserURL() (url string, ok bool) { + if row.forward == nil { + return "", false + } + if !row.url() { + return "http://" + remotePortAddress(*row.forward), true + } + if row.added.scheme != "http" && row.added.scheme != "https" { + return "", false + } + return row.added.scheme + "://" + remotePortAddress(*row.forward) + row.added.path, true +} + +// copyText is what Copy Local Address copies for the row's forward: the URL the user added, with +// this computer's local address in place of the host's, or the local address as host:port. +func (row remotePortRow) copyText() string { + switch { + case row.forward == nil: + return "" + case row.url(): + return row.added.scheme + "://" + remotePortAddress(*row.forward) + row.added.path + } + return remotePortAddress(*row.forward) +} + +// remotePortsBusy is what runs for a row. +type remotePortsBusy int + +const ( + remotePortForwarding remotePortsBusy = iota + 1 + remotePortStopping +) + +// remotePortConfirm is a forward that waits for the user to confirm its target (S28). +type remotePortConfirm struct { + key remotePortKey + host string +} + +// remotePorts is the state of the Ports window of a remote workspace (remoteProject.ports). +type remotePorts struct { + // listening is the host's last listing of its listening ports; listed is set once one arrived + // over the current session. readFailed is why the last reading failed, "" when it did not. + listening []core.RemoteListeningPort + listed bool + readFailed string + // forwards are the session's running forwards by id. + forwards []core.RemoteForward + // manual are the ports the user added, kept while the workspace is open, across sessions. + manual []remotePortAdded + // localPorts are the local ports the user chose for rows, kept like manual; a row without one + // is forwarded on its own port number. + localPorts map[remotePortKey]uint16 + // local is the row whose local port the user is choosing, nil while none is; localField is the + // port typed for it, and localInvalid is set when that text is not a port. + local *remotePortKey + localOpen bool + localField ui.Field + localInvalid bool + // busy is what runs for a row, and failed why the last start or stop of a row failed. + busy map[remotePortKey]remotePortsBusy + failed map[remotePortKey]string + // stoppingAll is set while Stop All Forwards runs. + stoppingAll bool + // confirm is the forward waiting for the user's confirmation, nil while none does. + confirm *remotePortConfirm + confirmOpen bool + // notice is the window's message about the last action, such as the forward limit, "" for none. + notice string + // add is the field a port is typed into; adding is set while Core reads the address typed, and + // addRefused is the reason Core refused the last one, "" when it did not. + add ui.Field + adding bool + addRefused string + // reading is set while a reading runs or the next one is scheduled; shown is set each time the + // window is drawn, so a reading that finds it unset since the last one stops reading. stopTimer + // stops the scheduled reading; timer tells its callback apart from a later schedule's. + reading bool + shown bool + stopTimer func() bool + timer uint64 +} + +// reset forgets what belonged to the ended session: its forwards, what ran for them and the +// listing it read. The ports the user added stay. +func (ports *remotePorts) reset() { + ports.stopReading() + ports.listening, ports.listed, ports.readFailed = nil, false, "" + ports.forwards = nil + clear(ports.busy) + clear(ports.failed) + ports.stoppingAll = false + ports.confirm, ports.confirmOpen = nil, false + ports.local, ports.localOpen, ports.localInvalid = nil, false, false + ports.notice = "" +} + +// localPort is the local port a forward of row key asks for: the one the user chose, or the +// host's port number, so the address reads as it does on the host. +func (ports *remotePorts) localPort(key remotePortKey) uint16 { + if port := ports.localPorts[key]; port != 0 { + return port + } + return key.port +} + +// stopReading stops the scheduled reading; a callback already queued finds its token outdated. +func (ports *remotePorts) stopReading() { + if ports.stopTimer != nil { + ports.stopTimer() + ports.stopTimer = nil + } + ports.timer++ + ports.reading = false +} + +// rows are the window's rows: the listening ports, the ports added by hand and the forwards, by +// port and then by address. +func (ports *remotePorts) rows() []remotePortRow { + index := map[remotePortKey]int{} + var rows []remotePortRow + row := func(key remotePortKey) *remotePortRow { + at, known := index[key] + if !known { + at = len(rows) + index[key] = at + rows = append(rows, remotePortRow{key: key}) + } + return &rows[at] + } + for _, port := range ports.listening { + r := row(remotePortKey{host: remotePortHost(port.Address), port: port.Port}) + r.listening = append(r.listening, port) + } + for _, added := range ports.manual { + // A copy: a row outlives a later change of ports.manual in the callbacks it is given to. + row(added.key).added = &added + } + for i := range ports.forwards { + r := row(forwardKey(ports.forwards[i])) + if r.forward == nil { + r.forward = &ports.forwards[i] + } + } + slices.SortFunc(rows, func(x, y remotePortRow) int { + if x.key.port != y.key.port { + return int(x.key.port) - int(y.key.port) + } + return strings.Compare(x.key.host, y.key.host) + }) + return rows +} + +// row is the window's row key, and whether there is one. +func (ports *remotePorts) row(key remotePortKey) (remotePortRow, bool) { + for _, row := range ports.rows() { + if row.key == key { + return row, true + } + } + return remotePortRow{key: key}, false +} + +// putAdded records a port the user added, replacing the address its row was added with before. +func (ports *remotePorts) putAdded(added remotePortAdded) { + for i := range ports.manual { + if ports.manual[i].key == added.key { + ports.manual[i] = added + return + } + } + ports.manual = append(ports.manual, added) +} + +// putForward records forward as running, replacing the one of the same id. +func (ports *remotePorts) putForward(forward core.RemoteForward) { + for i := range ports.forwards { + if ports.forwards[i].ID == forward.ID { + ports.forwards[i] = forward + return + } + } + ports.forwards = append(ports.forwards, forward) + slices.SortFunc(ports.forwards, func(x, y core.RemoteForward) int { + switch { + case x.ID < y.ID: + return -1 + case x.ID > y.ID: + return 1 + } + return 0 + }) +} + +// dropForward forgets the forward id. +func (ports *remotePorts) dropForward(id uint64) { + ports.forwards = slices.DeleteFunc(ports.forwards, func(forward core.RemoteForward) bool { return forward.ID == id }) +} + +// setBusy records what runs for key, or that nothing does for 0. +func (ports *remotePorts) setBusy(key remotePortKey, busy remotePortsBusy) { + if busy == 0 { + delete(ports.busy, key) + return + } + if ports.busy == nil { + ports.busy = map[remotePortKey]remotePortsBusy{} + } + ports.busy[key] = busy +} + +// setFailed records why the last action of key failed, or that it did not for "". +func (ports *remotePorts) setFailed(key remotePortKey, reason string) { + if reason == "" { + delete(ports.failed, key) + return + } + if ports.failed == nil { + ports.failed = map[remotePortKey]string{} + } + ports.failed[key] = reason +} + +// remotePortsReason is the text a failure of the window shows: Core's summary, which is meant for +// the user's diagnostics, or the error's own text. +func remotePortsReason(err error) string { + var coreErr *core.Error + if errors.As(err, &coreErr) && coreErr.Message != "" { + return coreErr.Message + } + return err.Error() +} + +// remotePortsLimit is the maximum the details of a CodeForwardLimitReached failure carry, or +// fallback when they carry none. +func remotePortsLimit(err error, fallback int) int { + var coreErr *core.Error + if !errors.As(err, &coreErr) { + return fallback + } + var details struct { + Maximum int `json:"maximum"` + } + if json.Unmarshal([]byte(coreErr.Details), &details) != nil || details.Maximum <= 0 { + return fallback + } + return details.Maximum +} + +// remotePortsCode is the code of a Core failure, "" for any other error. +func remotePortsCode(err error) core.ErrorCode { + var coreErr *core.Error + if errors.As(err, &coreErr) { + return coreErr.Code + } + return "" +} + +// showRemotePorts is called each time the Ports window of p is drawn: it starts reading while the +// workspace has a session and no reading runs. +func (a *App) showRemotePorts(p *project) { + r := p.remote + if r == nil || r.closed { + return + } + r.ports.shown = true + if r.ports.reading || r.session == "" { + return + } + a.readRemotePorts(p) +} + +// readRemotePorts reads the host's listening ports and the session's forwards, and schedules the +// next reading while the window stays shown. A closed connection is lost; another failure is +// shown in the window and logged once until a reading succeeds again. +func (a *App) readRemotePorts(p *project) { + r := p.remote + ports := &r.ports + ports.reading, ports.shown = true, false + session, kernel := r.session, a.kernel + a.background(p, remotePortsTimeout, func(ctx context.Context) func(*App) { + listening, listenErr := kernel.RemoteListeningPorts(ctx, session) + forwards, forwardsErr := kernel.RemoteForwards(ctx, session) + return func(a *App) { + if r.closed || r.session != session || !ports.reading { + // log-exempt: 用户取消:工作区已关闭、会话已结束或端口读取已停止,这次读取的结果不再适用。 + return + } + for _, err := range []error{listenErr, forwardsErr} { + if err != nil && remoteConnectionClosed(err) { + a.loseRemote(p, session, err) + return + } + } + if forwardsErr == nil { + ports.forwards = forwards + } + if listenErr == nil { + ports.listening, ports.listed = listening, true + } + if err := errors.Join(listenErr, forwardsErr); err != nil { + if ports.readFailed == "" { + a.backgroundFailed("remote_ports_read", remoteLogError(err)) + } + ports.readFailed = remotePortsReason(err) + } else { + ports.readFailed = "" + } + a.scheduleRemotePorts(p) + } + }) +} + +// scheduleRemotePorts reads again after remotePortsInterval if the window is open and was drawn +// meanwhile; it stops reading otherwise, until the window is shown again. +func (a *App) scheduleRemotePorts(p *project) { + r := p.remote + ports := &r.ports + if ports.stopTimer != nil { + ports.stopTimer() + } + ports.timer++ + token := ports.timer + ports.stopTimer = a.remoteAfterFunc(remotePortsInterval, func() { + a.post(func(a *App) { + if a.project != p || r.closed || ports.timer != token { + return + } + ports.stopTimer = nil + if !ports.shown || r.session == "" || !a.chrome.isOpen(catalogIndex[itemPorts]) { + ports.reading = false + return + } + a.readRemotePorts(p) + }) + }) +} + +// forwardRemotePort starts a forward of row key to host over p's session, on the row's local port +// (remotePorts.localPort); when another program holds it, Core listens on a free port and reports +// the change. confirmed records that the user confirmed a target outside the host's loopback +// interface; without it Core refuses such a target and the window asks. +func (a *App) forwardRemotePort(p *project, key remotePortKey, host string, confirmed bool, surface actionSurface) { + r := p.remote + if r == nil || r.closed || r.session == "" || r.ports.busy[key] != 0 { + // log-exempt: 非用户操作:没有会话或这一行已有操作在进行,按钮此时不可用。 + return + } + a.performed("remote.ports.forward", surface) + ports := &r.ports + ports.setBusy(key, remotePortForwarding) + ports.setFailed(key, "") + ports.notice = "" + session, kernel := r.session, a.kernel + target := core.RemoteForwardTarget{Host: host, Port: key.port, LocalPort: ports.localPort(key), AllowNonLoopback: confirmed} + a.background(p, remotePortsTimeout, func(ctx context.Context) func(*App) { + forward, _, err := kernel.RemoteStartForward(ctx, session, target) + return func(a *App) { + if r.closed || r.session != session { + // log-exempt: 用户取消:工作区已关闭或会话已结束,会话结束时 Core 已停止它的转发。 + return + } + ports.setBusy(key, 0) + a.forwardStarted(p, session, key, host, forward, err) + } + }) +} + +// forwardStarted records how starting the forward of row key to host over session ended. +func (a *App) forwardStarted(p *project, session string, key remotePortKey, host string, forward core.RemoteForward, err error) { + ports := &p.remote.ports + switch code := remotePortsCode(err); { + case err == nil: + ports.putForward(forward) + case code == core.CodeForwardTargetNotConfirmed: + a.operationRejected("remote_port_forward", "target_not_confirmed") + ports.confirm, ports.confirmOpen = &remotePortConfirm{key: key, host: host}, true + case code == core.CodeConnectionClosed: + a.loseRemote(p, session, err) + case code == core.CodeForwardLimitReached: + a.operationFailed("remote_port_forward", remoteLogError(err)) + ports.notice = i18n.SharedFormat(a.language(), "desktop.remote.ports.limit", + map[string]string{"maximum": strconv.Itoa(remotePortsLimit(err, len(ports.forwards)))}) + case code == core.CodeInvalidRequest: + a.operationFailed("remote_port_forward", remoteLogError(err)) + ports.setFailed(key, i18n.Shared(a.language(), "desktop.remote.ports.invalidTarget")) + default: + a.operationFailed("remote_port_forward", remoteLogError(err)) + ports.setFailed(key, remotePortsReason(err)) + } +} + +// chooseRemoteLocalPort asks for the local port of row key, starting from the one it uses now. +func (a *App) chooseRemoteLocalPort(p *project, key remotePortKey, surface actionSurface) { + r := p.remote + if r == nil || r.closed || r.session == "" || r.ports.busy[key] != 0 { + // log-exempt: 非用户操作:没有会话或这一行已有操作在进行,菜单项此时不可用。 + return + } + a.performed("remote.ports.localPort", surface) + ports := &r.ports + port := ports.localPort(key) + for _, forward := range ports.forwards { + if forwardKey(forward) == key { + port = forward.LocalPort + break + } + } + ports.local, ports.localOpen, ports.localInvalid = &key, true, false + ports.localField.SetText(strconv.Itoa(int(port))) +} + +// applyRemoteLocalPort forwards the row whose local port the user chose on the typed port: it +// starts the forward of a row that has none, and moves a running one, which Core keeps on the +// local port it listens on, by stopping it and starting it again. A forward already on that port +// stays as it is. +func (a *App) applyRemoteLocalPort(p *project) { + ports := &p.remote.ports + if ports.local == nil { + return + } + key := *ports.local + n, err := strconv.ParseUint(strings.TrimSpace(ports.localField.Text()), 10, 16) + if err != nil || n == 0 { + a.operationRejected("remote_port_local", "invalid_port") + ports.localInvalid = true + return + } + port := uint16(n) + ports.local, ports.localOpen, ports.localInvalid = nil, false, false + if ports.localPorts == nil { + ports.localPorts = map[remotePortKey]uint16{} + } + ports.localPorts[key] = port + switch row, ok := ports.row(key); { + case !ok: + case row.forward == nil: + a.forwardRemotePort(p, key, row.target(), false, surfaceButton) + case row.forward.LocalPort != port: + a.moveRemotePort(p, key, *row.forward, port) + } +} + +// moveRemotePort stops forward of row key and starts it again on local port. The target was +// confirmed when the forward started, so it is not asked about again. +func (a *App) moveRemotePort(p *project, key remotePortKey, forward core.RemoteForward, port uint16) { + r := p.remote + if r.closed || r.session == "" || r.ports.busy[key] != 0 { + // log-exempt: 非用户操作:没有会话或这一行已有操作在进行,按钮此时不可用。 + return + } + a.performed("remote.ports.move", surfaceButton) + ports := &r.ports + ports.setBusy(key, remotePortForwarding) + ports.setFailed(key, "") + ports.notice = "" + session, kernel := r.session, a.kernel + target := core.RemoteForwardTarget{Host: forward.TargetHost, Port: forward.TargetPort, LocalPort: port, + AllowNonLoopback: !forward.LoopbackTarget} + a.background(p, remotePortsTimeout, func(ctx context.Context) func(*App) { + _, stopErr := kernel.RemoteStopForward(ctx, session, forward.ID) + var started core.RemoteForward + var startErr error + if stopErr == nil { + started, _, startErr = kernel.RemoteStartForward(ctx, session, target) + } + return func(a *App) { + if r.closed || r.session != session { + // log-exempt: 用户取消:工作区已关闭或会话已结束,会话结束时 Core 已停止它的转发。 + return + } + ports.setBusy(key, 0) + switch { + case stopErr != nil && remoteConnectionClosed(stopErr): + a.loseRemote(p, session, stopErr) + case stopErr != nil: + a.operationFailed("remote_port_stop", remoteLogError(stopErr)) + ports.setFailed(key, remotePortsReason(stopErr)) + default: + ports.dropForward(forward.ID) + a.forwardStarted(p, session, key, forward.TargetHost, started, startErr) + } + } + }) +} + +// confirmRemotePort forwards the target waiting for confirmation, which the user confirmed. +func (a *App) confirmRemotePort(p *project) { + ports := &p.remote.ports + pending := ports.confirm + ports.confirm, ports.confirmOpen = nil, false + if pending == nil { + return + } + a.forwardRemotePort(p, pending.key, pending.host, true, surfaceButton) +} + +// stopRemotePort stops the forward of row key. +func (a *App) stopRemotePort(p *project, key remotePortKey, id uint64, surface actionSurface) { + r := p.remote + if r == nil || r.closed || r.session == "" || r.ports.busy[key] != 0 { + // log-exempt: 非用户操作:没有会话或这一行已有操作在进行,按钮此时不可用。 + return + } + a.performed("remote.ports.stop", surface) + ports := &r.ports + ports.setBusy(key, remotePortStopping) + ports.setFailed(key, "") + session, kernel := r.session, a.kernel + a.background(p, remotePortsTimeout, func(ctx context.Context) func(*App) { + _, err := kernel.RemoteStopForward(ctx, session, id) + return func(a *App) { + if r.closed || r.session != session { + // log-exempt: 用户取消:工作区已关闭或会话已结束,会话结束时 Core 已停止它的转发。 + return + } + ports.setBusy(key, 0) + switch { + case err == nil: + // A forward Core no longer knows has stopped as well. + ports.dropForward(id) + case remoteConnectionClosed(err): + a.loseRemote(p, session, err) + default: + a.operationFailed("remote_port_stop", remoteLogError(err)) + ports.setFailed(key, remotePortsReason(err)) + } + } + }) +} + +// stopAllRemotePorts stops every forward of p's session, then reads the forwards again. +func (a *App) stopAllRemotePorts(p *project, surface actionSurface) { + r := p.remote + if r == nil || r.closed || r.session == "" || r.ports.stoppingAll || len(r.ports.forwards) == 0 { + // log-exempt: 非用户操作:没有会话、没有转发或停止全部已在进行,按钮此时不可用。 + return + } + a.performed("remote.ports.stopAll", surface) + ports := &r.ports + ports.stoppingAll = true + ids := make([]uint64, len(ports.forwards)) + for i, forward := range ports.forwards { + ids[i] = forward.ID + ports.setBusy(forwardKey(forward), remotePortStopping) + } + session, kernel := r.session, a.kernel + a.background(p, remotePortsTimeout, func(ctx context.Context) func(*App) { + var stopErr error + for _, id := range ids { + if _, err := kernel.RemoteStopForward(ctx, session, id); err != nil { + stopErr = err + break + } + } + forwards, listErr := kernel.RemoteForwards(ctx, session) + return func(a *App) { + if r.closed || r.session != session { + // log-exempt: 用户取消:工作区已关闭或会话已结束,会话结束时 Core 已停止它的转发。 + return + } + ports.stoppingAll = false + clear(ports.busy) + err := errors.Join(stopErr, listErr) + switch { + case err != nil && (remoteConnectionClosed(stopErr) || remoteConnectionClosed(listErr)): + a.loseRemote(p, session, err) + return + case err != nil: + a.operationFailed("remote_port_stop_all", remoteLogError(err)) + ports.notice = i18n.SharedFormat(a.language(), "desktop.remote.ports.statusFailed", + map[string]string{"reason": remotePortsReason(err)}) + } + if listErr == nil { + ports.forwards = forwards + } + } + }) +} + +// addRemotePort has Core read the address typed into the window — a port, host:port or a URL — +// then adds its port and forwards it. A refused address is shown under the field, which keeps the +// text so it can be corrected. +func (a *App) addRemotePort(p *project, surface actionSurface) { + r := p.remote + if r == nil || r.closed || r.ports.adding { + // log-exempt: 非用户操作:工作区已关闭或上一个地址正在解析,按钮此时不可用。 + return + } + ports := &r.ports + text := strings.TrimSpace(ports.add.Text()) + if text == "" { + // log-exempt: 非用户操作:输入为空,按钮此时不可用。 + return + } + ports.adding = true + kernel := a.kernel + a.background(p, remotePortsTimeout, func(ctx context.Context) func(*App) { + address, err := kernel.RemoteParseForwardAddress(ctx, text) + return func(a *App) { + ports.adding = false + if r.closed { + // log-exempt: 用户取消:工作区已关闭,添加的端口随窗口一起丢弃。 + return + } + if _, reason, refused := core.RemoteConnectionFieldError(err); refused { + a.operationRejected("remote_port_add", remotePortsAddRejection(reason)) + ports.addRefused = reason + return + } + if err != nil { + a.operationFailed("remote_port_add", remoteLogError(err)) + ports.notice = i18n.SharedFormat(a.language(), "desktop.remote.ports.statusFailed", + map[string]string{"reason": remotePortsReason(err)}) + return + } + ports.addRefused = "" + if strings.TrimSpace(ports.add.Text()) == text { + ports.add.SetText("") + } + a.addRemoteAddress(p, address, surface) + } + }) +} + +// remotePortsAddRejections are the log reasons of the reasons Core refuses an address typed into +// the window with (remote.parseForwardAddress); a reason Core adds later is logged as +// invalid_address. +var remotePortsAddRejections = map[string]string{ + "empty": "empty_address", + "tooLong": "address_too_long", + "malformed": "malformed_address", + "scheme": "invalid_scheme", + "credentials": "credentials_in_address", + "host": "invalid_host", + "port": "invalid_port", +} + +// remotePortsAddRejection is the log reason of reason, a fixed token whatever Core sends. +func remotePortsAddRejection(reason string) string { + if token, known := remotePortsAddRejections[reason]; known { + return token + } + return "invalid_address" +} + +// addRemoteAddress adds the port of address, which Core read, and forwards it unless it is +// forwarded already. +func (a *App) addRemoteAddress(p *project, address core.RemoteForwardAddress, surface actionSurface) { + ports := &p.remote.ports + key := remotePortKey{host: remotePortHost(address.TargetHost), port: address.TargetPort} + ports.putAdded(remotePortAdded{key: key, host: address.TargetHost, scheme: address.Scheme, path: address.Path}) + row, _ := ports.row(key) + if row.forward != nil { + // log-exempt: 非用户操作:这个端口已在转发,添加只让它出现在列表里,或换成新输入的网址。 + return + } + a.forwardRemotePort(p, key, row.target(), false, surface) +} + +// removeRemotePort removes a port the user added from the window. +func (a *App) removeRemotePort(p *project, key remotePortKey) { + ports := &p.remote.ports + a.performed("remote.ports.remove", surfaceContextMenu) + ports.manual = slices.DeleteFunc(ports.manual, func(added remotePortAdded) bool { return added.key == key }) + ports.setFailed(key, "") +} + +// remotePortAddress is the local address of forward, as host:port. +func remotePortAddress(forward core.RemoteForward) string { + return net.JoinHostPort(forward.LocalHost, strconv.Itoa(int(forward.LocalPort))) +} + +// openRemotePort opens the forward of row in the system browser (remotePortRow.browserURL). +func (a *App) openRemotePort(row remotePortRow, surface actionSurface) { + url, ok := row.browserURL() + if !ok { + // log-exempt: 非用户操作:这一行没有转发,或它的网址不是浏览器打开的协议,按钮此时不显示。 + return + } + a.performed("remote.ports.open", surface) + if err := openURL(url); err != nil { + // The error can name the URL, whose path and query the user typed and which may hold a + // token, so the log keeps only that the browser did not open it; the notice shows the URL. + a.operationFailed("remote_port_open", errRemotePortOpen) + a.notifyError(a.text.Run.Ports.OpenFailed(url)) + } +} + +// errRemotePortOpen is what the log keeps of a forward's address the system did not open. +var errRemotePortOpen = errors.New("the system did not open the forwarded address") + +// copyRemotePort copies the local address of row's forward to the clipboard +// (remotePortRow.copyText). +func (a *App) copyRemotePort(row remotePortRow, surface actionSurface) { + if row.forward == nil { + // log-exempt: 非用户操作:这一行没有转发,按钮此时不显示。 + return + } + a.performed("remote.ports.copy", surface) + if err := app.SetClipboardText(row.copyText()); err != nil { + a.operationFailed("remote_port_copy", err) + } +} diff --git a/desktop/internal/workbench/remote_ports_test.go b/desktop/internal/workbench/remote_ports_test.go new file mode 100644 index 000000000..2d56b3993 --- /dev/null +++ b/desktop/internal/workbench/remote_ports_test.go @@ -0,0 +1,844 @@ +package workbench + +import ( + "context" + "errors" + "net" + "net/netip" + "net/url" + "slices" + "strconv" + "strings" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/vivaui/viva/gfx" +) + +// remoteHostPorts stands in for the host's listening ports (ports.listening) and for Core's +// forwards of each session, which it keeps as Core does: a target outside the host's loopback +// interface needs the user's confirmation (S28), the same target again is the running forward, a +// local port that is taken is replaced by a free one, and a session runs at most limit forwards +// when limit is set. +type remoteHostPorts struct { + listening []core.RemoteListeningPort + // listenErr fails every listing while it is set; listings counts the listings asked for. + listenErr error + listings int + forwards map[string][]core.RemoteForward + next uint64 + limit int + // taken are the local ports other programs of this computer listen on. + taken map[uint16]bool + // starts are the targets forwards were asked for, and stops the forwards stopped. + starts []core.RemoteForwardTarget + stops []uint64 +} + +func (k *remoteHostKernel) RemoteListeningPorts(context.Context, string) ([]core.RemoteListeningPort, error) { + k.mu.Lock() + defer k.mu.Unlock() + k.ports.listings++ + if err := k.ports.listenErr; err != nil { + return nil, err + } + return slices.Clone(k.ports.listening), nil +} + +func (k *remoteHostKernel) RemoteForwards(_ context.Context, session string) ([]core.RemoteForward, error) { + k.mu.Lock() + defer k.mu.Unlock() + return slices.Clone(k.ports.forwards[session]), nil +} + +func (k *remoteHostKernel) RemoteStartForward(_ context.Context, session string, target core.RemoteForwardTarget) (core.RemoteForward, bool, error) { + k.mu.Lock() + defer k.mu.Unlock() + p := &k.ports + p.starts = append(p.starts, target) + host, loopback := target.Host, target.Host == "localhost" + if ip, err := netip.ParseAddr(host); err == nil { + ip = ip.Unmap() + switch { + case ip.IsUnspecified() && ip.Is4(): + ip = netip.AddrFrom4([4]byte{127, 0, 0, 1}) + case ip.IsUnspecified(): + ip = netip.IPv6Loopback() + } + host, loopback = ip.String(), ip.IsLoopback() + } + if !loopback && !target.AllowNonLoopback { + return core.RemoteForward{}, false, &core.Error{Command: "remote.startForward", Code: core.CodeForwardTargetNotConfirmed, Message: "not confirmed"} + } + for _, forward := range p.forwards[session] { + if forward.TargetHost == host && forward.TargetPort == target.Port { + return forward, false, nil + } + } + if p.limit > 0 && len(p.forwards[session]) >= p.limit { + return core.RemoteForward{}, false, &core.Error{Command: "remote.startForward", Code: core.CodeForwardLimitReached, + Message: "too many forwards", Details: `{"maximum":` + strconv.Itoa(p.limit) + `}`} + } + p.next++ + forward := core.RemoteForward{ID: p.next, LocalHost: "127.0.0.1", LocalPort: target.LocalPort, + TargetHost: host, TargetPort: target.Port, LoopbackTarget: loopback} + if requested := target.LocalPort; requested != 0 { + forward.RequestedLocalPort = &requested + } + if forward.LocalPort == 0 || p.taken[forward.LocalPort] || p.localInUse(forward.LocalPort) { + forward.LocalPortChanged = forward.LocalPort != 0 + forward.LocalPort = 40000 + uint16(p.next) + } + if p.forwards == nil { + p.forwards = map[string][]core.RemoteForward{} + } + p.forwards[session] = append(p.forwards[session], forward) + return forward, true, nil +} + +// localInUse reports whether a forward of any session listens on local port. +func (p *remoteHostPorts) localInUse(port uint16) bool { + for _, forwards := range p.forwards { + for _, forward := range forwards { + if forward.LocalPort == port { + return true + } + } + } + return false +} + +// RemoteParseForwardAddress reads text as Core does for what the tests type: a port alone on +// localhost, host:port, and a URL, whose port defaults by scheme and whose path keeps its query; a +// URL with a user name is refused as credentials, a URL without a port of a scheme that has no +// default as port, and any other text as malformed. +func (k *remoteHostKernel) RemoteParseForwardAddress(_ context.Context, text string) (core.RemoteForwardAddress, error) { + refuse := func(reason string) (core.RemoteForwardAddress, error) { + return core.RemoteForwardAddress{}, &core.Error{Command: "remote.parseForwardAddress", Code: core.CodeInvalidRequest, + Message: "the address is not valid", Details: `{"field":"text","reason":"` + reason + `"}`} + } + port := func(text string) (uint16, bool) { + n, err := strconv.ParseUint(text, 10, 16) + return uint16(n), err == nil && n != 0 + } + text = strings.TrimSpace(text) + if n, ok := port(text); ok { + return core.RemoteForwardAddress{TargetHost: "localhost", TargetPort: n}, nil + } + if strings.Contains(text, "://") { + u, err := url.Parse(text) + switch { + case err != nil || u.Hostname() == "": + return refuse("malformed") + case u.User != nil: + return refuse("credentials") + } + scheme, portText := strings.ToLower(u.Scheme), u.Port() + if portText == "" { + portText = map[string]string{"http": "80", "ws": "80", "https": "443", "wss": "443"}[scheme] + } + n, ok := port(portText) + if !ok { + return refuse("port") + } + path := u.RequestURI() + if path == "/" { + path = "" + } + return core.RemoteForwardAddress{TargetHost: strings.ToLower(u.Hostname()), TargetPort: n, Scheme: scheme, Path: path}, nil + } + host, portText, err := net.SplitHostPort(text) + n, ok := port(portText) + if err != nil || host == "" || !ok { + return refuse("malformed") + } + return core.RemoteForwardAddress{TargetHost: host, TargetPort: n}, nil +} + +func (k *remoteHostKernel) RemoteStopForward(_ context.Context, session string, id uint64) (bool, error) { + k.mu.Lock() + defer k.mu.Unlock() + p := &k.ports + p.stops = append(p.stops, id) + before := len(p.forwards[session]) + p.forwards[session] = slices.DeleteFunc(p.forwards[session], func(forward core.RemoteForward) bool { return forward.ID == id }) + return len(p.forwards[session]) < before, nil +} + +// takeAfter is the pending timer that waits d, which no longer is; the others stay pending. A +// workspace whose Ports window is open has its heartbeat and the window's next reading pending. +func (s *remoteTimers) takeAfter(t *testing.T, d time.Duration) *remoteTimer { + t.Helper() + s.mu.Lock() + defer s.mu.Unlock() + var found []*remoteTimer + for _, timer := range s.pending { + if !timer.stopped && timer.after == d { + found = append(found, timer) + } + } + if len(found) != 1 { + t.Fatalf("%d timers of %v pending, want one", len(found), d) + } + found[0].stopped = true + return found[0] +} + +// liveAfter counts the pending timers that wait d. +func (s *remoteTimers) liveAfter(d time.Duration) int { + s.mu.Lock() + defer s.mu.Unlock() + n := 0 + for _, timer := range s.pending { + if !timer.stopped && timer.after == d { + n++ + } + } + return n +} + +// fireAfter runs the pending timer that waits d and applies what it started. +func (h *harness) fireAfter(t *testing.T, timers *remoteTimers, d time.Duration) { + t.Helper() + timers.takeAfter(t, d).run() + h.settle() + h.settle() + h.settle() +} + +// openRemotePortsWindow opens the remote test workspace on a host listening on listening, shows +// its Ports window and waits for the window's first reading. +func (h *harness) openRemotePortsWindow(t *testing.T, k *remoteHostKernel, listening ...core.RemoteListeningPort) *project { + t.Helper() + k.set(func(k *remoteHostKernel) { k.ports.listening = listening }) + p := h.openRemoteTestProject(t) + h.app.openToolWindow(itemPorts) + h.redraw() + h.await("the Ports window's first reading", func() bool { return p.remote.ports.listed || p.remote.ports.readFailed != "" }) + h.settle() + return p +} + +// portRowControl is where the control named label of the Ports window's row remote, as its Remote +// Port column reads, was laid out in the last frame. +func (h *harness) portRowControl(remote, label string) gfx.Rect { + h.t.Helper() + bounds, ok := h.portRowHas(remote, label) + if !ok { + h.t.Fatalf("row %q has no control named %q", remote, label) + } + return bounds +} + +// portRowHas is where the control named label of the Ports window's row remote was laid out in the +// last frame, and whether the row has one. The row is the widest control named remote: the Remote +// Port cell of a long address is named after it too, for its tooltip. +func (h *harness) portRowHas(remote, label string) (gfx.Rect, bool) { + h.t.Helper() + hits := h.driver.Snapshot().Hits + var row *gfx.Hit + for i := range hits { + if hits[i].Label == remote && !hits[i].IsLabel && (row == nil || hits[i].Bounds.Width > row.Bounds.Width) { + row = &hits[i] + } + } + if row == nil { + h.t.Fatalf("no row %q is shown", remote) + return gfx.Rect{}, false + } + for _, hit := range hits { + if hit.Label == label && !hit.IsLabel && hit.Bounds.Y >= row.Bounds.Y && hit.Bounds.Y+hit.Bounds.Height <= row.Bounds.Y+row.Bounds.Height { + return hit.Bounds, true + } + } + return gfx.Rect{}, false +} + +// hasControl reports whether a control named label was laid out in the last frame. +func (h *harness) hasControl(label string) bool { + return slices.ContainsFunc(h.driver.Snapshot().Hits, func(hit gfx.Hit) bool { return hit.Label == label && !hit.IsLabel }) +} + +// remotePortKeys are the keys of rows, in order. +func remotePortKeys(rows []remotePortRow) []remotePortKey { + keys := make([]remotePortKey, len(rows)) + for i, row := range rows { + keys[i] = row.key + } + return keys +} + +// The Ports tool window exists only in a remote workspace: a local window neither shows its +// button nor lists it among the tool windows, and closing the workspace takes it away again. +func TestRemotePortsWindowIsOnlyInARemoteWorkspace(t *testing.T) { + h, _, _, _ := remoteWorkspaceHarness(t) + index := catalogIndex[itemPorts] + listed := func() bool { + return slices.ContainsFunc(h.app.commands(), func(c command) bool { return c.id == toolCommandPrefix+itemPorts }) + } + if h.app.chrome.present(index) || listed() { + t.Fatal("a window without a remote workspace offers the Ports window") + } + h.openRemoteTestProject(t) + h.settle() + if !h.app.chrome.present(index) || !listed() { + t.Fatal("the remote workspace does not offer the Ports window") + } + h.button(itemPorts) + + h.app.openToolWindow(itemPorts) + h.redraw() + h.app.closeProject() + h.settle() + if h.app.chrome.present(index) || h.app.chrome.isOpen(index) || listed() { + t.Fatal("the Ports window outlived the remote workspace") + } +} + +// The window lists the host's listening ports, one row for a server listening on every interface +// of both families, with its process; Forward forwards the row to the host's loopback address on +// the same local port, or a free one when that is taken, the row and the status bar show the +// local address and the count, and the count opens the window. +func TestRemotePortsListsAndForwardsTheHostsPorts(t *testing.T) { + h, k, _, logger := remoteWorkspaceHarness(t) + lang := h.app.language() + p := h.openRemotePortsWindow(t, k, + core.RemoteListeningPort{Address: "0.0.0.0", Port: 8080, PID: 41, Process: "node"}, + core.RemoteListeningPort{Address: "::", Port: 8080, PID: 41, Process: "node"}, + core.RemoteListeningPort{Address: "127.0.0.1", Port: 5432, PID: 7, Process: "postgres"}, + core.RemoteListeningPort{Address: "127.0.0.2", Port: 5432}, + core.RemoteListeningPort{Address: "10.0.0.5", Port: 9000}, + ) + k.set(func(k *remoteHostKernel) { k.ports.taken = map[uint16]bool{5432: true} }) + ports := &p.remote.ports + want := []remotePortKey{{port: 5432}, {host: "127.0.0.2", port: 5432}, {port: 8080}, {host: "10.0.0.5", port: 9000}} + if got := remotePortKeys(ports.rows()); !slices.Equal(got, want) { + t.Fatalf("rows %v, want %v", got, want) + } + if len(k.ports.starts) != 0 || len(ports.forwards) != 0 { + t.Fatal("a port was forwarded before the user asked") + } + node := i18n.SharedFormat(lang, "desktop.remote.ports.process", map[string]string{"process": "node", "pid": "41"}) + if !h.shows(node) || !h.shows("10.0.0.5:9000") || !h.shows(i18n.Shared(lang, "desktop.remote.ports.processUnknown")) { + t.Fatal("the rows do not show the ports and their processes") + } + // Each row shows the address the host serves the port on; a row served on more than one names + // the first and counts the others, which its tooltip lists. + both := i18n.SharedFormat(lang, "desktop.remote.ports.remoteMore", map[string]string{"address": "0.0.0.0:8080", "count": "1"}) + listening := i18n.SharedFormat(lang, "desktop.remote.ports.remoteListening", map[string]string{"addresses": "0.0.0.0:8080, [::]:8080"}) + if !h.shows(both) || !h.hasControl(listening) || !h.shows("127.0.0.1:5432") || !h.shows("127.0.0.2:5432") { + t.Fatal("the rows do not show the addresses the host listens on") + } + + forward := i18n.Shared(lang, "desktop.remote.ports.forward") + h.click(center(h.portRowControl(both, forward))) + h.await("the forward", func() bool { return len(ports.forwards) == 1 && len(ports.busy) == 0 }) + h.settle() + if got := k.ports.starts; len(got) != 1 || got[0] != (core.RemoteForwardTarget{Host: "127.0.0.1", Port: 8080, LocalPort: 8080}) { + t.Fatalf("started %+v, want one forward to the IPv4 loopback address on the same local port", got) + } + label := i18n.Shared(lang, "desktop.remote.ports.statusLabel") + if !h.shows("127.0.0.1:8080") || !h.shows(i18n.Shared(lang, "desktop.remote.ports.statusForwarded")) || !h.hasControl(label) { + t.Fatal("the forward is not shown in its row and in the status bar") + } + h.click(center(h.portRowControl("127.0.0.1:5432", forward))) + h.await("the forward on a free port", func() bool { return len(ports.forwards) == 2 && len(ports.busy) == 0 }) + h.settle() + if changed := ports.forwards[1]; !changed.LocalPortChanged || changed.LocalPort == 5432 || !h.shows(remotePortAddress(changed)) { + t.Fatalf("forward %+v: the taken local port was not replaced and shown", changed) + } + + h.app.reduceChrome(core.SetChromeOpen(itemPorts, false)) + h.redraw() + h.clickLabeled(label) + if !h.app.chrome.isOpen(catalogIndex[itemPorts]) { + t.Fatal("the status bar's count did not open the Ports window") + } + actions := remoteActions(logger) + if !slices.Contains(actions, "remote.ports.forward") || !slices.Contains(actions, "remote.ports.status") { + t.Fatalf("performed %q, want the forward and the status bar's click", actions) + } + if event := loggedAny(t, logger, remoteTestHost, "10.0.0.5", "node", "postgres"); event != "" { + t.Fatalf("logged the host, an address or a process: %s", event) + } +} + +// A target outside the host's loopback interface is forwarded only after the window asked: Forward +// in the question forwards it, and Cancel forwards nothing and is logged as declined. +func TestRemotePortsAsksBeforeForwardingOutsideTheLoopback(t *testing.T) { + h, k, _, logger := remoteWorkspaceHarness(t) + lang := h.app.language() + p := h.openRemotePortsWindow(t, k, core.RemoteListeningPort{Address: "10.0.0.5", Port: 9000}) + ports := &p.remote.ports + title := i18n.Shared(lang, "desktop.remote.ports.confirmTitle") + + h.click(center(h.portRowControl("10.0.0.5:9000", i18n.Shared(lang, "desktop.remote.ports.forward")))) + h.await("the question", func() bool { return ports.confirm != nil && len(ports.busy) == 0 }) + h.settle() + if !h.shows(title) || !rejected(logger, "remote_port_forward", "target_not_confirmed") || len(ports.forwards) != 0 { + t.Fatal("the unconfirmed target was not asked about") + } + h.click(center(h.popupHit(i18n.Shared(lang, "desktop.remote.ports.confirmForward")))) + h.await("the confirmed forward", func() bool { return len(ports.forwards) == 1 && len(ports.busy) == 0 }) + h.settle() + if got := k.ports.starts; len(got) != 2 || got[1] != (core.RemoteForwardTarget{Host: "10.0.0.5", Port: 9000, LocalPort: 9000, AllowNonLoopback: true}) { + t.Fatalf("started %+v, want the target again once confirmed", got) + } + if ports.confirm != nil || h.shows(title) { + t.Fatal("the question stayed open") + } + + ports.add.SetText("10.0.0.6:7000") + h.redraw() + h.clickLabeled(i18n.Shared(lang, "desktop.remote.ports.add")) + h.await("the second question", func() bool { return ports.confirm != nil && len(ports.busy) == 0 }) + h.settle() + h.click(center(h.popupHit(i18n.Shared(lang, "desktop.remote.ports.confirmCancel")))) + h.settle() + if ports.confirm != nil || len(ports.forwards) != 1 || len(k.ports.starts) != 3 { + t.Fatalf("forwards %d, starts %d: Cancel forwarded the target", len(ports.forwards), len(k.ports.starts)) + } + if !rejected(logger, "remote_port_forward", "target_declined") { + t.Fatal("Cancel was not logged as declined") + } +} + +// An address typed into the window is read by Core: a refused one stays in the field with the +// reason under it and is logged by a fixed reason, without the text; the others are added and +// forwarded to the host typed. The same row added again is not forwarded twice, and once stopped +// the menu removes it. +func TestRemotePortsAddsStopsAndRemovesAPort(t *testing.T) { + h, k, _, logger := remoteWorkspaceHarness(t) + lang := h.app.language() + p := h.openRemotePortsWindow(t, k) + ports := &p.remote.ports + empty := i18n.Shared(lang, "desktop.remote.ports.empty") + if !h.showsWrapped(empty) { + t.Fatal("the window does not say the host listens on nothing") + } + add := i18n.Shared(lang, "desktop.remote.ports.add") + submit := func(text string) { + t.Helper() + ports.add.SetText(text) + h.redraw() + h.clickLabeled(add) + } + for _, c := range []struct{ text, reason, token, message string }{ + {"not a port", "malformed", "malformed_address", "desktop.remote.ports.addInvalid"}, + {"http://dev:s3cret@localhost:3000", "credentials", "credentials_in_address", "desktop.remote.ports.addCredentials"}, + } { + submit(c.text) + h.await("the refusal of the "+c.reason+" address", func() bool { return ports.addRefused == c.reason && !ports.adding }) + h.settle() + if ports.add.Text() != c.text || !rejected(logger, "remote_port_add", c.token) || !h.showsWrapped(i18n.Shared(lang, c.message)) { + t.Fatalf("the %s address was not refused under the field that keeps it", c.reason) + } + } + if len(k.ports.starts) != 0 || len(ports.manual) != 0 { + t.Fatalf("starts %d, manual %d: a refused address was added", len(k.ports.starts), len(ports.manual)) + } + if event := loggedAny(t, logger, "s3cret", "not a port"); event != "" { + t.Fatalf("logged what was typed: %s", event) + } + + submit("3000") + h.await("the forward", func() bool { return len(ports.forwards) == 1 && len(ports.busy) == 0 }) + h.settle() + if got := k.ports.starts; len(got) != 1 || got[0] != (core.RemoteForwardTarget{Host: "localhost", Port: 3000, LocalPort: 3000}) { + t.Fatalf("started %+v, want the port on localhost", got) + } + if ports.addRefused != "" || ports.add.Text() != "" || !h.shows(i18n.Shared(lang, "desktop.remote.ports.sourceManual")) || !h.shows("localhost:3000") { + t.Fatal("the added port is not shown as added by hand") + } + submit("localhost:3000") + h.await("the address read again", func() bool { return ports.add.Text() == "" && !ports.adding }) + h.settle() + if len(k.ports.starts) != 1 || len(ports.manual) != 1 { + t.Fatalf("starts %d, manual %d: the port was added twice", len(k.ports.starts), len(ports.manual)) + } + + h.click(center(h.portRowControl("localhost:3000", i18n.Shared(lang, "desktop.remote.ports.stop")))) + h.await("the stop", func() bool { return len(ports.forwards) == 0 && len(ports.busy) == 0 }) + h.settle() + if !slices.Equal(k.ports.stops, []uint64{1}) || !h.shows(i18n.Shared(lang, "desktop.remote.ports.statusNotForwarded")) { + t.Fatalf("stopped %v: the row does not show the stopped forward", k.ports.stops) + } + h.rightClickAt(h.portRowControl("localhost:3000", "localhost:3000")) + h.click(center(h.popupHit(i18n.Shared(lang, "desktop.remote.ports.remove")))) + h.settle() + if len(ports.manual) != 0 || !h.showsWrapped(empty) { + t.Fatal("Remove left the port in the window") + } + want := []string{"remote.ports.forward", "remote.ports.stop", "remote.ports.remove"} + if got := remoteActions(logger); !slices.Equal(got[len(got)-len(want):], want) { + t.Fatalf("performed %q, want it to end with %q", got, want) + } +} + +// The menu forwards a row on a local port the user types, which the row keeps: a text that is not +// a port is refused, Cancel changes nothing, another port moves the running forward by stopping +// and starting it, the same port leaves it alone, and a confirmed target is not asked about again. +func TestRemotePortsForwardOnAChosenLocalPort(t *testing.T) { + h, k, _, logger := remoteWorkspaceHarness(t) + lang := h.app.language() + p := h.openRemotePortsWindow(t, k, + core.RemoteListeningPort{Address: "127.0.0.1", Port: 8080}, + core.RemoteListeningPort{Address: "10.0.0.5", Port: 9000}, + ) + ports := &p.remote.ports + apply := i18n.Shared(lang, "desktop.remote.ports.localApply") + choose := func(remote, item, port string) { + t.Helper() + h.rightClickAt(h.portRowControl(remote, remote)) + h.click(center(h.popupHit(i18n.Shared(lang, item)))) + h.settle() + if ports.local == nil || !h.shows(i18n.Shared(lang, "desktop.remote.ports.localTitle")) { + t.Fatal("the local port dialog did not open") + } + if got := ports.localField.Text(); got != port { + t.Fatalf("the dialog starts from %q, want %q", got, port) + } + } + submit := func(text string) { + t.Helper() + ports.localField.SetText(text) + h.redraw() + h.click(center(h.popupHit(apply))) + h.settle() + } + + choose("127.0.0.1:8080", "desktop.remote.ports.forwardLocal", "8080") + submit("70000") + if !ports.localInvalid || ports.local == nil || len(k.ports.starts) != 0 || !rejected(logger, "remote_port_local", "invalid_port") || + !h.shows(i18n.Shared(lang, "desktop.remote.ports.localInvalid")) { + t.Fatal("a text that is not a port was not refused in the dialog") + } + submit("18080") + h.await("the forward", func() bool { return len(ports.forwards) == 1 && len(ports.busy) == 0 }) + h.settle() + if got := k.ports.starts; len(got) != 1 || got[0] != (core.RemoteForwardTarget{Host: "127.0.0.1", Port: 8080, LocalPort: 18080}) { + t.Fatalf("started %+v, want the chosen local port", got) + } + if ports.local != nil || !h.shows("127.0.0.1:18080") { + t.Fatal("the forward on the chosen port is not shown") + } + + choose("127.0.0.1:8080", "desktop.remote.ports.changeLocal", "18080") + ports.localField.SetText("1") + h.redraw() + h.click(center(h.popupHit(i18n.Shared(lang, "desktop.remote.ports.localCancel")))) + h.settle() + if ports.local != nil || len(k.ports.starts) != 1 || len(k.ports.stops) != 0 || ports.localPorts[remotePortKey{port: 8080}] != 18080 { + t.Fatal("Cancel changed the forward") + } + choose("127.0.0.1:8080", "desktop.remote.ports.changeLocal", "18080") + submit("18080") + if len(k.ports.starts) != 1 || len(k.ports.stops) != 0 { + t.Fatal("the same local port restarted the forward") + } + choose("127.0.0.1:8080", "desktop.remote.ports.changeLocal", "18080") + submit("18081") + h.await("the moved forward", func() bool { + return len(ports.forwards) == 1 && ports.forwards[0].LocalPort == 18081 && len(ports.busy) == 0 + }) + h.settle() + if !slices.Equal(k.ports.stops, []uint64{1}) || !h.shows("127.0.0.1:18081") { + t.Fatalf("stopped %v: the forward was not moved to the new port", k.ports.stops) + } + + h.click(center(h.portRowControl("127.0.0.1:8080", i18n.Shared(lang, "desktop.remote.ports.stop")))) + h.await("the stop", func() bool { return len(ports.forwards) == 0 && len(ports.busy) == 0 }) + h.settle() + h.click(center(h.portRowControl("127.0.0.1:8080", i18n.Shared(lang, "desktop.remote.ports.forward")))) + h.await("the forward again", func() bool { return len(ports.forwards) == 1 && len(ports.busy) == 0 }) + if got := k.ports.starts[len(k.ports.starts)-1]; got.LocalPort != 18081 { + t.Fatalf("forwarded again on %d, want the chosen port the row keeps", got.LocalPort) + } + + h.click(center(h.portRowControl("10.0.0.5:9000", i18n.Shared(lang, "desktop.remote.ports.forward")))) + h.await("the question", func() bool { return ports.confirm != nil && len(ports.busy) == 0 }) + h.settle() + h.click(center(h.popupHit(i18n.Shared(lang, "desktop.remote.ports.confirmForward")))) + h.await("the confirmed forward", func() bool { return len(ports.forwards) == 2 && len(ports.busy) == 0 }) + h.settle() + choose("10.0.0.5:9000", "desktop.remote.ports.changeLocal", "9000") + submit("19000") + h.await("the moved confirmed forward", func() bool { + return len(ports.forwards) == 2 && ports.forwards[1].LocalPort == 19000 && len(ports.busy) == 0 + }) + h.settle() + want := core.RemoteForwardTarget{Host: "10.0.0.5", Port: 9000, LocalPort: 19000, AllowNonLoopback: true} + if got := k.ports.starts[len(k.ports.starts)-1]; got != want || ports.confirm != nil { + t.Fatalf("started %+v, want the confirmed target without asking again", got) + } + actions := remoteActions(logger) + if !slices.Contains(actions, "remote.ports.localPort") || !slices.Contains(actions, "remote.ports.move") { + t.Fatalf("performed %q, want the dialog and the move", actions) + } +} + +// Past the session's limit the window says how many forwards Core runs, and Stop All Forwards +// stops every forward and takes the status bar's count away. +func TestRemotePortsStopsAllAndReportsTheLimit(t *testing.T) { + h, k, _, logger := remoteWorkspaceHarness(t) + lang := h.app.language() + k.set(func(k *remoteHostKernel) { k.ports.limit = 2 }) + p := h.openRemotePortsWindow(t, k, + core.RemoteListeningPort{Address: "127.0.0.1", Port: 3000}, + core.RemoteListeningPort{Address: "127.0.0.1", Port: 3001}, + core.RemoteListeningPort{Address: "127.0.0.1", Port: 3002}, + ) + ports := &p.remote.ports + forward := i18n.Shared(lang, "desktop.remote.ports.forward") + for i, port := range []string{"127.0.0.1:3000", "127.0.0.1:3001", "127.0.0.1:3002"} { + h.click(center(h.portRowControl(port, forward))) + h.await("the forward of "+port, func() bool { return len(ports.busy) == 0 && (len(ports.forwards) == i+1 || ports.notice != "") }) + h.settle() + } + limit := i18n.SharedFormat(lang, "desktop.remote.ports.limit", map[string]string{"maximum": "2"}) + if len(ports.forwards) != 2 || ports.notice != limit || !h.showsWrapped(limit) { + t.Fatalf("forwards %d: the limit is not reported", len(ports.forwards)) + } + if got := countFailures(logger, "remote_port_forward"); got != 1 { + t.Fatalf("remote_port_forward failed %d times, want once", got) + } + + h.clickLabeled(i18n.Shared(lang, "desktop.remote.ports.stopAll")) + h.await("Stop All Forwards", func() bool { return !ports.stoppingAll && len(ports.forwards) == 0 }) + h.settle() + if len(k.ports.forwards[p.remote.session]) != 0 || h.hasControl(i18n.Shared(lang, "desktop.remote.ports.statusLabel")) { + t.Fatal("Stop All Forwards left a forward running or counted") + } + if !slices.Contains(remoteActions(logger), "remote.ports.stopAll") { + t.Fatal("Stop All Forwards was not logged") + } +} + +// A lost session takes its forwards with it: the window shows the port unforwarded and reads the +// new session's forwards once the workspace connects again. +func TestRemotePortsForgetTheForwardsOfALostSession(t *testing.T) { + h, k, timers, _ := remoteWorkspaceHarness(t) + lang := h.app.language() + p := h.openRemotePortsWindow(t, k, core.RemoteListeningPort{Address: "127.0.0.1", Port: 8080}) + r := p.remote + h.click(center(h.portRowControl("127.0.0.1:8080", i18n.Shared(lang, "desktop.remote.ports.forward")))) + h.await("the forward", func() bool { return len(r.ports.forwards) == 1 && len(r.ports.busy) == 0 }) + h.settle() + + k.set(func(k *remoteHostKernel) { + k.once = &core.Error{Command: "remote.serverState", Code: core.CodeConnectionClosed, Message: "closed"} + }) + h.fireAfter(t, timers, remoteHeartbeatInterval) + h.await("the new session's reading", func() bool { + return r.session == "session-2" && !r.beating && r.ports.listed && !p.tree.reading + }) + h.settle() + if len(r.ports.forwards) != 0 || h.hasControl(i18n.Shared(lang, "desktop.remote.ports.statusLabel")) { + t.Fatal("the lost session's forward is still shown") + } + if !h.shows(i18n.Shared(lang, "desktop.remote.ports.statusNotForwarded")) { + t.Fatal("the port is not shown unforwarded") + } + if got := timers.liveAfter(remotePortsInterval); got != 1 { + t.Fatalf("%d readings of the window pending, want the new session's one", got) + } +} + +// The window reads the host while it is open, and stops once it is hidden until it is shown again. +func TestRemotePortsReadOnlyWhileTheWindowIsOpen(t *testing.T) { + h, k, timers, _ := remoteWorkspaceHarness(t) + p := h.openRemotePortsWindow(t, k, core.RemoteListeningPort{Address: "127.0.0.1", Port: 8080}) + listings := func() int { return k.count(func(k *remoteHostKernel) int { return k.ports.listings }) } + if got := listings(); got != 1 { + t.Fatalf("listed %d times on opening, want once", got) + } + h.fireAfter(t, timers, remotePortsInterval) + if got := listings(); got != 2 { + t.Fatalf("listed %d times, want the open window read again", got) + } + + h.app.reduceChrome(core.SetChromeOpen(itemPorts, false)) + h.redraw() + h.fireAfter(t, timers, remotePortsInterval) + if got := listings(); got != 2 || p.remote.ports.reading || timers.liveAfter(remotePortsInterval) != 0 { + t.Fatalf("listed %d times: the hidden window kept reading", got) + } + + h.app.openToolWindow(itemPorts) + h.redraw() + h.await("the shown window's reading", func() bool { return listings() == 3 && timers.liveAfter(remotePortsInterval) == 1 }) +} + +// A reading that fails is shown in the window and logged once until a reading succeeds again. +func TestRemotePortsReportAFailedReadingOnce(t *testing.T) { + h, k, timers, logger := remoteWorkspaceHarness(t) + lang := h.app.language() + k.set(func(k *remoteHostKernel) { k.ports.listenErr = errors.New("ss: not found") }) + p := h.openRemotePortsWindow(t, k) + ports := &p.remote.ports + failed := i18n.SharedFormat(lang, "desktop.remote.ports.readFailed", map[string]string{"reason": "ss: not found"}) + if ports.readFailed == "" || !h.showsWrapped(failed) { + t.Fatal("the failed reading is not shown") + } + h.fireAfter(t, timers, remotePortsInterval) + if got := countFailures(logger, "remote_ports_read"); got != 1 { + t.Fatalf("remote_ports_read failed %d times, want once while it keeps failing", got) + } + + k.set(func(k *remoteHostKernel) { k.ports.listenErr = nil }) + h.fireAfter(t, timers, remotePortsInterval) + if ports.readFailed != "" || !ports.listed || h.showsWrapped(failed) { + t.Fatal("the successful reading did not clear the failure") + } + k.set(func(k *remoteHostKernel) { k.ports.listenErr = errors.New("ss: not found") }) + h.fireAfter(t, timers, remotePortsInterval) + if got := countFailures(logger, "remote_ports_read"); got != 2 { + t.Fatalf("remote_ports_read failed %d times, want a new failure logged again", got) + } +} + +// A URL typed into the window is forwarded to the loopback address the host serves its port on and +// keeps its scheme and path: the row reads it as typed with the addresses the host listens on in +// its tooltip, Open in Browser opens it with the local address in place of the host's, a URL a +// browser does not open offers no Open in Browser, and a browser that fails to open it logs nothing +// of the URL, whose query can hold a token. +func TestRemotePortsForwardAURL(t *testing.T) { + var opened []string + var openErr error + previous := openURL + openURL = func(address string) error { opened = append(opened, address); return openErr } + t.Cleanup(func() { openURL = previous }) + h, k, _, logger := remoteWorkspaceHarness(t) + lang := h.app.language() + p := h.openRemotePortsWindow(t, k, core.RemoteListeningPort{Address: "0.0.0.0", Port: 3443, PID: 9, Process: "vite"}) + ports := &p.remote.ports + add := i18n.Shared(lang, "desktop.remote.ports.add") + open := i18n.Shared(lang, "desktop.remote.ports.openBrowser") + submit := func(text string, forwards int) { + t.Helper() + ports.add.SetText(text) + h.redraw() + h.clickLabeled(add) + h.await("the forward of the URL", func() bool { return len(ports.forwards) == forwards && len(ports.busy) == 0 }) + h.settle() + } + + submit("HTTPS://Localhost:3443/app?tab=1&token=t0ken", 1) + if got := k.ports.starts; len(got) != 1 || got[0] != (core.RemoteForwardTarget{Host: "127.0.0.1", Port: 3443, LocalPort: 3443}) { + t.Fatalf("started %+v, want the URL's port on the IPv4 loopback address the host serves it on", got) + } + // The column cuts the URL off, so the tooltip gives it whole. + row := "https://localhost:3443/app?tab=1&token=t0ken" + listening := i18n.SharedFormat(lang, "desktop.remote.ports.remoteUrlListening", map[string]string{"url": row, "addresses": "0.0.0.0:3443"}) + if !h.hasControl(row) || !h.hasControl(listening) || len(ports.manual) != 1 { + t.Fatal("the URL's row does not read as typed with the addresses the host listens on") + } + local := "https://127.0.0.1:3443/app?tab=1&token=t0ken" + h.click(center(h.portRowControl(row, open))) + h.settle() + if !slices.Equal(opened, []string{local}) { + t.Fatalf("opened %q, want the URL on the local address", opened) + } + if got, _ := ports.row(remotePortKey{port: 3443}); got.copyText() != local { + t.Fatalf("Copy Local Address copies %q, want the URL on the local address", got.copyText()) + } + openErr = errors.New("open " + local + ": no application") + h.click(center(h.portRowControl(row, open))) + h.settle() + if got := countFailures(logger, "remote_port_open"); got != 1 { + t.Fatalf("remote_port_open failed %d times, want once", got) + } + if event := loggedAny(t, logger, "t0ken", "/app"); event != "" { + t.Fatalf("logged the URL: %s", event) + } + + submit("ws://localhost:3001", 2) + if _, ok := h.portRowHas("ws://localhost:3001", open); ok { + t.Fatal("a ws URL offers Open in Browser") + } + if _, ok := h.portRowHas("ws://localhost:3001", i18n.Shared(lang, "desktop.remote.ports.copyAddress")); !ok { + t.Fatal("a ws URL offers no Copy Local Address") + } +} + +// remotePortsRemote reads a row as the host serves it, its IP address included, a row served on +// more than one address as the first and a count; a URL the user added reads as typed. browserURL +// and copyText put the forward's local address in place of the host's. +func TestRemotePortRowText(t *testing.T) { + listening := func(port uint16, addresses ...string) []core.RemoteListeningPort { + var v []core.RemoteListeningPort + for _, address := range addresses { + v = append(v, core.RemoteListeningPort{Address: address, Port: port}) + } + return v + } + forward := func(local string, port uint16) *core.RemoteForward { + return &core.RemoteForward{ID: 1, LocalHost: local, LocalPort: port} + } + added := func(host, scheme, path string) *remotePortAdded { + return &remotePortAdded{host: host, scheme: scheme, path: path} + } + cases := []struct { + name string + row remotePortRow + text string + tip string + browser string + copied string + }{ + {name: "both families", row: remotePortRow{key: remotePortKey{port: 8080}, listening: listening(8080, "::", "0.0.0.0", "::")}, + text: "0.0.0.0:8080 +1", tip: "Listening on 0.0.0.0:8080, [::]:8080"}, + {name: "IPv6 loopback", row: remotePortRow{key: remotePortKey{port: 5432}, listening: listening(5432, "::1")}, text: "[::1]:5432"}, + {name: "one address twice", row: remotePortRow{key: remotePortKey{port: 3000}, listening: listening(3000, "127.0.0.1", "127.0.0.1")}, + text: "127.0.0.1:3000"}, + {name: "link-local address", row: remotePortRow{key: remotePortKey{host: "fe80::1", port: 22}, listening: listening(22, "fe80::1")}, + text: "[fe80::1]:22"}, + {name: "long address", row: remotePortRow{key: remotePortKey{host: "2001:db8:1234:5678::abcd", port: 8443}, listening: listening(8443, "2001:db8:1234:5678::abcd")}, + text: "[2001:db8:1234:5678::abcd]:8443", tip: "[2001:db8:1234:5678::abcd]:8443"}, + {name: "added port", row: remotePortRow{key: remotePortKey{port: 3000}, added: added("localhost", "", "")}, text: "localhost:3000"}, + {name: "added host", row: remotePortRow{key: remotePortKey{host: "build.example", port: 9000}, added: added("Build.Example", "", "")}, + text: "build.example:9000"}, + {name: "forward only", row: remotePortRow{key: remotePortKey{port: 8080}, forward: &core.RemoteForward{TargetHost: "127.0.0.1", LocalHost: "127.0.0.1", LocalPort: 8080}}, + text: "127.0.0.1:8080", browser: "http://127.0.0.1:8080", copied: "127.0.0.1:8080"}, + {name: "forwarded port", row: remotePortRow{key: remotePortKey{port: 8080}, listening: listening(8080, "0.0.0.0"), forward: forward("::1", 18080)}, + text: "0.0.0.0:8080", browser: "http://[::1]:18080", copied: "[::1]:18080"}, + {name: "http URL", row: remotePortRow{key: remotePortKey{port: 5173}, added: added("localhost", "http", "/app?tab=1"), forward: forward("127.0.0.1", 40001)}, + text: "http://localhost:5173/app?tab=1", tip: "http://localhost:5173/app?tab=1", browser: "http://127.0.0.1:40001/app?tab=1", copied: "http://127.0.0.1:40001/app?tab=1"}, + {name: "https URL served", row: remotePortRow{key: remotePortKey{port: 443}, listening: listening(443, "127.0.0.1"), added: added("localhost", "https", ""), forward: forward("127.0.0.1", 40002)}, + text: "https://localhost:443", tip: "https://localhost:443, listening on 127.0.0.1:443", browser: "https://127.0.0.1:40002", copied: "https://127.0.0.1:40002"}, + {name: "wss URL", row: remotePortRow{key: remotePortKey{port: 443}, added: added("localhost", "wss", "/socket"), forward: forward("127.0.0.1", 40003)}, + text: "wss://localhost:443/socket", tip: "wss://localhost:443/socket", copied: "wss://127.0.0.1:40003/socket"}, + {name: "URL not forwarded", row: remotePortRow{key: remotePortKey{port: 3000}, added: added("localhost", "http", "/")}, text: "http://localhost:3000/"}, + } + for _, c := range cases { + text, tip := remotePortsRemote(i18n.English, c.row) + browser, browsable := c.row.browserURL() + if text != c.text || tip != c.tip || browser != c.browser || browsable != (c.browser != "") || c.row.copyText() != c.copied { + t.Errorf("%s: text %q, tip %q, browser %q %v, copied %q; want %q, %q, %q, %q", c.name, text, tip, browser, browsable, + c.row.copyText(), c.text, c.tip, c.browser, c.copied) + } + } +} + +func TestRemotePortHost(t *testing.T) { + cases := map[string]string{ + "0.0.0.0": "", + "::": "", + "127.0.0.1": "", + "::1": "", + "[::1]": "", + "::ffff:127.0.0.1": "", + "LocalHost": "", + "127.0.0.2": "127.0.0.2", + "::ffff:10.0.0.5": "10.0.0.5", + "fe80::1": "fe80::1", + "Build.Example": "build.example", + } + for address, want := range cases { + if got := remotePortHost(address); got != want { + t.Errorf("remotePortHost(%q) = %q, want %q", address, got, want) + } + } +} diff --git a/desktop/internal/workbench/remote_ports_view.go b/desktop/internal/workbench/remote_ports_view.go new file mode 100644 index 000000000..78d8b703e --- /dev/null +++ b/desktop/internal/workbench/remote_ports_view.go @@ -0,0 +1,444 @@ +package workbench + +import ( + "net" + "strconv" + "strings" + "unicode/utf8" + + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/1lck/Lithe-IDEA/desktop/internal/icons" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +// This file draws the Ports tool window of a remote workspace (remote_ports.go) and the status +// bar's count of its forwards. + +const ( + // remotePortsRowHeight is the height of a row of the list and of its header. + remotePortsRowHeight = 26 + // The widths of the list's fixed columns; the Process column takes the rest. + remotePortsRemoteWidth = 200 + remotePortsLocalWidth = 150 + remotePortsSourceWidth = 90 + remotePortsStatusWidth = 170 + remotePortsActionWidth = 96 +) + +// remotePortsActions declares the Ports window's header actions: the security note of forwards +// (S30) and Stop All Forwards. +func (a *App) remotePortsActions(c ui.C, p *project) { + r := p.remote + if r == nil { + return + } + language := a.language() + ui.Button(c.Part("ports-help"), i18n.Shared(language, "native.moreInformation")).Icon(icons.Info).IconOnly().Ghost().Size(18, 18). + Tooltip(i18n.Shared(language, "desktop.remote.ports.help")) + disabled := r.session == "" || len(r.ports.forwards) == 0 || r.ports.stoppingAll + if _, clicked := a.toolIconButton(c.Part("ports-stop-all"), i18n.Shared(language, "desktop.remote.ports.stopAll"), icons.Square, false, disabled); clicked { + c.After(func() { a.stopAllRemotePorts(p, surfaceToolbar) }) + } +} + +// remotePortsView declares the body of the Ports window: the field a port is typed into, the +// window's message, and the list of ports. +func (a *App) remotePortsView(c ui.C, p *project) { + r := p.remote + if r == nil { + a.toolPlaceholder(c) + return + } + a.showRemotePorts(p) + ports := &r.ports + language := a.language() + ui.Column(c).Fill().Background(a.colors.Editor).Children(func() { + a.remotePortsAddRow(c, p) + switch ports.addRefused { + case "": + case "credentials": + a.remotePortsLine(c.Part("add-invalid"), i18n.Shared(language, "desktop.remote.ports.addCredentials"), a.theme.Danger) + default: + a.remotePortsLine(c.Part("add-invalid"), i18n.Shared(language, "desktop.remote.ports.addInvalid"), a.theme.Danger) + } + if ports.notice != "" { + a.remotePortsLine(c.Part("notice"), ports.notice, a.colors.Warning) + } + ui.Divider(c) + if r.session == "" { + a.panelMessage(c, i18n.Shared(language, "desktop.remote.ports.disconnected"), a.colors.Subtle) + return + } + if ports.readFailed != "" { + a.remotePortsLine(c.Part("read-failed"), i18n.SharedFormat(language, "desktop.remote.ports.readFailed", + map[string]string{"reason": ports.readFailed}), a.theme.Danger) + } + rows := ports.rows() + if len(rows) == 0 { + if !ports.listed && ports.readFailed == "" { + a.panelMessage(c, i18n.Shared(language, "desktop.remote.ports.loading"), a.colors.Subtle) + } else { + a.panelMessage(c, i18n.Shared(language, "desktop.remote.ports.empty"), a.colors.Subtle) + } + return + } + a.remotePortsHeader(c) + ui.Scroll(c.Part("ports-list")).Scrollbars().Fill().Children(func() { + for _, row := range rows { + a.remotePortsRow(c.Key("port:"+row.key.host+":"+strconv.Itoa(int(row.key.port))), p, row) + } + }) + }) + a.remotePortsConfirm(c, p) + a.remotePortsLocal(c, p) +} + +// remotePortsLine declares a line of the window's messages in color. +func (a *App) remotePortsLine(c ui.C, text string, color gfx.Color) { + ui.Row(c).FillWidth().Shrink(0).PadX(shellContentPad).PadY(4).Children(func() { + ui.Paragraph(c, text, 3).Grow(1).Color(color) + }) +} + +// remotePortsAddRow declares the field a port, host:port or URL is typed into and the button that +// forwards it. +func (a *App) remotePortsAddRow(c ui.C, p *project) { + ports := &p.remote.ports + language := a.language() + k := c.Part("ports-add") + ui.Row(k).FillWidth().Height(panelHeaderHeight).Shrink(0).Items(ui.Center).Gap(6).PadX(8).Children(func() { + submitted := ui.TextField(k.Part("field"), &ports.add, i18n.Shared(language, "desktop.remote.ports.addLabel"), + i18n.Shared(language, "desktop.remote.ports.addPlaceholder")).Grow(1).Submitted() + unavailable := p.remote.session == "" || ports.adding + add := ui.Button(k.Part("button"), i18n.Shared(language, "desktop.remote.ports.add")).Outline(). + Disabled(unavailable || strings.TrimSpace(ports.add.Text()) == "") + if (submitted || add.Clicked()) && !unavailable { + surface := surfaceButton + if submitted { + surface = surfaceShortcut + } + c.After(func() { a.addRemotePort(p, surface) }) + } + }) +} + +// remotePortsHeader declares the header of the list. +func (a *App) remotePortsHeader(c ui.C) { + language := a.language() + k := c.Part("ports-header") + ui.Row(k).FillWidth().Height(remotePortsRowHeight).Shrink(0).Items(ui.Center).PadX(shellContentPad).Children(func() { + column := func(key, text string, width float32) { + cell := ui.Row(k.Part(key)).Shrink(0).Items(ui.Center) + if width > 0 { + cell = cell.Width(width) + } else { + cell = cell.Grow(1).Shrink(1).MinWidth(0) + } + cell.Children(func() { + ui.Text(k.Part(key+"-text"), text).FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Subtle).Ellipsis() + }) + } + column("remote", i18n.Shared(language, "desktop.remote.ports.columnRemote"), remotePortsRemoteWidth) + column("local", i18n.Shared(language, "desktop.remote.ports.columnLocal"), remotePortsLocalWidth) + column("process", i18n.Shared(language, "desktop.remote.ports.columnProcess"), 0) + column("source", i18n.Shared(language, "desktop.remote.ports.columnSource"), remotePortsSourceWidth) + column("status", i18n.Shared(language, "desktop.remote.ports.columnStatus"), remotePortsStatusWidth) + ui.Row(k.Part("actions")).Width(remotePortsActionWidth).Shrink(0) + }) + ui.Divider(c) +} + +// remotePortsProcess is the Process column of row: the command name and process ID of each +// listening process the host named, or Unknown. +func remotePortsProcess(language i18n.Language, row remotePortRow) string { + var names []string + seen := map[uint32]bool{} + for _, port := range row.listening { + if port.PID == 0 || seen[port.PID] { + continue + } + seen[port.PID] = true + names = append(names, i18n.SharedFormat(language, "desktop.remote.ports.process", + map[string]string{"process": port.Process, "pid": strconv.FormatUint(uint64(port.PID), 10)})) + } + if len(names) == 0 { + if len(row.listening) == 0 { + return "" + } + return i18n.Shared(language, "desktop.remote.ports.processUnknown") + } + return strings.Join(names, ", ") +} + +// remotePortsRemoteFits is the most characters of the Remote Port column that its width shows +// whole; a longer text, such as a URL, a global IPv6 address or a long host name, ends in an +// ellipsis, so its tooltip gives it whole. +const remotePortsRemoteFits = 24 + +// remotePortsRemote is the Remote Port column of row and its tooltip. The column reads the URL the +// user added the port as; otherwise the first address the host listens on for it, IPv4 first, +// with the count of the others; otherwise the address the user typed or the forward's target. +// The tooltip gives what the column cuts off or leaves out: the URL with every address the host +// listens on for its port, every address of a port the host listens on more than once, or a text +// longer than the column shows whole. It is "" when the column says everything. +func remotePortsRemote(language i18n.Language, row remotePortRow) (text, tip string) { + port := strconv.Itoa(int(row.key.port)) + addresses := row.addresses() + switch { + case row.url(): + text = row.added.scheme + "://" + net.JoinHostPort(row.added.host, port) + row.added.path + case len(addresses) > 1: + text = i18n.SharedFormat(language, "desktop.remote.ports.remoteMore", + map[string]string{"address": addresses[0], "count": strconv.Itoa(len(addresses) - 1)}) + case len(addresses) == 1: + text = addresses[0] + default: + text = net.JoinHostPort(row.target(), port) + } + listening := strings.Join(addresses, ", ") + switch { + case row.url() && len(addresses) > 0: + tip = i18n.SharedFormat(language, "desktop.remote.ports.remoteUrlListening", map[string]string{"url": text, "addresses": listening}) + case len(addresses) > 1: + tip = i18n.SharedFormat(language, "desktop.remote.ports.remoteListening", map[string]string{"addresses": listening}) + case utf8.RuneCountInString(text) > remotePortsRemoteFits: + tip = text + } + return text, tip +} + +// remotePortsStatus is the Status column of row and its colour. +func (a *App) remotePortsStatus(ports *remotePorts, row remotePortRow) (string, gfx.Color) { + language := a.language() + switch ports.busy[row.key] { + case remotePortForwarding: + return i18n.Shared(language, "desktop.remote.ports.statusForwarding"), a.colors.Subtle + case remotePortStopping: + return i18n.Shared(language, "desktop.remote.ports.statusStopping"), a.colors.Subtle + } + if reason := ports.failed[row.key]; reason != "" { + return i18n.SharedFormat(language, "desktop.remote.ports.statusFailed", map[string]string{"reason": reason}), a.theme.Danger + } + if row.forward != nil { + return i18n.Shared(language, "desktop.remote.ports.statusForwarded"), a.colors.Success + } + return i18n.Shared(language, "desktop.remote.ports.statusNotForwarded"), a.colors.Subtle +} + +// remotePortsRow declares one row of the list, its actions and its context menu. +func (a *App) remotePortsRow(c ui.C, p *project, row remotePortRow) { + r := p.remote + ports := &r.ports + language := a.language() + busy := ports.busy[row.key] != 0 || ports.stoppingAll + status, statusColor := a.remotePortsStatus(ports, row) + source := i18n.Shared(language, "desktop.remote.ports.sourceManual") + if len(row.listening) > 0 { + source = i18n.Shared(language, "desktop.remote.ports.sourceListening") + } + local := "" + localTip := "" + if row.forward != nil { + local = remotePortAddress(*row.forward) + if row.forward.LocalPortChanged && row.forward.RequestedLocalPort != nil { + localTip = i18n.SharedFormat(language, "desktop.remote.ports.localChanged", map[string]string{ + "requested": strconv.Itoa(int(*row.forward.RequestedLocalPort)), + "port": strconv.Itoa(int(row.forward.LocalPort)), + }) + } + } + remote, remoteTip := remotePortsRemote(language, row) + line := ui.Row(c).FillWidth().Height(remotePortsRowHeight).Shrink(0).Items(ui.Center).PadX(shellContentPad). + Hover(ui.Look{}.Background(a.colors.Hover)). + HitWith(ui.ID(c), remote, gfx.HitOptions{Value: status, SkipFocus: true}) + line.Children(func() { + remoteCell := ui.Row(c.Part("remote")).Width(remotePortsRemoteWidth).Shrink(0).Items(ui.Center) + if remoteTip != "" { + // The cell takes an identity for its tooltip, which gives what the column cuts off or + // leaves out. + remoteCell = remoteCell.HitWith(ui.ID(c.Part("remote")), remoteTip, gfx.HitOptions{Role: gfx.RoleStatus, SkipFocus: true}). + Tooltip(remoteTip) + } + remoteCell.Children(func() { + ui.Text(c.Part("remote-text"), remote).Color(a.colors.Text).Ellipsis() + }) + localCell := ui.Row(c.Part("local")).Width(remotePortsLocalWidth).Shrink(0).Items(ui.Center) + color := a.colors.Text + if localTip != "" { + // The cell takes an identity for its tooltip, which says why the port differs. + color = a.colors.Warning + localCell = localCell.HitWith(ui.ID(c.Part("local")), local, gfx.HitOptions{Role: gfx.RoleStatus, Value: localTip, SkipFocus: true}). + Tooltip(localTip) + } + localCell.Children(func() { + ui.Text(c.Part("local-text"), local).Color(color).Ellipsis() + }) + ui.Row(c.Part("process")).Grow(1).Shrink(1).MinWidth(0).Items(ui.Center).Children(func() { + ui.Text(c.Part("process-text"), remotePortsProcess(language, row)).Color(a.colors.Subtle).Ellipsis() + }) + ui.Row(c.Part("source")).Width(remotePortsSourceWidth).Shrink(0).Items(ui.Center).Children(func() { + ui.Text(c.Part("source-text"), source).Color(a.colors.Subtle).Ellipsis() + }) + ui.Row(c.Part("status")).Width(remotePortsStatusWidth).Shrink(0).Items(ui.Center).Children(func() { + ui.Text(c.Part("status-text"), status).Color(statusColor).Ellipsis() + }) + ui.Row(c.Part("actions")).Width(remotePortsActionWidth).Shrink(0).Items(ui.Center).Justify(ui.End).Gap(2).Children(func() { + a.remotePortsRowActions(c, p, row, busy) + }) + }) + ui.ContextMenu(c.Part("menu"), line, func(menu *ui.MenuItems) { + menu.WidthRange(180, 280) + if row.forward != nil { + forward := *row.forward + if _, browsable := row.browserURL(); browsable { + if menu.Item(i18n.Shared(language, "desktop.remote.ports.openBrowser")).Icon(icons.ExternalLink).Clicked() { + c.After(func() { a.openRemotePort(row, surfaceContextMenu) }) + } + } + if menu.Item(i18n.Shared(language, "desktop.remote.ports.copyAddress")).Icon(icons.Copy).Clicked() { + c.After(func() { a.copyRemotePort(row, surfaceContextMenu) }) + } + if menu.Item(i18n.Shared(language, "desktop.remote.ports.changeLocal")).Icon(icons.Pencil).Disabled(busy || r.session == "").Clicked() { + c.After(func() { a.chooseRemoteLocalPort(p, row.key, surfaceContextMenu) }) + } + if menu.Item(i18n.Shared(language, "desktop.remote.ports.stop")).Icon(icons.Square).Disabled(busy).Clicked() { + c.After(func() { a.stopRemotePort(p, row.key, forward.ID, surfaceContextMenu) }) + } + } else { + if menu.Item(i18n.Shared(language, "desktop.remote.ports.forward")).Icon(icons.ArrowLeftRight).Disabled(busy || r.session == "").Clicked() { + c.After(func() { a.forwardRemotePort(p, row.key, row.target(), false, surfaceContextMenu) }) + } + if menu.Item(i18n.Shared(language, "desktop.remote.ports.forwardLocal")).Icon(icons.Pencil).Disabled(busy || r.session == "").Clicked() { + c.After(func() { a.chooseRemoteLocalPort(p, row.key, surfaceContextMenu) }) + } + } + if row.added != nil && row.forward == nil && len(row.listening) == 0 { + menu.Separator() + if menu.Item(i18n.Shared(language, "desktop.remote.ports.remove")).Icon(icons.Trash2).Disabled(busy).Clicked() { + c.After(func() { a.removeRemotePort(p, row.key) }) + } + } + }) +} + +// remotePortsRowActions declares the buttons at the end of row: Open in Browser — unless the row's +// URL is not one a browser opens — Copy Local Address and Stop Forwarding for a forwarded port, +// Forward otherwise. +func (a *App) remotePortsRowActions(c ui.C, p *project, row remotePortRow, busy bool) { + language := a.language() + if row.forward == nil { + if _, clicked := a.toolIconButton(c.Part("forward"), i18n.Shared(language, "desktop.remote.ports.forward"), icons.ArrowLeftRight, false, busy || p.remote.session == ""); clicked { + c.After(func() { a.forwardRemotePort(p, row.key, row.target(), false, surfaceButton) }) + } + return + } + forward := *row.forward + if _, browsable := row.browserURL(); browsable { + if _, clicked := a.toolIconButton(c.Part("open"), i18n.Shared(language, "desktop.remote.ports.openBrowser"), icons.ExternalLink, false, false); clicked { + c.After(func() { a.openRemotePort(row, surfaceButton) }) + } + } + if _, clicked := a.toolIconButton(c.Part("copy"), i18n.Shared(language, "desktop.remote.ports.copyAddress"), icons.Copy, false, false); clicked { + c.After(func() { a.copyRemotePort(row, surfaceButton) }) + } + if _, clicked := a.toolIconButton(c.Part("stop"), i18n.Shared(language, "desktop.remote.ports.stop"), icons.Square, false, busy); clicked { + c.After(func() { a.stopRemotePort(p, row.key, forward.ID, surfaceButton) }) + } +} + +// remotePortsConfirm declares the question a forward to a target outside the host's loopback +// interface waits for (S28). Closing it is a refusal. +func (a *App) remotePortsConfirm(c ui.C, p *project) { + ports := &p.remote.ports + if ports.confirm == nil { + ports.confirmOpen = false + return + } + language := a.language() + pending := *ports.confirm + target := net.JoinHostPort(pending.host, strconv.Itoa(int(pending.key.port))) + closed := ui.Modal(c.Part("ports-confirm"), &ports.confirmOpen, i18n.Shared(language, "desktop.remote.ports.confirmTitle"), func() { + ui.Paragraph(c, i18n.SharedFormat(language, "desktop.remote.ports.confirmBody", + map[string]string{"target": target, "name": p.remote.name}), 5).Color(a.colors.Warning) + }, func() { + if ui.Button(c, i18n.Shared(language, "desktop.remote.ports.confirmCancel")).Outline().Clicked() { + ports.confirmOpen = false + } + if ui.Button(c, i18n.Shared(language, "desktop.remote.ports.confirmForward")).Clicked() { + c.After(func() { a.confirmRemotePort(p) }) + } + }) + if closed || !ports.confirmOpen { + if ports.confirm != nil { + a.operationRejected("remote_port_forward", "target_declined") + } + ports.confirm, ports.confirmOpen = nil, false + } +} + +// remotePortsLocal declares the dialog the local port of a row is chosen in. Closing it changes +// nothing. +func (a *App) remotePortsLocal(c ui.C, p *project) { + ports := &p.remote.ports + if ports.local == nil { + ports.localOpen = false + return + } + language := a.language() + row, _ := ports.row(*ports.local) + remote, _ := remotePortsRemote(language, row) + closed := ui.Modal(c.Part("ports-local"), &ports.localOpen, i18n.Shared(language, "desktop.remote.ports.localTitle"), func() { + ui.Paragraph(c, i18n.SharedFormat(language, "desktop.remote.ports.localBody", + map[string]string{"remote": remote, "name": p.remote.name}), 5).Color(a.colors.Text) + submitted := ui.TextField(c.Part("ports-local-field"), &ports.localField, i18n.Shared(language, "desktop.remote.ports.localLabel"), + i18n.Shared(language, "desktop.remote.ports.localLabel")).FillWidth().Submitted() + if ports.localInvalid { + ui.Text(c, i18n.Shared(language, "desktop.remote.ports.localInvalid")).FontSize(12).Color(a.theme.Danger) + } + if submitted { + c.After(func() { a.applyRemoteLocalPort(p) }) + } + }, func() { + if ui.Button(c, i18n.Shared(language, "desktop.remote.ports.localCancel")).Outline().Clicked() { + ports.localOpen = false + } + if ui.Button(c, i18n.Shared(language, "desktop.remote.ports.localApply")).Clicked() { + c.After(func() { a.applyRemoteLocalPort(p) }) + } + }) + if closed || !ports.localOpen { + ports.local, ports.localOpen, ports.localInvalid = nil, false, false + } +} + +// remotePortsStatusItem declares the status bar's count of the forwards of the open remote +// workspace, next to its connection, while it forwards a port. A click opens the Ports window. +func (a *App) remotePortsStatusItem(c ui.C) { + p := a.project + if p == nil || p.remote == nil || len(p.remote.ports.forwards) == 0 { + return + } + language := a.language() + count := strconv.Itoa(len(p.remote.ports.forwards)) + k := c.Part("remote-ports") + button := ui.Row(k).Height(chromeStatusItem).Shrink(0).Items(ui.Center).Gap(chromeGap).PadX(chromeStatusPad). + Radius(a.theme.Metrics.RadiusItem()). + Hover(ui.Look{}.Background(a.colors.Hover)). + HitWith(ui.ID(k), i18n.Shared(language, "desktop.remote.ports.statusLabel"), gfx.HitOptions{ + Role: gfx.RoleButton, + Cursor: gfx.PointerCursorHand, + Value: count, + }). + Tooltip(i18n.SharedFormat(language, "desktop.remote.ports.statusTooltip", map[string]string{"count": count})) + button.Children(func() { + ui.Icon(k, icons.ArrowLeftRight).Size(chromeMarkSize, chromeMarkSize).Shrink(0).Color(a.colors.Accent) + a.chromeStatusLabel(k, count) + }) + if button.Clicked() { + c.After(func() { + a.performed("remote.ports.status", surfaceButton) + a.openToolWindow(itemPorts) + }) + } +} diff --git a/desktop/internal/workbench/remote_ports_visual_test.go b/desktop/internal/workbench/remote_ports_visual_test.go new file mode 100644 index 000000000..843bac963 --- /dev/null +++ b/desktop/internal/workbench/remote_ports_visual_test.go @@ -0,0 +1,148 @@ +//go:build vivahead && lithevisual + +package workbench + +import ( + "os" + "path/filepath" + "strings" + "testing" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/1lck/Lithe-IDEA/desktop/internal/remoteplaceholder" + "github.com/1lck/Lithe-IDEA/desktop/internal/remoteserver" + "github.com/1lck/Lithe-IDEA/desktop/internal/store" + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/headless" +) + +// TestVisualRemotePorts captures the Ports tool window of a remote workspace: the host's listening +// ports by the addresses the host serves them on, with one forwarded on a free local port because +// its own was taken and a URL added by hand, the row's menu, the question a target outside the +// host's loopback interface asks, and the dialog a forward's local port is chosen in. +func TestVisualRemotePorts(t *testing.T) { + out := os.Getenv("LITHE_VISUAL_OUTPUT_DIR") + if out == "" { + t.Skip("set LITHE_VISUAL_OUTPUT_DIR") + } + if err := os.MkdirAll(out, 0755); err != nil { + t.Fatal(err) + } + for _, look := range []struct{ theme, language, suffix string }{ + {"light", "en-US", "light-en-US"}, + {"dark", "zh-Hans", "dark-zh-CN"}, + } { + t.Run(look.suffix, func(t *testing.T) { + prefs := store.At(t.TempDir()) + if err := prefs.Save(settingsFile, settings{Theme: themeChoice(look.theme), Language: look.language, DisableAutoSave: true}); err != nil { + t.Fatal(err) + } + var session *headless.Session + kernel := &remoteHostKernel{testKernel: &testKernel{Client: core.NewClient()}} + // The folder was kept in safe mode before, so it opens without the trust question. + kernel.git.trust = map[string]string{remoteTestFolder: core.WorkspaceDistrusted} + kernel.ports.listening = []core.RemoteListeningPort{ + {Address: "0.0.0.0", Port: 8080, PID: 41, Process: "node"}, + {Address: "::", Port: 8080, PID: 41, Process: "node"}, + {Address: "127.0.0.1", Port: 5432, PID: 7, Process: "postgres"}, + {Address: "10.0.0.5", Port: 9000}, + } + kernel.ports.taken = map[uint16]bool{8080: true} + h := newHarnessWithDriver(t, Options{Kernel: kernel, Store: prefs, Languages: []string{look.language}}, func(config app.Config) (*app.Driver, func(), error) { + config.Width, config.Height = 1200, 760 + var err error + session, err = headless.Open(config, nil, headless.Options{}) + if err != nil { + return nil, nil, err + } + return session.Driver(), session.Close, nil + }) + lang := h.app.language() + shot := func(scene string) { + t.Helper() + // The scenes set the window's state directly, which does not ask for a frame. + h.app.invalidator.Invalidate() + h.settleChain() + if err := session.Screenshot(filepath.Join(out, "remote-ports-"+scene+"-"+look.suffix+".png")); err != nil { + t.Fatal(err) + } + } + timers := &remoteTimers{} + anchor := filepath.Join(t.TempDir(), remoteplaceholder.AnchorName) + h.app.remoteBundle = func() (remoteserver.Bundle, error) { + return remoteserver.Bundle{Version: "0.0.0-visual", Builds: []remoteserver.Build{{ + Target: "x86_64-unknown-linux-musl", Path: "/bundle/lithe-server", SHA256: strings.Repeat("0", 64), + }}}, nil + } + h.app.remoteAnchor = func() (string, error) { return anchor, nil } + h.app.remoteAfter = timers.start + h.app.openRemote(surfaceMenu) + h.settleChain() + r := &h.app.remote + r.selectNew() + r.form.name.SetText("Build box") + r.form.host.SetText(remoteTestHost) + r.form.user.SetText("dev") + h.app.saveRemote() + h.settleChain() + if r.err != "" || r.fieldErr.field != "" { + t.Fatalf("saving the connection: %q %+v", r.err, r.fieldErr) + } + + p := h.openRemoteTestProject(t) + h.app.openToolWindow(itemPorts) + h.redraw() + ports := &p.remote.ports + h.await("the Ports window's first reading", func() bool { return ports.listed || ports.readFailed != "" }) + if !ports.listed { + t.Fatalf("reading the ports failed: %s", ports.readFailed) + } + + // Nothing is forwarded until asked: 8080, which the host serves on both families, is + // forwarded on a free local port because another program uses its own, and a URL is + // added by hand. + for _, row := range ports.rows() { + if row.key.port == 8080 { + h.app.forwardRemotePort(p, row.key, row.target(), false, surfaceButton) + } + } + h.await("the forward", func() bool { return len(ports.forwards) == 1 && len(ports.busy) == 0 }) + ports.add.SetText("http://localhost:5173/app") + h.app.addRemotePort(p, surfaceButton) + h.await("the added URL's forward", func() bool { return len(ports.forwards) == 2 && len(ports.busy) == 0 }) + shot("list") + + both := i18n.SharedFormat(lang, "desktop.remote.ports.remoteMore", map[string]string{"address": "0.0.0.0:8080", "count": "1"}) + h.rightClickAt(h.portRowControl(both, both)) + h.settleChain() + if !h.shows(i18n.Shared(lang, "desktop.remote.ports.changeLocal")) { + t.Fatal("the row's menu did not open") + } + shot("menu") + if err := h.driver.Key(gfx.KeyEscape, 0); err != nil { + t.Fatal(err) + } + h.settleChain() + + for _, row := range ports.rows() { + if row.key.host == "10.0.0.5" { + h.app.forwardRemotePort(p, row.key, row.target(), false, surfaceButton) + } + } + h.await("the question", func() bool { return ports.confirm != nil && len(ports.busy) == 0 }) + shot("confirm") + ports.confirm = nil + h.settleChain() + + h.app.chooseRemoteLocalPort(p, remotePortKey{port: 8080}, surfaceContextMenu) + h.settleChain() + if ports.local == nil { + t.Fatal("the local port dialog did not open") + } + ports.localField.SetText("18080") + shot("local") + }) + } +} diff --git a/desktop/internal/workbench/remote_workspace.go b/desktop/internal/workbench/remote_workspace.go index 368d1141a..6906f4c93 100644 --- a/desktop/internal/workbench/remote_workspace.go +++ b/desktop/internal/workbench/remote_workspace.go @@ -107,6 +107,8 @@ type remoteProject struct { watch *remoteWatch watchWait remoteWatchWait watchNotified bool + // ports is the Ports tool window's state (remote_ports.go). + ports remotePorts // closed is set once the project closes; nothing of the workspace runs afterwards. closed bool } @@ -342,6 +344,8 @@ func (a *App) loseRemote(p *project, session string, err error) { a.backgroundFailed("remote_session_lost", remoteLogError(err)) a.stopRemoteWatch(p) a.closeGitObservation(p) + // Core stops the session's forwards with it. + r.ports.reset() r.session, r.misses = "", 0 r.binding.Detach() r.stopRemoteTimer() @@ -458,6 +462,7 @@ func (a *App) closeRemoteWorkspace(p *project) { } r.closed = true r.stopRemoteTimer() + r.ports.reset() a.stopRemoteWatch(p) if r.reconnecting != nil { r.reconnecting.cancel() @@ -502,6 +507,8 @@ func (a *App) openRemoteProject(target remoteTarget) { // Its first terminal runs on the host once it is shown, over the session attached below. a.openTerminals(p) a.project = p + // The tool windows of a remote workspace, such as Ports, are shown while it is open. + a.chrome.setRemote(true) a.notice = "" a.logView.reset() a.worktreeView.reset() diff --git a/desktop/internal/workbench/remote_workspace_test.go b/desktop/internal/workbench/remote_workspace_test.go index 675b6bffe..ebb8fdcec 100644 --- a/desktop/internal/workbench/remote_workspace_test.go +++ b/desktop/internal/workbench/remote_workspace_test.go @@ -39,8 +39,9 @@ var remoteTestFolders = map[string][]core.RemoteDirectoryEntry{ // remoteHostKernel stands in for a host over SSH: it opens numbered sessions, lists // remoteTestFolders, answers heartbeats as the test says, lists the workspace's tree only for a // request that carries the workspace's session, keeps the files of files -// (remote_documents_test.go), watches the workspace's folder (remote_watch_test.go) and searches -// it (remote_search_test.go). Everything else is the real Core. +// (remote_documents_test.go), watches the workspace's folder (remote_watch_test.go), searches +// it (remote_search_test.go) and forwards the host's ports (remote_ports_test.go). Everything else +// is the real Core. type remoteHostKernel struct { *testKernel mu sync.Mutex @@ -77,6 +78,8 @@ type remoteHostKernel struct { search remoteHostSearch // git is the workspace's trust and the host's repository (remote_git_test.go). git remoteHostGit + // ports are the host's listening ports and the sessions' forwards (remote_ports_test.go). + ports remoteHostPorts } // remoteTestTree is the workspace's tree the Project tool window lists by default. diff --git a/desktop/internal/workbench/shell_view.go b/desktop/internal/workbench/shell_view.go index 4ba95a5af..c03504cbe 100644 --- a/desktop/internal/workbench/shell_view.go +++ b/desktop/internal/workbench/shell_view.go @@ -139,6 +139,9 @@ func (a *App) shellPanel(c ui.C, s slot, index int, hidden *slot) ui.Box { if tool.id == itemNotifications { a.notificationClearButton(hk) } + if tool.id == itemPorts && p != nil { + a.remotePortsActions(c, p) + } if tabbed && p != nil { a.drawGitActions(c, p) } @@ -163,10 +166,10 @@ func (a *App) shellPanel(c ui.C, s slot, index int, hidden *slot) ui.Box { // remoteToolWindow reports whether the tool window id works in a remote workspace: the project // listing, search and terminals run on the host, and so do Git's log and commit once the -// workspace is trusted (in safe mode they say so, as in a local project). +// workspace is trusted (in safe mode they say so, as in a local project); Ports exists only there. func remoteToolWindow(id string) bool { switch id { - case itemProject, itemNotifications, itemTerminal, itemFind, itemGit, itemCommit: + case itemProject, itemNotifications, itemTerminal, itemFind, itemGit, itemCommit, itemPorts: return true } return false @@ -228,6 +231,8 @@ func (a *App) toolBody(c ui.C, tool item, p *project) { a.debugView(c, p) case itemNotifications: a.notificationsToolBody(c.Part("notificationHistory")) + case itemPorts: + a.remotePortsView(c, p) default: switch { case tool.tool != nil && tool.tool.View != "": diff --git a/docs/assets/remote-ports/README.md b/docs/assets/remote-ports/README.md new file mode 100644 index 000000000..bba7bc078 --- /dev/null +++ b/docs/assets/remote-ports/README.md @@ -0,0 +1,20 @@ +# 远程工作区“端口”工具窗口(#2231)无头测试截图 + +来自生产 Viva Page 的无头渲染,由 `TestVisualRemotePorts` 生成。主机由测试替换的内核模拟:主机上 `node` 同时在 `0.0.0.0:8080` 和 `[::]:8080` 监听,`postgres` 在 `127.0.0.1:5432` 监听,另有一个进程未知的 `10.0.0.5:9000`;本机的 8080 端口被另一个程序占用。测试不启动 OpenSSH,也不在本机真正监听端口。截图覆盖深色与浅色主题、中文与英文界面,用于确认: + +- 打开工作区和窗口都不会自动转发任何端口:8080 和手动添加的网址是测试里点了“转发”之后才转发的; +- 远端端口列带上主机监听的 IP 地址:同一端口在多个地址监听时显示第一个地址和其余数量(`0.0.0.0:8080 +1`),悬停提示列出全部地址; +- 顶部输入框接受端口、主机:端口或网址;手动添加的 `http://localhost:5173/app` 按输入的样子显示,转发到主机上提供该端口的回环地址,“在浏览器中打开”把主机地址换成本机地址、保留路径; +- 列表列出远端端口、本机地址、进程、来源(监听发现、手动添加)和状态;8080 的本机端口被占用,改用空闲端口 40001,本机地址用警告色显示;状态栏显示已转发的数量; +- 已转发行的右键菜单:在浏览器中打开、复制本机地址、更改本机端口…、停止转发; +- 转发 `10.0.0.5:9000` 这种主机回环地址以外的目标前先询问(S28); +- “更改本机端口…”打开的对话框:说明转发到本机回环地址的哪个端口,端口被占用时改用空闲端口并在行里注明。 + +截图不代表 macOS/Windows 原生窗口验收,也不代表真实 SSH 主机上的整机验收。 + +| 场景 | 浅色英文 | 深色中文 | +| --- | --- | --- | +| 端口列表 | [浅色英文](remote-ports-list-light-en-US.png) | [深色中文](remote-ports-list-dark-zh-CN.png) | +| 已转发行的右键菜单 | [浅色英文](remote-ports-menu-light-en-US.png) | [深色中文](remote-ports-menu-dark-zh-CN.png) | +| 转发回环地址以外的目标前询问 | [浅色英文](remote-ports-confirm-light-en-US.png) | [深色中文](remote-ports-confirm-dark-zh-CN.png) | +| 选择本机端口 | [浅色英文](remote-ports-local-light-en-US.png) | [深色中文](remote-ports-local-dark-zh-CN.png) | diff --git a/docs/assets/remote-ports/remote-ports-confirm-dark-zh-CN.png b/docs/assets/remote-ports/remote-ports-confirm-dark-zh-CN.png new file mode 100644 index 000000000..bb9e24acd Binary files /dev/null and b/docs/assets/remote-ports/remote-ports-confirm-dark-zh-CN.png differ diff --git a/docs/assets/remote-ports/remote-ports-confirm-light-en-US.png b/docs/assets/remote-ports/remote-ports-confirm-light-en-US.png new file mode 100644 index 000000000..55e95fafd Binary files /dev/null and b/docs/assets/remote-ports/remote-ports-confirm-light-en-US.png differ diff --git a/docs/assets/remote-ports/remote-ports-list-dark-zh-CN.png b/docs/assets/remote-ports/remote-ports-list-dark-zh-CN.png new file mode 100644 index 000000000..d3246647e Binary files /dev/null and b/docs/assets/remote-ports/remote-ports-list-dark-zh-CN.png differ diff --git a/docs/assets/remote-ports/remote-ports-list-light-en-US.png b/docs/assets/remote-ports/remote-ports-list-light-en-US.png new file mode 100644 index 000000000..ae56c01b7 Binary files /dev/null and b/docs/assets/remote-ports/remote-ports-list-light-en-US.png differ diff --git a/docs/assets/remote-ports/remote-ports-local-dark-zh-CN.png b/docs/assets/remote-ports/remote-ports-local-dark-zh-CN.png new file mode 100644 index 000000000..de5490799 Binary files /dev/null and b/docs/assets/remote-ports/remote-ports-local-dark-zh-CN.png differ diff --git a/docs/assets/remote-ports/remote-ports-local-light-en-US.png b/docs/assets/remote-ports/remote-ports-local-light-en-US.png new file mode 100644 index 000000000..f6eba1fc6 Binary files /dev/null and b/docs/assets/remote-ports/remote-ports-local-light-en-US.png differ diff --git a/docs/assets/remote-ports/remote-ports-menu-dark-zh-CN.png b/docs/assets/remote-ports/remote-ports-menu-dark-zh-CN.png new file mode 100644 index 000000000..6cda40d10 Binary files /dev/null and b/docs/assets/remote-ports/remote-ports-menu-dark-zh-CN.png differ diff --git a/docs/assets/remote-ports/remote-ports-menu-light-en-US.png b/docs/assets/remote-ports/remote-ports-menu-light-en-US.png new file mode 100644 index 000000000..768090cab Binary files /dev/null and b/docs/assets/remote-ports/remote-ports-menu-light-en-US.png differ diff --git a/scripts/desktop/build-desktop-core.sh b/scripts/desktop/build-desktop-core.sh index 3d435d381..4f6463d70 100755 --- a/scripts/desktop/build-desktop-core.sh +++ b/scripts/desktop/build-desktop-core.sh @@ -317,11 +317,12 @@ PINNED_CORE_REPOSITORY="https://github.com/Lithe-IDEA/Lithe-core-rust.git" # Lithe-core-rust main at 66a1476: #147 starts, stops and lists port forwards # (remote.startForward, remote.stopForward, remote.forwards) and names the process of each # listening port (S28/S29, #2231). -# Lithe-core-rust #154 at 2304b57 (on main 68a69a6): remote.parseAddress, remote.effectiveSettings, +# Lithe-core-rust main at 822f871: #154 remote.parseAddress, remote.effectiveSettings, # remote.sshConfigHosts and remote.mottyHosts; the connections query, import and markConnected; -# remoteStage events and classified authentication questions (#2231). Move to the main commit once -# #154 merges. -PINNED_CORE_REVISION="a73d60f387f91935c12003804303b12bfba79af9" +# remoteStage events and classified authentication questions (#2231); #155 build preferences. +# Lithe-core-rust main at ae593eb: #156 remote.parseForwardAddress reads a port, host:port or URL +# typed into the Ports window (#2231). +PINNED_CORE_REVISION="ae593eb1cca7c5529823f8339608d7e0ba3dd6ec" PROFILE="debug" CHECKOUT_ONLY="no" while [[ $# -gt 0 ]]; do diff --git a/shared/i18n/features/remote-ports.json b/shared/i18n/features/remote-ports.json new file mode 100644 index 000000000..75cb11032 --- /dev/null +++ b/shared/i18n/features/remote-ports.json @@ -0,0 +1,509 @@ +{ + "schemaVersion": 1, + "messages": [ + { + "id": "desktop.remote.ports.title", + "description": "Tool stripe button and header of the Ports tool window of a remote workspace, which lists the host's listening ports and the forwards to them", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.ports.help", + "description": "Ports tool window: tip of the info glyph in the header: forwards listen only on this computer's loopback address, every local program can reach them, and the host cannot reach back", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.ports.columnRemote", + "description": "Ports tool window: column of the port as the host sees it", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.ports.columnLocal", + "description": "Ports tool window: column of the address the forward listens on, on this computer", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.ports.columnProcess", + "description": "Ports tool window: column of the host process that listens on the port", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.ports.columnSource", + "description": "Ports tool window: column of how the port got into the list", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.ports.columnStatus", + "description": "Ports tool window: column of whether the port is forwarded", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.ports.sourceListening", + "description": "Ports tool window, Source column: the port was found listening on the host", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.ports.sourceManual", + "description": "Ports tool window, Source column: the user added the port by hand", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.ports.process", + "description": "Ports tool window, Process column: the command name and process ID of the host process that listens", + "platforms": [ + "desktop" + ], + "parameters": { + "process": "string", + "pid": "string" + } + }, + { + "id": "desktop.remote.ports.processUnknown", + "description": "Ports tool window, Process column: the host did not say which process listens, for example one run by another account", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.ports.statusNotForwarded", + "description": "Ports tool window, Status column: the port is not forwarded", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.ports.statusForwarded", + "description": "Ports tool window, Status column: the port is forwarded", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.ports.statusForwarding", + "description": "Ports tool window, Status column: the forward is being started", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.ports.statusStopping", + "description": "Ports tool window, Status column: the forward is being stopped", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.ports.statusFailed", + "description": "Ports tool window, Status column: forwarding or stopping the port failed, with the reason", + "platforms": [ + "desktop" + ], + "parameters": { + "reason": "string" + } + }, + { + "id": "desktop.remote.ports.localChanged", + "description": "Ports tool window, Local Address column: tooltip of a forward whose usual local port was taken on this computer, so another was chosen", + "platforms": [ + "desktop" + ], + "parameters": { + "requested": "string", + "port": "string" + } + }, + { + "id": "desktop.remote.ports.forward", + "description": "Ports tool window: button and menu item that forwards the row's port", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.ports.stop", + "description": "Ports tool window: button and menu item that stops forwarding the row's port", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.ports.stopAll", + "description": "Ports tool window: header button that stops every forward of the workspace", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.ports.openBrowser", + "description": "Ports tool window: button and menu item that opens the forward's local address in the default browser, with the scheme and path of the URL the port was added as", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.ports.copyAddress", + "description": "Ports tool window: button and menu item that copies the forward's local address, as a URL when the port was added as one", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.ports.remove", + "description": "Ports tool window: menu item that removes a port the user added and that is not forwarded", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.ports.addLabel", + "description": "Ports tool window: accessible label of the field where a port to forward is typed", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.ports.addPlaceholder", + "description": "Ports tool window: placeholder of the field where a port to forward is typed, as a port alone, host:port or a URL", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.ports.add", + "description": "Ports tool window: button that adds and forwards the typed port", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.ports.addInvalid", + "description": "Ports tool window: the typed text is not a port, host:port or a URL with a port or a known scheme", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.ports.addCredentials", + "description": "Ports tool window: the typed URL contains a user name or password, which the window refuses so it is never stored or shown", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.ports.remoteMore", + "description": "Ports tool window, Remote Port column: the first address the host listens on for the port, with how many other addresses it also listens on", + "platforms": [ + "desktop" + ], + "parameters": { + "address": "string", + "count": "string" + } + }, + { + "id": "desktop.remote.ports.remoteListening", + "description": "Ports tool window, Remote Port column: tooltip listing every address the host listens on for the port, separated by commas", + "platforms": [ + "desktop" + ], + "parameters": { + "addresses": "string" + } + }, + { + "id": "desktop.remote.ports.remoteUrlListening", + "description": "Ports tool window, Remote Port column: tooltip of a port the user added as a URL, giving the whole URL and every address the host listens on for its port, separated by commas", + "platforms": [ + "desktop" + ], + "parameters": { + "url": "string", + "addresses": "string" + } + }, + { + "id": "desktop.remote.ports.empty", + "description": "Ports tool window: the host has no listening port and the user added none", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.ports.loading", + "description": "Ports tool window: the first listing of the host's ports has not arrived", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.ports.disconnected", + "description": "Ports tool window: the workspace has no connection; its forwards ended with the session", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.ports.readFailed", + "description": "Ports tool window: reading the host's listening ports failed, with the reason", + "platforms": [ + "desktop" + ], + "parameters": { + "reason": "string" + } + }, + { + "id": "desktop.remote.ports.limit", + "description": "Ports tool window: the connection already runs the most forwards Core allows", + "platforms": [ + "desktop" + ], + "parameters": { + "maximum": "string" + } + }, + { + "id": "desktop.remote.ports.invalidTarget", + "description": "Ports tool window: Core refused the forward's target host or port", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.ports.confirmTitle", + "description": "Ports tool window: title of the dialog that asks before forwarding to an address that is not the host's own loopback address", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.ports.confirmBody", + "description": "Ports tool window: body of the dialog that asks before forwarding to an address that is not the host's own loopback address", + "platforms": [ + "desktop" + ], + "parameters": { + "target": "string", + "name": "string" + } + }, + { + "id": "desktop.remote.ports.confirmForward", + "description": "Ports tool window: button of the confirmation dialog that forwards anyway", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.ports.confirmCancel", + "description": "Ports tool window: button of the confirmation dialog that forwards nothing", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.ports.statusLabel", + "description": "Status bar of a remote workspace: accessible label of the item that counts the forwarded ports and opens the Ports tool window", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.ports.statusTooltip", + "description": "Status bar of a remote workspace: tooltip of the item that counts the forwarded ports", + "platforms": [ + "desktop" + ], + "parameters": { + "count": "string" + } + }, + { + "id": "desktop.remote.ports.changeLocal", + "description": "Ports tool window: context menu item of a forwarded port that forwards it on another local port", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.ports.forwardLocal", + "description": "Ports tool window: context menu item of a port not forwarded yet that forwards it on a local port the user chooses", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.ports.localTitle", + "description": "Ports tool window: title of the dialog the local port of a forward is chosen in", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.ports.localBody", + "description": "Ports tool window: body of the dialog the local port of a forward is chosen in", + "platforms": [ + "desktop" + ], + "parameters": { + "remote": "string", + "name": "string" + } + }, + { + "id": "desktop.remote.ports.localLabel", + "description": "Ports tool window: label and placeholder of the field of the local port dialog", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.ports.localInvalid", + "description": "Ports tool window: shown under the local port field when its text is not a port number", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.ports.localApply", + "description": "Ports tool window: button of the local port dialog that forwards on the typed port", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.ports.localCancel", + "description": "Ports tool window: button of the local port dialog that changes nothing", + "platforms": [ + "desktop" + ] + } + ], + "locales": { + "en-US": { + "desktop.remote.ports.title": "Ports", + "desktop.remote.ports.help": "A forwarded port listens only on this computer's loopback address (127.0.0.1). Every program on this computer can connect to it, not just Lithe. The host cannot reach this computer through it.", + "desktop.remote.ports.columnRemote": "Remote Port", + "desktop.remote.ports.columnLocal": "Local Address", + "desktop.remote.ports.columnProcess": "Process", + "desktop.remote.ports.columnSource": "Source", + "desktop.remote.ports.columnStatus": "Status", + "desktop.remote.ports.sourceListening": "Listening", + "desktop.remote.ports.sourceManual": "Added", + "desktop.remote.ports.process": "{process} (PID {pid})", + "desktop.remote.ports.processUnknown": "Unknown", + "desktop.remote.ports.statusNotForwarded": "Not forwarded", + "desktop.remote.ports.statusForwarded": "Forwarded", + "desktop.remote.ports.statusForwarding": "Forwarding…", + "desktop.remote.ports.statusStopping": "Stopping…", + "desktop.remote.ports.statusFailed": "Failed: {reason}", + "desktop.remote.ports.localChanged": "Port {requested} is in use on this computer, so {port} is used instead.", + "desktop.remote.ports.forward": "Forward", + "desktop.remote.ports.stop": "Stop Forwarding", + "desktop.remote.ports.stopAll": "Stop All Forwards", + "desktop.remote.ports.openBrowser": "Open in Browser", + "desktop.remote.ports.copyAddress": "Copy Local Address", + "desktop.remote.ports.remove": "Remove", + "desktop.remote.ports.addLabel": "Port to Forward", + "desktop.remote.ports.addPlaceholder": "Port, host:port or URL", + "desktop.remote.ports.add": "Forward Port", + "desktop.remote.ports.addInvalid": "Enter a port from 1 to 65535, host:port, or a URL such as http://localhost:3000.", + "desktop.remote.ports.addCredentials": "The address can't include a user name or password.", + "desktop.remote.ports.remoteMore": "{address} +{count}", + "desktop.remote.ports.remoteListening": "Listening on {addresses}", + "desktop.remote.ports.remoteUrlListening": "{url}, listening on {addresses}", + "desktop.remote.ports.empty": "No ports are listening on the host. Type a port above to forward it anyway.", + "desktop.remote.ports.loading": "Reading the host's listening ports…", + "desktop.remote.ports.disconnected": "Not connected. Forwards end with the connection; forward the ports again after reconnecting.", + "desktop.remote.ports.readFailed": "Could not read the host's listening ports: {reason}", + "desktop.remote.ports.limit": "This connection already forwards {maximum} ports, the most allowed. Stop one first.", + "desktop.remote.ports.invalidTarget": "The host or port is not valid.", + "desktop.remote.ports.confirmTitle": "Forward to Another Address?", + "desktop.remote.ports.confirmBody": "{target} is not the loopback address of {name}. Forwarding it lets every program on this computer reach that address through the host. Continue only if you trust it.", + "desktop.remote.ports.confirmForward": "Forward", + "desktop.remote.ports.confirmCancel": "Cancel", + "desktop.remote.ports.statusLabel": "Forwarded Ports", + "desktop.remote.ports.statusTooltip": "{count} forwarded. Click to open Ports.", + "desktop.remote.ports.changeLocal": "Change Local Port…", + "desktop.remote.ports.forwardLocal": "Forward to Local Port…", + "desktop.remote.ports.localTitle": "Local Port", + "desktop.remote.ports.localBody": "Forward {remote} on {name} to this port of this computer's loopback address. If another program uses it, a free port is used instead and the row says so.", + "desktop.remote.ports.localLabel": "Local port", + "desktop.remote.ports.localInvalid": "Enter a port number from 1 to 65535.", + "desktop.remote.ports.localApply": "Forward", + "desktop.remote.ports.localCancel": "Cancel" + }, + "zh-CN": { + "desktop.remote.ports.title": "端口", + "desktop.remote.ports.help": "转发的端口只监听本机的回环地址(127.0.0.1)。本机上的所有程序都能连接,不只是 Lithe;主机无法通过它反向访问本机。", + "desktop.remote.ports.columnRemote": "远端端口", + "desktop.remote.ports.columnLocal": "本机地址", + "desktop.remote.ports.columnProcess": "进程", + "desktop.remote.ports.columnSource": "来源", + "desktop.remote.ports.columnStatus": "状态", + "desktop.remote.ports.sourceListening": "监听发现", + "desktop.remote.ports.sourceManual": "手动添加", + "desktop.remote.ports.process": "{process}(PID {pid})", + "desktop.remote.ports.processUnknown": "未知", + "desktop.remote.ports.statusNotForwarded": "未转发", + "desktop.remote.ports.statusForwarded": "已转发", + "desktop.remote.ports.statusForwarding": "正在转发…", + "desktop.remote.ports.statusStopping": "正在停止…", + "desktop.remote.ports.statusFailed": "失败:{reason}", + "desktop.remote.ports.localChanged": "本机端口 {requested} 已被占用,改用 {port}。", + "desktop.remote.ports.forward": "转发", + "desktop.remote.ports.stop": "停止转发", + "desktop.remote.ports.stopAll": "停止全部转发", + "desktop.remote.ports.openBrowser": "在浏览器中打开", + "desktop.remote.ports.copyAddress": "复制本机地址", + "desktop.remote.ports.remove": "移除", + "desktop.remote.ports.addLabel": "要转发的端口", + "desktop.remote.ports.addPlaceholder": "端口、主机:端口或网址", + "desktop.remote.ports.add": "转发端口", + "desktop.remote.ports.addInvalid": "请输入 1–65535 的端口、“主机:端口”,或 http://localhost:3000 这样的网址。", + "desktop.remote.ports.addCredentials": "地址不能包含用户名或密码。", + "desktop.remote.ports.remoteMore": "{address} +{count}", + "desktop.remote.ports.remoteListening": "监听地址:{addresses}", + "desktop.remote.ports.remoteUrlListening": "{url},监听地址:{addresses}", + "desktop.remote.ports.empty": "主机上没有正在监听的端口。也可以在上方输入端口直接转发。", + "desktop.remote.ports.loading": "正在读取主机上的监听端口…", + "desktop.remote.ports.disconnected": "未连接。转发随连接一起结束,重新连接后需要再次转发。", + "desktop.remote.ports.readFailed": "无法读取主机上的监听端口:{reason}", + "desktop.remote.ports.limit": "此连接已转发 {maximum} 个端口,达到上限,请先停止一个。", + "desktop.remote.ports.invalidTarget": "主机或端口无效。", + "desktop.remote.ports.confirmTitle": "转发到其他地址?", + "desktop.remote.ports.confirmBody": "{target} 不是 {name} 自身的回环地址。转发后,本机上的所有程序都能经由主机访问这个地址。请确认你信任它后再继续。", + "desktop.remote.ports.confirmForward": "转发", + "desktop.remote.ports.confirmCancel": "取消", + "desktop.remote.ports.statusLabel": "已转发的端口", + "desktop.remote.ports.statusTooltip": "已转发 {count} 个端口,点击打开“端口”窗口。", + "desktop.remote.ports.changeLocal": "更改本机端口…", + "desktop.remote.ports.forwardLocal": "转发到指定本机端口…", + "desktop.remote.ports.localTitle": "本机端口", + "desktop.remote.ports.localBody": "把 {name} 上的 {remote} 转发到本机回环地址的这个端口。如果它已被其他程序占用,会改用一个空闲端口,并在这一行注明。", + "desktop.remote.ports.localLabel": "本机端口", + "desktop.remote.ports.localInvalid": "请输入 1 到 65535 之间的端口号。", + "desktop.remote.ports.localApply": "转发", + "desktop.remote.ports.localCancel": "取消" + } + } +} diff --git a/shared/platform-feature-matrix/features/remote-workspace.json b/shared/platform-feature-matrix/features/remote-workspace.json index d82910366..2ef2dda03 100644 --- a/shared/platform-feature-matrix/features/remote-workspace.json +++ b/shared/platform-feature-matrix/features/remote-workspace.json @@ -2,7 +2,7 @@ "id": "remote-workspace", "area": "工作区", "group": "远程开发", - "capability": "远程连接、远程路径工作区、主机文件编辑与监听、主机终端、主机搜索与替换、远程信任与主机 Git", + "capability": "远程连接、远程路径工作区、主机文件编辑与监听、主机终端、主机搜索与替换、远程信任与主机 Git、端口转发", "macos": { "implementationStatus": "partial", "verificationStatus": "pending", @@ -39,7 +39,13 @@ "desktop/internal/workbench/git_observation.go", "desktop/internal/workbench/git_exclude.go", "desktop/internal/workbench/gitreview.go", - "desktop/internal/remoteplaceholder/remoteplaceholder_test.go" + "desktop/internal/remoteplaceholder/remoteplaceholder_test.go", + "desktop/internal/core/remote_forward.go", + "desktop/internal/core/remote_helpers_test.go", + "desktop/internal/workbench/remote_ports.go", + "desktop/internal/workbench/remote_ports_view.go", + "desktop/internal/workbench/remote_ports_test.go", + "desktop/internal/workbench/remote_ports_visual_test.go" ] }, "windows": { @@ -68,11 +74,14 @@ "desktop/internal/workbench/workspace_trust.go", "desktop/internal/workbench/git_observation.go", "desktop/internal/workbench/git_exclude.go", - "desktop/internal/workbench/gitreview.go" + "desktop/internal/workbench/gitreview.go", + "desktop/internal/core/remote_forward.go", + "desktop/internal/workbench/remote_ports.go", + "desktop/internal/workbench/remote_ports_view.go" ] }, "owner": "Remote", - "verification": "在“远程开发”窗口选中已保存的 Linux SSH 连接点“连接”:SSH 询问出现在窗口中,连接后窗口改为主机的文件夹选择,从主目录开始列出子文件夹(跳过名称不是 UTF-8 的条目并说明数量),可输入 ~ 或 / 开头的路径跳转,不存在的路径说明原因且不能打开;“返回”断开这次会话回到连接表单。选中文件夹点“打开”:新标签页打开远程工作区,窗口标题为“文件夹 [SSH: 连接名]”,项目树经 Core 列出主机目录(本机占位目录始终为空),右键只有复制主机路径和刷新;以安全模式打开的文件夹,编辑器上方说明可以浏览、编辑、保存和搜索主机文件,信任文件夹后才能用 Git;受信任的文件夹说明文件、终端和 Git 都在主机上,运行、调试和语言服务器暂不可用;空白编辑区提示 Search Everywhere 和 Find in Files。在项目树双击文件:编辑器经会话读取主机文件(不超过 16 MiB),保存时带上打开时的大小和修改时间写回主机,新建的文件只在主机上不存在时创建;主机上的文件期间被别人改过时保存被拒绝并显示外部修改冲突,“加载磁盘版本”载入主机内容,本机占位目录始终为空。超过 8 MiB 的保存说明主机单次保存上限,编辑内容保留;主机上缺失、无权限、不是普通文件、超时和连接断开分别说明原因,连接断开后自动重连并把打开的文档和主机重新比对。图片、PDF 等查看器、文件夹外的文件、本地历史和插件终端都被拒绝并提示,不回退到本机。打开“终端”工具窗口:经会话的 remote.runTerminal 在主机文件夹运行主机账户的登录 shell(不带参数,不读本机 Shell 设置,没有本机 Shell 菜单),标签名为连接名,之后的标签为“连接名 (2)”等;输入按顺序、每块不超过 32 KiB 写入,主机说忙时稍后重试,窗口尺寸随输入发送;输出超过 8 MiB 未显示时丢弃最旧的部分并记一次失败。程序退出显示退出码,被信号结束显示 128+信号,关闭标签不算失败。连接断开时终端显示会话已结束,工作区按退避重连;未连接时按回车说明工作区未连接,重连后按回车在新会话上运行。终端起不来时显示 Core 给出的原因(可能含主机路径),日志只记命令名和错误码。拖到终端的文件粘贴为主机路径并按 POSIX shell 加引号,本机工作区外的文件不粘贴并提示原因;粘贴图片不可用(图片会存到本机)。每个会话连接后,经 remote.runWatch 在主机上递归监听整个文件夹,跳过已启用插件隐藏的文件夹名(按原样比较大小写),插件改变隐藏名称时重新开始监听;在主机上新建、修改、删除文件后,项目树重新列出受影响的目录(Core 的 workspace.filterChanges 按可见性规则过滤,不需要会话),打开的文档与主机比对:没有编辑的重新载入,有编辑的显示外部修改冲突;文件夹外和被隐藏文件夹里的变化不触发列表。监听开始时、主机丢失变化(overflow)时、一次超过 4096 个变化时,重新列出树中展开的目录并比对所有文档,日志每次监听各记一次;主机监听数用尽时其余部分继续监听,提示一次“项目文件可能无法自动更新”。监听中文件夹被删除或移走时立即重新监听;主机找不到文件夹时项目树显示根目录不可用,监听等树重新列出文件夹后再开始,主机与树结论不一致时也只等待、不反复重试。其他监听失败只记命令名和错误码、提示一次,等下一个会话再开始;监听发现连接断开时与心跳一样结束会话并重连。Find in Files 的搜索、计数和替换预览带远程绑定发送,Core 从主机文件夹建立索引并读取主机上的当前内容,结果路径相对主机文件夹;点结果在远程编辑器打开主机文件并定位到匹配处,本机占位目录始终为空。主机监听报告的变化路径在下一次查询前增量更新索引,不重建;监听开始和主机丢失变化时重建一次。包含生成文件的查询每次都重建索引(主机监听跳过插件隐藏的文件夹);主机监听数用尽后、会话断开到下一个会话的监听开始之间,每次查询都重建,只由监听提示一次“项目文件可能无法自动更新”,搜索不再另外提示。查询显示期间主机上的变化让结果重新查询。Search Everywhere 所有页签都可用,文件名和文本来自主机,打开弹窗时重新读取生成文件的名称;远程工作区不启动语言服务器,符号只有 Core 在主机文件中找到的。Replace All 在编辑器中替换打开的文档;未打开的文件经会话读取主机内容,由 Core 替换后,只在主机文件仍是读取时的内容时写回,期间被改过的报告冲突,已被删除的说明主机上找不到文件,其余文件照常替换,都不写本机占位目录。在文件夹选择中打开从未决定过的文件夹:先询问是否信任(显示连接名和主机文件夹,Core 给出上级文件夹时可勾选信任其下的所有文件夹),“信任并打开”把决定按连接名记入 Core 的远程信任记录后以受信任方式打开,“以安全模式打开”只读打开,“返回”回到文件夹选择;之前决定过的文件夹直接按记录打开。安全模式下 Git、提交和日志窗口与本机项目一样说明需要信任,编辑器上方的提示里可以信任文件夹,信任后不重开窗口就在主机上启动 Git。受信任的工作区经会话在主机上运行 Git:状态、暂存、提交、差异(含编辑器行号旁的变更标记)、日志与分支、逐行追溯(读取主机上的文件内容)、搁置与储藏都读写主机仓库,本机占位目录始终没有 .git;“排除到本地”写入主机仓库的 info/exclude(缺少 info 文件夹时在主机上创建,读写期间文件被别人改过时这次排除失败、不覆盖)。同一会话经 remote.runWatch 递归监听主机仓库的 git 目录(公共目录在别处时一并监听),主机上 git checkout、commit 等改动元数据后按路径分类并重新读取状态;监听开始、丢失变化或主机监听数用尽时重新读取一次完整状态,新会话重新开始监听。主机文件夹位于上级目录开始的仓库内时,Git 和提交窗口说明要打开仓库顶层文件夹,不显示变更也不记为失败。工作树列表、锁定、解锁、删除在主机上执行,复制路径复制主机路径;打开、在新窗口打开、在文件浏览器中显示和新建工作树被拒绝并提示。受信任的远程工作区里运行、调试、当前文件运行、测试、构建任务和插件语言服务器都不在本机启动,都记为拒绝并提示,运行、测试和构建工具窗口说明暂不可用。状态栏前端显示连接名和心跳往返时间;连续两次心跳无响应显示“无响应”,第三次结束会话并按 1、2、4、8、16 秒退避重连,共六次失败后显示“已断开”和原因,菜单里可“重新连接”;连接被关闭时立即重连。菜单里“断开并关闭”关闭工作区并结束会话,退出 Lithe 时关闭所有远程会话。最近项目不记录远程工作区。日志只有 remote.connect、remote.workspace.open/reconnect/disconnect 等动作和失败的操作名,不含主机、用户名、主机路径或主目录。运行 remote_workspace_test.go 的 5 个测试、remote_git_test.go 的 6 个测试、remoteplaceholder 的 TestHostAndLocalPathsMapBothWays、remote_documents_test.go 的 2 个测试、remote_terminal_test.go 的 9 个测试、remote_watch_test.go 的 5 个测试、remote_search_test.go 的 4 个测试、internal/core 的 TestRemoteTerminal*、TestRemoteWatch* 与 TestRemoteWorkspaceFiltersChangesWithoutTheHost、termview 的 TestOpenStartsTheProgramElsewhere,以及 TestVisualRemoteWorkspace 无头截图;在 Windows 运行 TestCoreRefusesUnadaptedCommandsAndAClosedSessionDetachesTheBinding,验证 Linux 主机路径能通过绑定校验。真实 SSH 主机上的整机验收(包括终端里 vim、top 等全屏程序与窗口缩放,主机上 git checkout 等大批量修改后的监听,以及大仓库上的搜索)仍待完成。远程 Git 的 AskPass 转交(推送、拉取时的凭据询问)、从上级目录开始的仓库、打开或新建远程工作树尚未支持;端口转发见 remote-development-workspace。", + "verification": "在“远程开发”窗口选中已保存的 Linux SSH 连接点“连接”:SSH 询问出现在窗口中,连接后窗口改为主机的文件夹选择,从主目录开始列出子文件夹(跳过名称不是 UTF-8 的条目并说明数量),可输入 ~ 或 / 开头的路径跳转,不存在的路径说明原因且不能打开;“返回”断开这次会话回到连接表单。选中文件夹点“打开”:新标签页打开远程工作区,窗口标题为“文件夹 [SSH: 连接名]”,项目树经 Core 列出主机目录(本机占位目录始终为空),右键只有复制主机路径和刷新;以安全模式打开的文件夹,编辑器上方说明可以浏览、编辑、保存和搜索主机文件,信任文件夹后才能用 Git;受信任的文件夹说明文件、终端和 Git 都在主机上,运行、调试和语言服务器暂不可用;空白编辑区提示 Search Everywhere 和 Find in Files。在项目树双击文件:编辑器经会话读取主机文件(不超过 16 MiB),保存时带上打开时的大小和修改时间写回主机,新建的文件只在主机上不存在时创建;主机上的文件期间被别人改过时保存被拒绝并显示外部修改冲突,“加载磁盘版本”载入主机内容,本机占位目录始终为空。超过 8 MiB 的保存说明主机单次保存上限,编辑内容保留;主机上缺失、无权限、不是普通文件、超时和连接断开分别说明原因,连接断开后自动重连并把打开的文档和主机重新比对。图片、PDF 等查看器、文件夹外的文件、本地历史和插件终端都被拒绝并提示,不回退到本机。打开“终端”工具窗口:经会话的 remote.runTerminal 在主机文件夹运行主机账户的登录 shell(不带参数,不读本机 Shell 设置,没有本机 Shell 菜单),标签名为连接名,之后的标签为“连接名 (2)”等;输入按顺序、每块不超过 32 KiB 写入,主机说忙时稍后重试,窗口尺寸随输入发送;输出超过 8 MiB 未显示时丢弃最旧的部分并记一次失败。程序退出显示退出码,被信号结束显示 128+信号,关闭标签不算失败。连接断开时终端显示会话已结束,工作区按退避重连;未连接时按回车说明工作区未连接,重连后按回车在新会话上运行。终端起不来时显示 Core 给出的原因(可能含主机路径),日志只记命令名和错误码。拖到终端的文件粘贴为主机路径并按 POSIX shell 加引号,本机工作区外的文件不粘贴并提示原因;粘贴图片不可用(图片会存到本机)。每个会话连接后,经 remote.runWatch 在主机上递归监听整个文件夹,跳过已启用插件隐藏的文件夹名(按原样比较大小写),插件改变隐藏名称时重新开始监听;在主机上新建、修改、删除文件后,项目树重新列出受影响的目录(Core 的 workspace.filterChanges 按可见性规则过滤,不需要会话),打开的文档与主机比对:没有编辑的重新载入,有编辑的显示外部修改冲突;文件夹外和被隐藏文件夹里的变化不触发列表。监听开始时、主机丢失变化(overflow)时、一次超过 4096 个变化时,重新列出树中展开的目录并比对所有文档,日志每次监听各记一次;主机监听数用尽时其余部分继续监听,提示一次“项目文件可能无法自动更新”。监听中文件夹被删除或移走时立即重新监听;主机找不到文件夹时项目树显示根目录不可用,监听等树重新列出文件夹后再开始,主机与树结论不一致时也只等待、不反复重试。其他监听失败只记命令名和错误码、提示一次,等下一个会话再开始;监听发现连接断开时与心跳一样结束会话并重连。Find in Files 的搜索、计数和替换预览带远程绑定发送,Core 从主机文件夹建立索引并读取主机上的当前内容,结果路径相对主机文件夹;点结果在远程编辑器打开主机文件并定位到匹配处,本机占位目录始终为空。主机监听报告的变化路径在下一次查询前增量更新索引,不重建;监听开始和主机丢失变化时重建一次。包含生成文件的查询每次都重建索引(主机监听跳过插件隐藏的文件夹);主机监听数用尽后、会话断开到下一个会话的监听开始之间,每次查询都重建,只由监听提示一次“项目文件可能无法自动更新”,搜索不再另外提示。查询显示期间主机上的变化让结果重新查询。Search Everywhere 所有页签都可用,文件名和文本来自主机,打开弹窗时重新读取生成文件的名称;远程工作区不启动语言服务器,符号只有 Core 在主机文件中找到的。Replace All 在编辑器中替换打开的文档;未打开的文件经会话读取主机内容,由 Core 替换后,只在主机文件仍是读取时的内容时写回,期间被改过的报告冲突,已被删除的说明主机上找不到文件,其余文件照常替换,都不写本机占位目录。在文件夹选择中打开从未决定过的文件夹:先询问是否信任(显示连接名和主机文件夹,Core 给出上级文件夹时可勾选信任其下的所有文件夹),“信任并打开”把决定按连接名记入 Core 的远程信任记录后以受信任方式打开,“以安全模式打开”只读打开,“返回”回到文件夹选择;之前决定过的文件夹直接按记录打开。安全模式下 Git、提交和日志窗口与本机项目一样说明需要信任,编辑器上方的提示里可以信任文件夹,信任后不重开窗口就在主机上启动 Git。受信任的工作区经会话在主机上运行 Git:状态、暂存、提交、差异(含编辑器行号旁的变更标记)、日志与分支、逐行追溯(读取主机上的文件内容)、搁置与储藏都读写主机仓库,本机占位目录始终没有 .git;“排除到本地”写入主机仓库的 info/exclude(缺少 info 文件夹时在主机上创建,读写期间文件被别人改过时这次排除失败、不覆盖)。同一会话经 remote.runWatch 递归监听主机仓库的 git 目录(公共目录在别处时一并监听),主机上 git checkout、commit 等改动元数据后按路径分类并重新读取状态;监听开始、丢失变化或主机监听数用尽时重新读取一次完整状态,新会话重新开始监听。主机文件夹位于上级目录开始的仓库内时,Git 和提交窗口说明要打开仓库顶层文件夹,不显示变更也不记为失败。工作树列表、锁定、解锁、删除在主机上执行,复制路径复制主机路径;打开、在新窗口打开、在文件浏览器中显示和新建工作树被拒绝并提示。受信任的远程工作区里运行、调试、当前文件运行、测试、构建任务和插件语言服务器都不在本机启动,都记为拒绝并提示,运行、测试和构建工具窗口说明暂不可用。状态栏前端显示连接名和心跳往返时间;连续两次心跳无响应显示“无响应”,第三次结束会话并按 1、2、4、8、16 秒退避重连,共六次失败后显示“已断开”和原因,菜单里可“重新连接”;连接被关闭时立即重连。菜单里“断开并关闭”关闭工作区并结束会话,退出 Lithe 时关闭所有远程会话。最近项目不记录远程工作区。日志只有 remote.connect、remote.workspace.open/reconnect/disconnect 等动作和失败的操作名,不含主机、用户名、主机路径或主目录。运行 remote_workspace_test.go 的 5 个测试、remote_git_test.go 的 6 个测试、remoteplaceholder 的 TestHostAndLocalPathsMapBothWays、remote_documents_test.go 的 2 个测试、remote_terminal_test.go 的 9 个测试、remote_watch_test.go 的 5 个测试、remote_search_test.go 的 4 个测试、internal/core 的 TestRemoteTerminal*、TestRemoteWatch* 与 TestRemoteWorkspaceFiltersChangesWithoutTheHost、termview 的 TestOpenStartsTheProgramElsewhere,以及 TestVisualRemoteWorkspace 无头截图;在 Windows 运行 TestCoreRefusesUnadaptedCommandsAndAClosedSessionDetachesTheBinding,验证 Linux 主机路径能通过绑定校验。真实 SSH 主机上的整机验收(包括终端里 vim、top 等全屏程序与窗口缩放,主机上 git checkout 等大批量修改后的监听,以及大仓库上的搜索)仍待完成。远程工作区左侧多出“端口”工具窗口(本机工作区没有,关闭工作区后消失):窗口打开时每 3 秒经 ports.listening 读取主机上正在监听的端口和会话的转发,窗口关闭或未显示时停止读取;同一端口在 0.0.0.0 与 :: 上监听只显示一行;远端端口带上主机监听的 IP 地址,多个地址时显示第一个和其余数量,悬停提示列出全部,地址或网址过长被截断时悬停提示给出全文;列出远端端口、本机地址、进程(名称与 PID,读不到时为“未知”)、来源(监听发现、手动添加)和状态。默认不自动转发任何端口,打开窗口和发现新端口都不转发;行尾“转发”把端口转发到主机上对应族的回环地址,本机在 127.0.0.1 的同号端口监听,该端口被本机其他程序占用时改用空闲端口,本机地址用警告色显示并在提示里说明原端口。右键“转发到指定本机端口…”和已转发行的“更改本机端口…”打开对话框输入 1–65535 的本机端口,非法输入就地说明且不转发;改到另一个端口时先停止原转发再在新端口转发,选择在工作区打开期间保留,停止后再转发仍用该端口。顶部输入端口、主机:端口或网址(http、https、ws、wss,省略端口时按协议默认端口)可手动添加并转发,由 Core 的 remote.parseForwardAddress 解析;格式不对就地说明,网址里带用户名或密码时拒绝并说明,输入框保留原文、日志不记输入内容;同一目标再次添加不重复。网址行按输入的样子显示,转发到主机上提供该端口的回环地址;在浏览器打开和复制本机地址把主机部分换成本机地址并保留路径和查询,ws/wss 网址不提供在浏览器打开;浏览器打不开时提示网址,日志只记失败、不记网址。主机回环地址以外的目标先询问(S28),确认后才带 AllowNonLoopback 转发,取消记为拒绝。已转发行可在浏览器打开、复制本机地址、停止;手动添加且已停止、主机上也没有在监听的行可移除;窗口标题栏可全部停止,标题栏的 ⓘ 说明转发对本机其他程序可见(S30);会话转发数达到 Core 上限时说明上限;状态栏显示已转发数量,点击打开端口窗口;会话结束时转发随之结束,重连后不自动恢复。日志只记 remote.ports.forward/localPort/move/stop/status 等动作和失败操作名,不含主机、地址或进程名。运行 remote_ports_test.go 的 12 个测试、internal/core 的 TestRemoteSessionCommandsOfAnUnknownSession 与 TestRemoteParseForwardAddressReadsPortsAndURLs,以及 TestVisualRemotePorts 无头截图。手动添加的端口和本机端口选择只在工作区打开期间保留,关闭后不保存(需 Core 存储,后续阶段);主机侧监听的转发规则(主机端口转到另一台服务器)和反向转发只完成设计,尚未实现。远程 Git 的 AskPass 转交(推送、拉取时的凭据询问)、从上级目录开始的仓库、打开或新建远程工作树尚未支持。", "legacy": { "revision": "5a54c41aa37a4e6e6b68918a4b05765b9dd07a36", "macos": { @@ -109,5 +118,5 @@ "verificationStatus": "pending" } }, - "notes": "Viva:连接和会话由 Core 的 remote.connect/remote.disconnect/remote.closeAll 管理,远端服务按嵌入清单上传;文件夹选择用 remote.readDir。打开的工作区以用户缓存目录下的空占位目录作为本机根,每个请求带上远程绑定(会话、占位根、主机根),Core 只对有远程适配的命令放行,其余以 not_supported 拒绝,所以没有远程实现的功能在桌面端直接拒绝而不读本机占位目录。编辑器的读、写和比对改走 remote.stat、remote.readFile、remote.writeFile(带预期版本,主机按大小和修改时间拒绝过期写入);解码、恢复、语言识别等纯计算命令不带远程绑定发送。日志只记命令名和错误码,不记 Core 返回的消息(可能含主机路径)。macOS 由单元测试与无头截图覆盖;Core 按 POSIX 规则校验 Linux 主机路径,按客户端规则处理本机占位根(#2264)。终端经 remote.runTerminal 运行,输入与尺寸经 remote.hostRequest 的 terminal.write/terminal.resize 发送;关闭标签取消这次请求,Core 随即向主机发 terminal.close;一个连接断开的终端让工作区按同一会话丢失处理(与心跳一致),其他失败只结束该终端。文件夹监听经 remote.runWatch 在请求的 goroutine 上运行整个会话期间,不计入窗口的后台任务;事件在锁内合并后只投递一次到窗口线程,停止监听时作废已排队的变化。Find in Files、Search Everywhere 和 Replace All 的 workspace.search、searchIndex.update/invalidate、searchEverywhere、replacePreview 带远程绑定发送,searchPresentation、replaceText 等纯计算命令不带绑定;Core 以“会话身份 + 主机路径”为键缓存索引,主机监听的变化经 workspace.filterChanges 过滤后更新它。会话结束后 Core 不释放该会话的索引,每次重连或重新打开多留一份(#2277)。 远程信任:Core 的 remote.workspaceTrust 按“会话身份 + 主机文件夹”读出记录,remote.editWorkspaceTrust 写入决定(含连接名),桌面端只把 Core 给出的文档存到偏好目录;projectCodeAllowed 且状态为 trusted 才算受信任。受信任后 git.* 请求带远程绑定发送,Core 在主机上运行 Git,返回的路径是占位路径(remoteplaceholder.LocalPath 把主机路径换成占位路径,文件夹外的主机路径映射到占位目录旁的 .lithe-remote-host 下,不会落到本机真实路径)。git 目录的监听与文件夹监听同样跑在请求自己的 goroutine 上,会话丢失或失去信任时取消。" + "notes": "Viva:连接和会话由 Core 的 remote.connect/remote.disconnect/remote.closeAll 管理,远端服务按嵌入清单上传;文件夹选择用 remote.readDir。打开的工作区以用户缓存目录下的空占位目录作为本机根,每个请求带上远程绑定(会话、占位根、主机根),Core 只对有远程适配的命令放行,其余以 not_supported 拒绝,所以没有远程实现的功能在桌面端直接拒绝而不读本机占位目录。编辑器的读、写和比对改走 remote.stat、remote.readFile、remote.writeFile(带预期版本,主机按大小和修改时间拒绝过期写入);解码、恢复、语言识别等纯计算命令不带远程绑定发送。日志只记命令名和错误码,不记 Core 返回的消息(可能含主机路径)。macOS 由单元测试与无头截图覆盖;Core 按 POSIX 规则校验 Linux 主机路径,按客户端规则处理本机占位根(#2264)。终端经 remote.runTerminal 运行,输入与尺寸经 remote.hostRequest 的 terminal.write/terminal.resize 发送;关闭标签取消这次请求,Core 随即向主机发 terminal.close;一个连接断开的终端让工作区按同一会话丢失处理(与心跳一致),其他失败只结束该终端。文件夹监听经 remote.runWatch 在请求的 goroutine 上运行整个会话期间,不计入窗口的后台任务;事件在锁内合并后只投递一次到窗口线程,停止监听时作废已排队的变化。Find in Files、Search Everywhere 和 Replace All 的 workspace.search、searchIndex.update/invalidate、searchEverywhere、replacePreview 带远程绑定发送,searchPresentation、replaceText 等纯计算命令不带绑定;Core 以“会话身份 + 主机路径”为键缓存索引,主机监听的变化经 workspace.filterChanges 过滤后更新它。会话结束后 Core 不释放该会话的索引,每次重连或重新打开多留一份(#2277)。 远程信任:Core 的 remote.workspaceTrust 按“会话身份 + 主机文件夹”读出记录,remote.editWorkspaceTrust 写入决定(含连接名),桌面端只把 Core 给出的文档存到偏好目录;projectCodeAllowed 且状态为 trusted 才算受信任。受信任后 git.* 请求带远程绑定发送,Core 在主机上运行 Git,返回的路径是占位路径(remoteplaceholder.LocalPath 把主机路径换成占位路径,文件夹外的主机路径映射到占位目录旁的 .lithe-remote-host 下,不会落到本机真实路径)。git 目录的监听与文件夹监听同样跑在请求自己的 goroutine 上,会话丢失或失去信任时取消。 端口:remote.startForward/stopForward/forwards 与 ports.listening 都带会话发送;Core 只在本机 127.0.0.1 监听,请求的本机端口被占用时选空闲端口并返回 localPortChanged 与 requestedLocalPort;同一目标再次转发返回已有转发(created=false),所以更改本机端口是先停止再转发。顶部输入由 Core 的 remote.parseForwardAddress 解析为目标端口、主机、协议和路径,不连接主机;桌面端把网址的主机换成主机上提供该端口的回环地址再转发。非回环目标需 allowNonLoopback(S28),超过上限返回 forward_limit_reached 并带 maximum。读取在窗口的后台任务里进行,只在窗口打开且被绘制过时排下一次,不做空闲轮询。" }