diff --git a/.agents/notes/implemented/feature/2026-11-22-remote-ports-remembered-records.md b/.agents/notes/implemented/feature/2026-11-22-remote-ports-remembered-records.md new file mode 100644 index 000000000..9e1abfec8 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-11-22-remote-ports-remembered-records.md @@ -0,0 +1,107 @@ +# Agent 笔记:远程端口窗口记住标签、转发和规则,重连或重新打开后恢复转发 + +状态:已实现 + +## 先说结论 + +远程工作区的“端口”窗口会把以下内容记在本机:用户手动添加的端口、选过的本机端口、行和规则的标签、没停的本机转发,以及在主机上启动过的转发规则。 + +- 本机转发(T1、T2):每次接上会话(打开工作区、断线重连)时,由 Core 的 `remote.restoreForwards` 按记录重新转发,沿用当初的本机端口和对非回环目标的确认(S28)。 +- 转发规则(T3、T4):只记住,从不自动启动。行尾“启动”把规则填进“添加转发规则”,由用户再提交,所有询问都重新问一遍;“忘记”删除记录。 +- 监听主机全部网卡从不记住(S27),再启动时按回环地址填入。 + +记录文件是本机偏好目录下的 `remote/ports.json`。路径和大小上限由 Core 给出,内容由 Core 校验,并按连接目标和主机上工作区的真实路径分组。所以另一台主机、另一个账户、容器或文件夹都看不到这份记录。 + +## 问题 + +Issue #2231 §8 要求端口窗口像 VS Code 的“端口”视图那样:用户转发过的端口在重连后接着用,标签不丢。 + +#46a 之前的端口窗口只在工作区打开期间记住这些内容。断线重连后所有转发都消失,用户要一条条重新转发。手动添加的网址和本机端口选择也要重新输入。 + +同时有两条安全约束: +- 不能因为“记住”而在用户不知情时让主机监听端口。规则在主机上监听,记住后自动启动就等于绕过 S27、S29 的逐次确认。 +- 记录里有主机地址、端口和用户输入的标签。它们只能留在本机,不能写进日志、主机或应用包。 + +## 决策 + +### 存储归 Core,文件读写归桌面端 + +- Core #163 提供 `remote.portRecords`(读取并告诉桌面端存储位置)、`remote.editPortRecords`(对文本做一次编辑,返回新文本)、`remote.restoreForwards`(按文本重新转发)。Core 负责校验、分组和规范化:回环地址的各种写法记成同一行,网址的查询和片段不记(可能带令牌),空记录删除,标签最多 64 个字符且不含控制字符。 +- 桌面端的 `desktop/internal/remoteconn/ports.go` 只做文件读写:先问 Core 存储位置,用 `configfile` 读出字节,交给 Core,再把 Core 返回的新文本整体原子替换回去。替换前确认文件还是读到时的字节,不是就返回 `ErrConflict`,由上层重读后重试,最多 3 次。 +- 文件只在第一次修改时创建,读取不创建任何东西。它和远程偏好一样不写主机、工作区、应用包或安装目录,所以不影响代码签名和 Sparkle 增量更新,也不跨工作树复制。 + +### 窗口只写变化的部分 + +- 窗口在内存里保留当前状态(标签、本机端口、没停的转发、规则),`ports.written` 是 Core 上次报告的记录。 +- `recordEdits()` 比较两者,每个不同的行或规则生成一条编辑。所以停止、移除、改标签、规则启停都只写变化的部分,不会覆盖另一个窗口同时写入的其他行。 +- 同一时间只跑一次读写(`recordsBusy`)。结束时只有期间又改过(`recordsRevision` 变了)或接上了新会话才再同步一次。这样 Core 规范化后与窗口不同的内容不会引起循环写入。 + +### 每次接上会话都恢复 + +- 打开工作区和断线重连都会设置 `recordsAttach`。下一次同步先写出断线期间的修改,再读记录,最后调 `remote.restoreForwards`。 +- 刚打开的工作区把读到的记录并入窗口(`merge`,只填窗口还没有的);重连时窗口的内存状态优先。 +- 某条转发没能重新开始时,这一行标为失败,显示 Core 的原因,并忘掉“没停”这个状态。窗口顶部说明有几条没能恢复。其余转发照常恢复。 +- 会话在恢复期间断开就按断线处理,下一个会话接上时再恢复一次。 + +### 损坏的文件从不覆盖 + +Core 解不开的文件(`CodeParseFailed`、超出大小、编码不对)一律当作 `ErrDamaged`: +- 窗口说明文件无法读取; +- 之后的修改只留在内存里,`ports.written` 保持为空,所以不会生成任何编辑; +- 文件的字节保持原样,用户可以手动修好或删除。 + +没有用户偏好目录(`ErrUnavailable`)时,记录只留在内存里,和远程偏好一样不记日志。 + +### 日志 + +日志只记以下内容: +- 动作 `remote.ports.label`、`remote.ports.ruleStart`、`remote.ports.ruleForget`; +- 失败的操作名 `remote_port_records`、`remote_port_restore`,以及 Core 错误码; +- 标签对话框拒绝时的 `remote_port_label` 和 `invalid_label`。 + +日志不记主机、标签、端口、网址或转发地址(S30)。测试用 `loggedAny` 检查这几项都不在日志里。 + +## 考虑过的备选方案 + +- **规则也在重连后自动启动。** 被否:规则让主机监听端口,S27、S29 要求每次都确认,自动启动等于跳过确认。VS Code 也只自动恢复本机转发。 +- **把记录写进 `remote/preferences.json`。** 被否:偏好是用户在设置页改的少量配置,端口记录按工作区分组、改动频繁,混在一起会让两边的写入互相冲突,也让偏好文件变大。 +- **记录存在主机上(工作区或主机的配置目录)。** 被否:多个用户可能共用同一个主机账户或工作区,标签和本机端口是这台电脑的用户自己的选择;而且容器重建后主机侧的文件会消失。 +- **每次修改都把整份记录写一遍。** 被否:两个窗口打开同一个工作区时,后写的会覆盖先写的其他行。按差异逐条编辑,再加读到字节的比较,冲突时只重做自己的那几条。 +- **损坏时用空记录覆盖重建。** 被否:用户手改坏的文件里可能还有其他工作区的记录,覆盖等于静默删除。 + +## 后果 + +- 收益: + - 断线重连和重新打开后,用户的转发自动回来,标签和规则也还在; + - 规则仍然每次都确认,安全约束不变; + - Windows 和 macOS 共用同一份 Go 代码,记录格式和校验由 Core 统一。 +- 代价: + - 每次接上会话多一次读文件和 `remote.restoreForwards` 往返; + - 没能恢复的转发会被忘掉,用户要重新转发一次; + - 记录按工作区的真实路径分组,主机上移动或重命名文件夹后旧记录不再生效(也不会被清理)。 +- 真实 SSH 主机、Windows 和 WSL 上的整机验收在后续阶段完成。 + +## 验证 + +- `desktop/internal/workbench/remote_port_records_test.go`: + - 标签、没停的转发和规则写进文件,关闭再打开后标签还在、转发自动恢复、规则列为未运行;“启动”只填对话框不直接启动;含制表符的标签在对话框里被拒;空标签删除;日志不含主机、标签和端口; + - 重连后没能恢复的转发标为失败、显示 Core 的原因并被忘掉; + - 损坏的文件从不覆盖,修改只留在内存。 +- `desktop/internal/workbench/remote_ports_test.go` 的 `TestRemotePortsStartTheForwardsLeftRunningAgainAfterAReconnect`,以及 `remote_port_rules_test.go` 中停止后忘记、重连后不自动启动规则的断言。 +- `desktop/internal/remoteconn/ports_test.go`:读取不创建文件,只写记录文件,没变化的编辑不写,读到后被改过的文件返回冲突,损坏、断线和没有偏好目录各自报告。 +- `desktop/internal/core/remote_session_test.go`:三个新命令对未知会话返回 `connection_closed`。 +- `remote_ports_visual_test.go` 生成 `docs/assets/remote-ports/` 的编辑标签、标签列和重新打开后的截图。 + +```bash +scripts/desktop/desktop-go.sh test -count=1 -run 'TestRemote|TestPortRecords|TestDamagedPortRecords' ./internal/workbench ./internal/remoteconn ./internal/core +``` + +## 适用范围 + +本 Note 覆盖以下代码: +- `desktop/internal/core/remote_port_records.go`; +- `desktop/internal/remoteconn/ports.go`; +- `desktop/internal/workbench/remote_port_records.go`; +- `desktop/internal/workbench/remote_ports.go`、`desktop/internal/workbench/remote_ports_view.go`、`desktop/internal/workbench/remote_port_rules.go`、`desktop/internal/workbench/remote_port_rules_view.go` 中标签列、标签对话框、记住的规则和会话接上时恢复的部分。 + +以后端口窗口新增需要跨会话保留的内容时,先在 Core 的端口记录里加字段,再让桌面端通过 `recordEdits()` 写差异。不要在桌面端另存一份文件。 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 af8dad06e..535f51844 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 @@ -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` 列出远端正在监听的端口,桌面端的“端口”工具窗口用它列出主机上的端口,默认不自动转发。转发目标的输入(端口、`主机:端口`、网址)由 Core 的 `remote.parseForwardAddress` 解析。转发按“在哪一侧监听、由哪一侧连接哪个目标”建模为四类规则(#2231 §8 D10):T1 本机到主机回环、T2 本机到主机能访问的其他服务器(`remote.startForward`);T3 主机端口到其他服务器(`remote.startHostForward`)、T4 反向转发(`remote.startReverseForward`)。T3 在主机上完成转发,数据不绕回本机,默认只监听主机回环地址,监听全部网卡要逐次确认;T4 默认关闭,只有偏好里允许反向转发时 Core 才接受,主机只在回环地址监听、本机只连接回环地址。四类共用会话转发上限;T3、T4 随会话结束,重连后不自动恢复。 +- **端口**:隧道把远端的 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 本机到主机能访问的其他服务器(`remote.startForward`);T3 主机端口到其他服务器(`remote.startHostForward`)、T4 反向转发(`remote.startReverseForward`)。T3 在主机上完成转发,数据不绕回本机,默认只监听主机回环地址,监听全部网卡要逐次确认;T4 默认关闭,只有偏好里允许反向转发时 Core 才接受,主机只在回环地址监听、本机只连接回环地址。四类共用会话转发上限;T3、T4 随会话结束,重连或重新打开后只列出、不自动启动。用户没停的 T1、T2 转发、标签和启动过的规则按工作区记在本机,每次接上会话由 `remote.restoreForwards` 重新转发(见 [远程端口窗口记住标签、转发和规则](../../implemented/feature/2026-11-22-remote-ports-remembered-records.md))。 ### 后续阶段 diff --git a/desktop/internal/core/remote_port_records.go b/desktop/internal/core/remote_port_records.go new file mode 100644 index 000000000..d4e57f3df --- /dev/null +++ b/desktop/internal/core/remote_port_records.go @@ -0,0 +1,179 @@ +package core + +import "context" + +// What the Ports window remembers of a remote workspace after it closes or its connection drops +// (remote.portRecords, remote.editPortRecords, remote.restoreForwards): the ports the user added, +// the labels and local ports chosen for them, the local forwards left running, and the forwarding +// rules the user started on the host. The document is machine-local; the desktop reads and +// publishes it like the remote preferences, and Core validates it and keys it by the connection's +// target and the workspace's real path on the host, so another host, account, container or folder +// never sees it. + +// RemotePortRecordAdded is the address the user added a row with, as remote.parseForwardAddress +// read it. +type RemotePortRecordAdded struct { + // Host is the host read: an IP address, an IPv6 one without brackets, or a name in lower case; + // localhost for a port alone. + Host string `json:"host"` + // Scheme is the URL's scheme in lower case, "" for an address that is not a URL. + Scheme string `json:"scheme,omitempty"` + // Path is the URL's path without its query and fragment, "" when nothing but / remains. + Path string `json:"path,omitempty"` +} + +// RemotePortRecord is what one row of the Ports window remembers. A record with nothing but its +// key is no record: Core removes it. +type RemotePortRecord struct { + // Host is the row's address, "" for the host's own loopback address (localhost, 127.0.0.1, + // ::1 and the every-interface addresses); Port is the TCP port. + Host string `json:"host,omitempty"` + Port uint16 `json:"port"` + // Added is the address the user added the row with, nil for a listening port the user did not + // add. + Added *RemotePortRecordAdded `json:"added,omitempty"` + // Label is the name the user gave the row, at most 64 characters. + Label string `json:"label,omitempty"` + // LocalPort is the local port the user chose, 0 to forward on the row's own number. + LocalPort uint16 `json:"localPort,omitempty"` + // ForwardTarget is the target host of the local forward the user started for the row and did + // not stop, "" for none; it starts again after a reconnect. + ForwardTarget string `json:"forwardTarget,omitempty"` + // ConfirmedTarget records that the user confirmed that forward although its target is outside + // the host's loopback interface (S28). Core keeps it only with a ForwardTarget of such a target. + ConfirmedTarget bool `json:"confirmedTarget,omitempty"` +} + +// RemotePortRule is a forwarding rule the user started on the host. Kind is RemoteForwardHost or +// RemoteForwardReverse; the fields of the other kind are zero. Two rules are the same rule when +// they differ only in their labels. A rule never starts again without the user, and never listens +// on every interface of the host: that is asked every time. +type RemotePortRule struct { + Kind RemoteForwardKind `json:"kind"` + // ListenPort is the host port, 0 to let the host choose one at each start. + ListenPort uint16 `json:"listenPort,omitempty"` + // TargetHost and TargetPort are a host rule's server, as remote.forwards lists the target. + TargetHost string `json:"targetHost,omitempty"` + TargetPort uint16 `json:"targetPort,omitempty"` + // LocalPort is the port on this computer's loopback interface a reverse rule reaches. + LocalPort uint16 `json:"localPort,omitempty"` + // Label is the name the user gave the rule, at most 64 characters. + Label string `json:"label,omitempty"` +} + +// RemotePortRecords are what the Ports window remembers of one workspace: rows by port and then by +// host, the loopback row first, and rules in the order the user added them. +type RemotePortRecords struct { + Ports []RemotePortRecord `json:"ports"` + Rules []RemotePortRule `json:"rules"` +} + +// RemotePortRecordsState is what remote.portRecords reports. +type RemotePortRecordsState struct { + Records RemotePortRecords `json:"records"` + // Workspace is the workspace's real path on the host, which keys the records. + Workspace string `json:"workspace"` + // Storage is where the document lives below the application's preference root. + Storage RemotePreferenceStorage `json:"storage"` +} + +// RemotePortRecordKey names one row of the Ports window: Host as RemotePortRecord keys it, in any +// spelling of the host's loopback address, and the port. +type RemotePortRecordKey struct { + Host string `json:"host,omitempty"` + Port uint16 `json:"port"` +} + +// RemotePortRecordEdit is one change: exactly one field is set. Port replaces what its row +// remembers, and a row with nothing left is removed; RemovePort forgets a row; Rule records a rule +// or renames the same rule; RemoveRule forgets the same rule, whatever its label. +type RemotePortRecordEdit struct { + Port *RemotePortRecord `json:"port,omitempty"` + RemovePort *RemotePortRecordKey `json:"removePort,omitempty"` + Rule *RemotePortRule `json:"rule,omitempty"` + RemoveRule *RemotePortRule `json:"removeRule,omitempty"` +} + +// RemoteRestoredForward is one local forward remote.restoreForwards started again, or why it did +// not start: Forward is set when it started, Err when it failed. +type RemoteRestoredForward struct { + // Host and Port are the row, as RemotePortRecord keys it. + Host string + Port uint16 + // Forward is the running forward and Created whether this request started it; Forward is nil + // when the forward failed. + Forward *RemoteForward + Created bool + // Err is why the forward did not start, nil when it started. + Err *Error +} + +// RemotePortRecords reads what the Ports window remembers of the workspace opened as workspace +// through the session sessionID. document is the stored text, nil when there is none; a document +// Core cannot decode fails with CodeParseFailed, an unknown or broken session with +// CodeConnectionClosed and a workspace that no longer exists with CodeWorkspaceNotFound. +func (c *Client) RemotePortRecords(ctx context.Context, document *string, sessionID, workspace string) (RemotePortRecordsState, error) { + var result RemotePortRecordsState + err := c.Execute(ctx, "remote.portRecords", remotePortRecordsRequest{document, sessionID, workspace}, &result) + return result, err +} + +// EditRemotePortRecords applies edit to document for the workspace. changed is false and updated +// nil when the edit changes nothing, so the caller writes nothing; records is the workspace's +// records after the edit. A refused value fails with CodeInvalidRequest whose details name the +// field. +func (c *Client) EditRemotePortRecords(ctx context.Context, document *string, sessionID, workspace string, edit RemotePortRecordEdit) (changed bool, updated *string, records RemotePortRecords, err error) { + var result struct { + Changed bool `json:"changed"` + Document *string `json:"document"` + Records RemotePortRecords `json:"records"` + } + err = c.Execute(ctx, "remote.editPortRecords", struct { + remotePortRecordsRequest + RemotePortRecordEdit + }{remotePortRecordsRequest{document, sessionID, workspace}, edit}, &result) + if err != nil { + return false, nil, RemotePortRecords{}, err + } + return result.Changed, result.Document, result.Records, nil +} + +// RestoreRemoteForwards starts again, in row order, the local forwards document records as left +// running in the workspace, each on its row's local port and with the confirmation it was given. +// One that fails is reported with its error and the others still start; a session that closes +// fails the whole request with CodeConnectionClosed. Rules are never started. +func (c *Client) RestoreRemoteForwards(ctx context.Context, document *string, sessionID, workspace string) ([]RemoteRestoredForward, error) { + var result struct { + Forwards []struct { + Host string `json:"host"` + Port uint16 `json:"port"` + Forward *RemoteForward `json:"forward"` + Created bool `json:"created"` + Error *wireError `json:"error"` + } `json:"forwards"` + } + const command = "remote.restoreForwards" + if err := c.Execute(ctx, command, remotePortRecordsRequest{document, sessionID, workspace}, &result); err != nil { + return nil, err + } + restored := make([]RemoteRestoredForward, 0, len(result.Forwards)) + for _, item := range result.Forwards { + forward := RemoteRestoredForward{Host: item.Host, Port: item.Port, Forward: item.Forward, Created: item.Created} + switch { + case item.Error != nil: + forward.Forward = nil + forward.Err = &Error{Command: command, Code: item.Error.Code, Message: item.Error.Message, Details: item.Error.Details} + case item.Forward == nil: + forward.Err = &Error{Command: command, Code: CodeParseFailed, Message: "restored forward without a forward or an error"} + } + restored = append(restored, forward) + } + return restored, nil +} + +// remotePortRecordsRequest names the stored document and the open workspace it is read for. +type remotePortRecordsRequest struct { + Document *string `json:"document"` + SessionID string `json:"sessionId"` + Workspace string `json:"workspace"` +} diff --git a/desktop/internal/core/remote_session_test.go b/desktop/internal/core/remote_session_test.go index a1409b8b7..95cc4ad33 100644 --- a/desktop/internal/core/remote_session_test.go +++ b/desktop/internal/core/remote_session_test.go @@ -138,6 +138,16 @@ func TestRemoteSessionCommandsOfAnUnknownSession(t *testing.T) { if _, err := client.RemoteListeningPorts(ctx, "no-such-session"); !errors.As(err, &coreErr) || coreErr.Code != CodeConnectionClosed { t.Fatalf("ports.listening = %v, want connection_closed", err) } + if _, err := client.RemotePortRecords(ctx, nil, "no-such-session", "/srv/repo"); !errors.As(err, &coreErr) || coreErr.Code != CodeConnectionClosed { + t.Fatalf("portRecords = %v, want connection_closed", err) + } + label := RemotePortRecordEdit{Port: &RemotePortRecord{Port: 8080, Label: "web"}} + if changed, updated, _, err := client.EditRemotePortRecords(ctx, nil, "no-such-session", "/srv/repo", label); changed || updated != nil || !errors.As(err, &coreErr) || coreErr.Code != CodeConnectionClosed { + t.Fatalf("editPortRecords = %v, %v, %v, want connection_closed", changed, updated != nil, err) + } + if restored, err := client.RestoreRemoteForwards(ctx, nil, "no-such-session", "/srv/repo"); restored != nil || !errors.As(err, &coreErr) || coreErr.Code != CodeConnectionClosed { + t.Fatalf("restoreForwards = %d, %v, want connection_closed", len(restored), err) + } } // A context without its remote workspace sends requests that compute from their payload as diff --git a/desktop/internal/i18n/shared.generated.go b/desktop/internal/i18n/shared.generated.go index a75305fbc..f1c8cee96 100644 --- a/desktop/internal/i18n/shared.generated.go +++ b/desktop/internal/i18n/shared.generated.go @@ -1855,6 +1855,7 @@ var sharedCatalogs = map[string]map[string]string{ "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.columnLabel": "Label", "desktop.remote.ports.columnLocal": "Local Address", "desktop.remote.ports.columnProcess": "Process", "desktop.remote.ports.columnRemote": "Remote Port", @@ -1865,12 +1866,19 @@ var sharedCatalogs = map[string]map[string]string{ "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.disconnected": "Not connected. Forwards end with the connection; the local forwards you left running start again when you reconnect.", + "desktop.remote.ports.editLabel": "Edit Label…", "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.labelApply": "Save", + "desktop.remote.ports.labelBody": "The label is shown in the Label column and kept on this computer for this workspace. Leave it empty to remove it.", + "desktop.remote.ports.labelCancel": "Cancel", + "desktop.remote.ports.labelField": "Label", + "desktop.remote.ports.labelInvalid": "Use at most 64 characters, without line breaks or tabs.", + "desktop.remote.ports.labelTitle": "Edit Label", "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", @@ -1884,10 +1892,13 @@ var sharedCatalogs = map[string]map[string]string{ "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.recordsDamaged": "The saved ports and rules of remote workspaces cannot be read, so they are not restored and changes are not saved. The file in the Lithe settings folder is left as it is.", + "desktop.remote.ports.recordsFailed": "The ports and rules of this workspace could not be remembered: {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.restoreFailed": "{count} forwards could not start again after reconnecting. Their rows show why.", "desktop.remote.ports.ruleAdd": "Add Forwarding Rule…", "desktop.remote.ports.ruleAllInterfaces": "Listen on every interface of the host", "desktop.remote.ports.ruleAllInterfacesNote": "Any computer that can reach the host can connect to this port and reach the target through it. You are asked every time; the choice is never remembered.", @@ -1904,6 +1915,7 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.remote.ports.ruleConfirmReverseTitle": "Forward a Host Port to This Computer?", "desktop.remote.ports.ruleConfirmTarget": "{target} is not the loopback address of {name}. With this rule, every program that can connect to the host port reaches that address through the host. Continue only if you trust it.", "desktop.remote.ports.ruleConnectionsFailed": "{count} ({failed} failed)", + "desktop.remote.ports.ruleForget": "Forget Rule", "desktop.remote.ports.ruleHostNote": "{name} listens on the port below and connects to the target itself; the data does not pass through this computer. By default it listens only on the host's loopback address (127.0.0.1), so only programs on the host can connect.", "desktop.remote.ports.ruleInvalidListen": "Enter a host port from 1 to 65535, or leave it empty.", "desktop.remote.ports.ruleKind": "Direction", @@ -1919,6 +1931,7 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.remote.ports.rulePortInUse": "Port {port} is used by another program on the host. Choose another port or leave it empty.", "desktop.remote.ports.ruleReverseNote": "{name} listens on the port below on its loopback address (127.0.0.1) and brings every connection back to a port on this computer's loopback address. Every user of the host can connect to that port.", "desktop.remote.ports.ruleReverseOff": "Forwarding a host port back to this computer (reverse forwarding) is off by default. You can allow it in Settings › Tools › Remote Workspace.", + "desktop.remote.ports.ruleStart": "Start…", "desktop.remote.ports.ruleSubmit": "Add", "desktop.remote.ports.ruleTarget": "Target", "desktop.remote.ports.ruleTargetPlaceholder": "Port, host:port or URL, as the host reaches it", @@ -1926,7 +1939,7 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.remote.ports.ruleTitle": "Add Forwarding Rule", "desktop.remote.ports.ruleUnsupported": "The remote server running on the host cannot listen on host ports. Reconnect to update it.", "desktop.remote.ports.rulesHeading": "Forwarding Rules", - "desktop.remote.ports.rulesHelp": "Forwarding rules listen on a host port and forward to another server or back to this computer. They stop when the connection ends and are not restored after reconnecting.", + "desktop.remote.ports.rulesHelp": "Forwarding rules listen on a host port and forward to another server or back to this computer. They stop when the connection ends; the window remembers them, and after reconnecting you start them again with Start.", "desktop.remote.ports.sourceListening": "Listening", "desktop.remote.ports.sourceManual": "Added", "desktop.remote.ports.statusFailed": "Failed: {reason}", @@ -1934,6 +1947,7 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.remote.ports.statusForwarding": "Forwarding…", "desktop.remote.ports.statusLabel": "Forwarded Ports", "desktop.remote.ports.statusNotForwarded": "Not forwarded", + "desktop.remote.ports.statusNotRunning": "Not running", "desktop.remote.ports.statusStopping": "Stopping…", "desktop.remote.ports.statusTooltip": "{count} forwarded. Click to open Ports.", "desktop.remote.ports.stop": "Stop Forwarding", @@ -5756,6 +5770,7 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.remote.ports.addLabel": "要转发的端口", "desktop.remote.ports.addPlaceholder": "端口、主机:端口或网址", "desktop.remote.ports.changeLocal": "更改本机端口…", + "desktop.remote.ports.columnLabel": "标签", "desktop.remote.ports.columnLocal": "本机地址", "desktop.remote.ports.columnProcess": "进程", "desktop.remote.ports.columnRemote": "远端端口", @@ -5766,12 +5781,19 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.remote.ports.confirmForward": "转发", "desktop.remote.ports.confirmTitle": "转发到其他地址?", "desktop.remote.ports.copyAddress": "复制本机地址", - "desktop.remote.ports.disconnected": "未连接。转发随连接一起结束,重新连接后需要再次转发。", + "desktop.remote.ports.disconnected": "未连接。转发随连接一起结束;重新连接后,没有停止的本地转发会自动恢复。", + "desktop.remote.ports.editLabel": "编辑标签…", "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.labelApply": "保存", + "desktop.remote.ports.labelBody": "标签显示在“标签”列,只保存在这台电脑上、只用于这个工作区。留空即删除标签。", + "desktop.remote.ports.labelCancel": "取消", + "desktop.remote.ports.labelField": "标签", + "desktop.remote.ports.labelInvalid": "最多 64 个字符,不能包含换行或制表符。", + "desktop.remote.ports.labelTitle": "编辑标签", "desktop.remote.ports.limit": "此连接已转发 {maximum} 个端口,达到上限,请先停止一个。", "desktop.remote.ports.loading": "正在读取主机上的监听端口…", "desktop.remote.ports.localApply": "转发", @@ -5785,10 +5807,13 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.remote.ports.process": "{process}(PID {pid})", "desktop.remote.ports.processUnknown": "未知", "desktop.remote.ports.readFailed": "无法读取主机上的监听端口:{reason}", + "desktop.remote.ports.recordsDamaged": "已保存的远程工作区端口和规则无法读取,因此不会恢复,改动也不会保存。Lithe 设置目录中的文件保持原样。", + "desktop.remote.ports.recordsFailed": "无法保存这个工作区的端口和规则:{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.restoreFailed": "重新连接后有 {count} 个转发无法恢复,原因见对应行。", "desktop.remote.ports.ruleAdd": "添加转发规则…", "desktop.remote.ports.ruleAllInterfaces": "监听主机的全部网卡", "desktop.remote.ports.ruleAllInterfacesNote": "能访问这台主机的任何电脑都能连接这个端口,并经由它访问目标。每次添加都会再次确认,不会记住。", @@ -5805,6 +5830,7 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.remote.ports.ruleConfirmReverseTitle": "把主机端口转发回本机?", "desktop.remote.ports.ruleConfirmTarget": "{target} 不是 {name} 自身的回环地址。添加后,能连接这个主机端口的程序都能经由主机访问这个地址。请确认你信任它后再继续。", "desktop.remote.ports.ruleConnectionsFailed": "{count}({failed} 个失败)", + "desktop.remote.ports.ruleForget": "忘记规则", "desktop.remote.ports.ruleHostNote": "{name} 监听下面的端口,并由主机自己连接目标,数据不经过本机。默认只监听主机的回环地址(127.0.0.1),只有主机上的程序能连接。", "desktop.remote.ports.ruleInvalidListen": "主机端口请输入 1 到 65535 之间的端口号,或留空。", "desktop.remote.ports.ruleKind": "方向", @@ -5820,6 +5846,7 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.remote.ports.rulePortInUse": "主机上的端口 {port} 已被其他程序占用,请换一个端口或留空。", "desktop.remote.ports.ruleReverseNote": "{name} 在回环地址(127.0.0.1)上监听下面的端口,把每个连接转回本机回环地址上的端口。主机上的所有用户都能连接这个端口。", "desktop.remote.ports.ruleReverseOff": "把主机端口转发回本机(反向转发)默认关闭,可在 设置 › 工具 › 远程工作区 中允许。", + "desktop.remote.ports.ruleStart": "启动…", "desktop.remote.ports.ruleSubmit": "添加", "desktop.remote.ports.ruleTarget": "目标", "desktop.remote.ports.ruleTargetPlaceholder": "端口、主机:端口或网址,由主机连接", @@ -5827,7 +5854,7 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.remote.ports.ruleTitle": "添加转发规则", "desktop.remote.ports.ruleUnsupported": "这台主机上运行的远端服务不支持在主机上监听端口,请重新连接以更新远端服务。", "desktop.remote.ports.rulesHeading": "转发规则", - "desktop.remote.ports.rulesHelp": "转发规则在主机上监听端口,转到另一台服务器或转回本机。规则随连接结束而停止,重新连接后不会自动恢复。", + "desktop.remote.ports.rulesHelp": "转发规则在主机上监听端口,转到另一台服务器或转回本机。规则随连接结束而停止;窗口会记住它们,重新连接后点“启动”即可再次启动。", "desktop.remote.ports.sourceListening": "监听发现", "desktop.remote.ports.sourceManual": "手动添加", "desktop.remote.ports.statusFailed": "失败:{reason}", @@ -5835,6 +5862,7 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.remote.ports.statusForwarding": "正在转发…", "desktop.remote.ports.statusLabel": "已转发的端口", "desktop.remote.ports.statusNotForwarded": "未转发", + "desktop.remote.ports.statusNotRunning": "未运行", "desktop.remote.ports.statusStopping": "正在停止…", "desktop.remote.ports.statusTooltip": "已转发 {count} 个端口,点击打开“端口”窗口。", "desktop.remote.ports.stop": "停止转发", diff --git a/desktop/internal/remoteconn/ports.go b/desktop/internal/remoteconn/ports.go new file mode 100644 index 000000000..26ff78828 --- /dev/null +++ b/desktop/internal/remoteconn/ports.go @@ -0,0 +1,126 @@ +package remoteconn + +import ( + "context" + "errors" + + "github.com/1lck/Lithe-IDEA/desktop/internal/configfile" + "github.com/1lck/Lithe-IDEA/desktop/internal/core" +) + +// What the Ports window of a remote workspace remembers (the ports the user added, their labels +// and local ports, the local forwards left running and the forwarding rules started on the host) +// lives in /remote/ports.json, the path and the size limit Core names +// (remote.portRecords), next to the remote preferences in the platform user preference directory. +// It is machine-local and owned by this machine's user: created on the first change, and only ever +// replaced whole, atomically, against the bytes it was read from. Core keys every record by the +// connection's target and the workspace's real path on the host. The file is never written to a +// host, a workspace, the app bundle or the installation directory, so it does not affect code +// signing or Sparkle delta updates, and it is not copied across worktrees. It holds no secret: +// host addresses, port numbers, the user's labels and the addresses typed into the window. + +// PortsKernel is the part of the Core client the port records use. +type PortsKernel interface { + RemotePortRecords(ctx context.Context, document *string, sessionID, workspace string) (core.RemotePortRecordsState, error) + EditRemotePortRecords(ctx context.Context, document *string, sessionID, workspace string, edit core.RemotePortRecordEdit) (changed bool, updated *string, records core.RemotePortRecords, err error) + RestoreRemoteForwards(ctx context.Context, document *string, sessionID, workspace string) ([]core.RemoteRestoredForward, error) +} + +// PortRecords is the port records document with the bytes it was read from, and the records of +// the workspace it was read for. +type PortRecords struct { + // State is Core's reading for the workspace. + State core.RemotePortRecordsState + root string + session string + workspace string + file configfile.Snapshot +} + +// ReadPortRecords reads the port records kept under root, the platform preference directory, for +// workspace opened over the session sessionID. Reading creates nothing. A document Core cannot +// decode fails with ErrDamaged joined to Core's error; a closed session fails with Core's +// CodeConnectionClosed. +func ReadPortRecords(ctx context.Context, kernel PortsKernel, root, sessionID, workspace string) (PortRecords, error) { + if root == "" { + return PortRecords{}, ErrUnavailable + } + // Core names the storage only for an open workspace, so the first reading has no document. + plan, err := kernel.RemotePortRecords(ctx, nil, sessionID, workspace) + if err != nil { + return PortRecords{}, err + } + file, err := configfile.Capture(ctx, root, plan.Storage.RelativePath, plan.Storage.MaximumBytes) + if errors.Is(err, configfile.ErrTooLarge) || errors.Is(err, configfile.ErrEncoding) { + return PortRecords{}, errors.Join(ErrDamaged, err) + } + if err != nil { + return PortRecords{}, err + } + text, err := file.Text() + if err != nil { + return PortRecords{}, errors.Join(ErrDamaged, err) + } + state := plan + if text != nil { + if state, err = kernel.RemotePortRecords(ctx, text, sessionID, workspace); err != nil { + return PortRecords{}, portRecordsError(err) + } + } + return PortRecords{State: state, root: root, session: sessionID, workspace: workspace, file: file}, nil +} + +// Edit applies edit to the bytes p was read from and publishes the result; after holds the +// workspace's records the edit leads to. An edit that changes nothing writes nothing. A refused +// value fails with Core's CodeInvalidRequest naming the field, and a file changed since p was read +// with ErrConflict, both without writing; committed reports that the new document reached the disk. +func (p PortRecords) Edit(ctx context.Context, kernel PortsKernel, edit core.RemotePortRecordEdit) (after core.RemotePortRecords, committed bool, err error) { + if p.root == "" { + return p.State.Records, false, ErrUnavailable + } + text, err := p.file.Text() + if err != nil { + return p.State.Records, false, errors.Join(ErrDamaged, err) + } + changed, document, after, err := kernel.EditRemotePortRecords(ctx, text, p.session, p.workspace, edit) + if err != nil { + return p.State.Records, false, portRecordsError(err) + } + if !changed { + return after, false, nil + } + if document == nil { + return p.State.Records, false, errors.New("remoteconn: Core changed the port records without a document") + } + committed, err = p.file.Replace(ctx, []byte(*document), func() error { return p.file.Verify(ctx) }) + if errors.Is(err, configfile.ErrConflict) { + err = errors.Join(ErrConflict, err) + } + return after, committed, err +} + +// Restore starts again the local forwards p records as left running, as +// core.Client.RestoreRemoteForwards does. +func (p PortRecords) Restore(ctx context.Context, kernel PortsKernel) ([]core.RemoteRestoredForward, error) { + if p.root == "" { + return nil, ErrUnavailable + } + text, err := p.file.Text() + if err != nil { + return nil, errors.Join(ErrDamaged, err) + } + restored, err := kernel.RestoreRemoteForwards(ctx, text, p.session, p.workspace) + if err != nil { + return nil, portRecordsError(err) + } + return restored, nil +} + +// portRecordsError marks Core's refusal to decode the stored document as ErrDamaged. +func portRecordsError(err error) error { + var coreErr *core.Error + if errors.As(err, &coreErr) && coreErr.Code == core.CodeParseFailed { + return errors.Join(ErrDamaged, err) + } + return err +} diff --git a/desktop/internal/remoteconn/ports_test.go b/desktop/internal/remoteconn/ports_test.go new file mode 100644 index 000000000..4d2dc6a60 --- /dev/null +++ b/desktop/internal/remoteconn/ports_test.go @@ -0,0 +1,180 @@ +package remoteconn + +import ( + "context" + "encoding/json" + "errors" + "os" + "path/filepath" + "slices" + "testing" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" +) + +// testPorts is a PortsKernel that keeps one workspace's records as the JSON of +// core.RemotePortRecords, without a session, and remembers the document of every call. +type testPorts struct { + documents []string +} + +var testPortsStorage = core.RemotePreferenceStorage{RelativePath: "remote/ports.json", MaximumBytes: 4096} + +func (k *testPorts) decode(document *string, sessionID string) (core.RemotePortRecords, error) { + if document != nil { + k.documents = append(k.documents, *document) + } + if sessionID != "session-1" { + return core.RemotePortRecords{}, &core.Error{Code: core.CodeConnectionClosed, Message: "closed"} + } + var records core.RemotePortRecords + if document != nil && json.Unmarshal([]byte(*document), &records) != nil { + return core.RemotePortRecords{}, &core.Error{Code: core.CodeParseFailed, Message: "not json"} + } + return records, nil +} + +func (k *testPorts) RemotePortRecords(_ context.Context, document *string, sessionID, workspace string) (core.RemotePortRecordsState, error) { + records, err := k.decode(document, sessionID) + return core.RemotePortRecordsState{Records: records, Workspace: workspace, Storage: testPortsStorage}, err +} + +func (k *testPorts) EditRemotePortRecords(_ context.Context, document *string, sessionID, _ string, edit core.RemotePortRecordEdit) (bool, *string, core.RemotePortRecords, error) { + records, err := k.decode(document, sessionID) + if err != nil { + return false, nil, core.RemotePortRecords{}, err + } + if edit.Port != nil { + records.Ports = slices.DeleteFunc(records.Ports, func(record core.RemotePortRecord) bool { return record.Port == edit.Port.Port }) + records.Ports = append(records.Ports, *edit.Port) + } + data, err := json.Marshal(records) + if err != nil { + return false, nil, core.RemotePortRecords{}, err + } + if document != nil && *document == string(data) { + return false, nil, records, nil + } + updated := string(data) + return true, &updated, records, nil +} + +func (k *testPorts) RestoreRemoteForwards(_ context.Context, document *string, sessionID, _ string) ([]core.RemoteRestoredForward, error) { + records, err := k.decode(document, sessionID) + if err != nil { + return nil, err + } + var restored []core.RemoteRestoredForward + for _, record := range records.Ports { + if record.ForwardTarget != "" { + restored = append(restored, core.RemoteRestoredForward{Port: record.Port, Forward: &core.RemoteForward{TargetPort: record.Port}, Created: true}) + } + } + return restored, nil +} + +// Reading absent records creates nothing; an edit writes only the records document below the +// preference root, an edit that changes nothing writes nothing, and the forwards are restored from +// the bytes on disk. +func TestPortRecordsWriteOnlyTheirDocument(t *testing.T) { + ctx := testContext(t) + kernel := &testPorts{} + root := filepath.Join(t.TempDir(), "preferences") + read, err := ReadPortRecords(ctx, kernel, root, "session-1", "/srv/repo") + if err != nil || read.State.Workspace != "/srv/repo" || len(read.State.Records.Ports) != 0 { + t.Fatalf("read: rows = %d, err = %v", len(read.State.Records.Ports), err) + } + if _, err := os.Stat(root); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("reading created the preference root: %v", err) + } + edit := core.RemotePortRecordEdit{Port: &core.RemotePortRecord{Port: 8080, Label: "web", ForwardTarget: "localhost"}} + after, committed, err := read.Edit(ctx, kernel, edit) + if err != nil || !committed || len(after.Ports) != 1 || after.Ports[0].Label != "web" { + t.Fatalf("edit: committed = %v, rows = %d, err = %v", committed, len(after.Ports), err) + } + var files []string + if err := filepath.WalkDir(root, func(path string, entry os.DirEntry, err error) error { + if err == nil && !entry.IsDir() { + files = append(files, path) + } + return err + }); err != nil { + t.Fatal(err) + } + if want := filepath.Join(root, "remote", "ports.json"); len(files) != 1 || files[0] != want { + t.Fatalf("the edit wrote %d files, want the records document alone", len(files)) + } + reread, err := ReadPortRecords(ctx, kernel, root, "session-1", "/srv/repo") + if err != nil || len(reread.State.Records.Ports) != 1 { + t.Fatalf("reread: rows = %d, err = %v", len(reread.State.Records.Ports), err) + } + data, _ := os.ReadFile(files[0]) + if _, committed, err := reread.Edit(ctx, kernel, edit); err != nil || committed { + t.Fatalf("unchanged edit: committed = %v, err = %v", committed, err) + } + if again, _ := os.ReadFile(files[0]); string(again) != string(data) { + t.Fatal("an edit that changes nothing rewrote the document") + } + restored, err := reread.Restore(ctx, kernel) + if err != nil || len(restored) != 1 || restored[0].Port != 8080 || kernel.documents[len(kernel.documents)-1] != string(data) { + t.Fatalf("restore: %d forwards, err = %v, want the forward the document records", len(restored), err) + } +} + +// An edit of a document changed since it was read is ErrConflict and keeps the other writer's +// bytes. +func TestPortRecordsEditOfAChangedDocumentIsAConflict(t *testing.T) { + ctx := testContext(t) + kernel := &testPorts{} + root := t.TempDir() + read, err := ReadPortRecords(ctx, kernel, root, "session-1", "/srv/repo") + if err != nil { + t.Fatal(err) + } + path := filepath.Join(root, "remote", "ports.json") + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + t.Fatal(err) + } + other := []byte(`{"ports":[{"port":9090,"label":"other"}],"rules":[]}`) + if err := os.WriteFile(path, other, 0o600); err != nil { + t.Fatal(err) + } + _, committed, err := read.Edit(ctx, kernel, core.RemotePortRecordEdit{Port: &core.RemotePortRecord{Port: 8080, Label: "web"}}) + if !errors.Is(err, ErrConflict) || committed { + t.Fatalf("edit: committed = %v, err = %v, want a conflict", committed, err) + } + if data, _ := os.ReadFile(path); string(data) != string(other) { + t.Fatal("the conflicting edit replaced the other writer's document") + } +} + +// A document Core cannot decode is ErrDamaged and is never sent to be edited; a closed session is +// Core's error and not a damaged document, and no preference root is ErrUnavailable. +func TestDamagedPortRecordsAreReported(t *testing.T) { + ctx := testContext(t) + kernel := &testPorts{} + root := t.TempDir() + path := filepath.Join(root, "remote", "ports.json") + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte("{not json"), 0o600); err != nil { + t.Fatal(err) + } + if _, err := ReadPortRecords(ctx, kernel, root, "session-1", "/srv/repo"); !errors.Is(err, ErrDamaged) { + t.Fatalf("read: err = %v, want ErrDamaged", err) + } + var coreErr *core.Error + if _, err := ReadPortRecords(ctx, kernel, root, "session-2", "/srv/repo"); errors.Is(err, ErrDamaged) || !errors.As(err, &coreErr) || coreErr.Code != core.CodeConnectionClosed { + t.Fatalf("closed session: err = %v, want connection_closed", err) + } + if _, err := ReadPortRecords(ctx, kernel, "", "session-1", "/srv/repo"); !errors.Is(err, ErrUnavailable) { + t.Fatalf("no root: err = %v", err) + } + if _, _, err := (PortRecords{}).Edit(ctx, kernel, core.RemotePortRecordEdit{}); !errors.Is(err, ErrUnavailable) { + t.Fatalf("edit without a reading: err = %v", err) + } + if _, err := (PortRecords{}).Restore(ctx, kernel); !errors.Is(err, ErrUnavailable) { + t.Fatalf("restore without a reading: err = %v", err) + } +} diff --git a/desktop/internal/workbench/app.go b/desktop/internal/workbench/app.go index 7dee97853..e4a43d525 100644 --- a/desktop/internal/workbench/app.go +++ b/desktop/internal/workbench/app.go @@ -254,6 +254,9 @@ type Kernel interface { 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) + RemotePortRecords(ctx context.Context, document *string, sessionID, workspace string) (core.RemotePortRecordsState, error) + EditRemotePortRecords(ctx context.Context, document *string, sessionID, workspace string, edit core.RemotePortRecordEdit) (changed bool, updated *string, records core.RemotePortRecords, err error) + RestoreRemoteForwards(ctx context.Context, document *string, sessionID, workspace string) ([]core.RemoteRestoredForward, 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) diff --git a/desktop/internal/workbench/remote_port_records.go b/desktop/internal/workbench/remote_port_records.go new file mode 100644 index 000000000..0168f4828 --- /dev/null +++ b/desktop/internal/workbench/remote_port_records.go @@ -0,0 +1,579 @@ +package workbench + +import ( + "context" + "errors" + "net" + "net/netip" + "slices" + "strconv" + "strings" + "time" + "unicode" + "unicode/utf8" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/1lck/Lithe-IDEA/desktop/internal/remoteconn" +) + +// This file is what the Ports window of a remote workspace remembers after the workspace closes or +// its connection drops (#2231 R1 #46b): the ports the user added, the labels and local ports chosen +// for rows, the local forwards left running and the forwarding rules the user started on the host. +// It lives in the port records document of remoteconn (remote/ports.json under the platform +// preference directory), where Core keys it by the connection's target and the workspace's real +// path on the host, so another host, account, container or folder never sees it. +// +// - The window keeps the records in memory and writes only the rows and rules that differ from +// what Core last reported for the document, one edit at a time, each against the bytes it read. +// - Every attach of a session, a reconnect or the workspace opened again, first reads the +// records and then has Core start again the local forwards left running, each with the +// confirmation it had (S28), as VS Code restores its forwarded ports. A forward that does not +// start is shown as failed and forgotten. +// - Rules are remembered but never started on their own: a remembered rule that does not run is +// listed with Start, which opens Add Forwarding Rule filled in with it, so every question is +// asked again; listening on every interface of the host is never remembered. +// - A document Core cannot decode is never overwritten: the window says so and keeps its records +// in memory only. Without a preference directory nothing is kept. +// +// The log names the outcome only, never an address, a label or a URL. + +const ( + // remotePortRecordsTimeout bounds one reading, write or restore of the records. + remotePortRecordsTimeout = 30 * time.Second + // remotePortRecordsRetries is how often an edit is read and applied again when another window + // changed the document meanwhile. + remotePortRecordsRetries = 3 + // remotePortLabelMax is the longest label Core keeps, in characters. + remotePortLabelMax = 64 +) + +// remotePortRunning is a local forward the user started for a row and did not stop: the target +// host it reaches, and whether the user confirmed that target outside the host's loopback +// interface (S28). +type remotePortRunning struct { + host string + confirmed bool +} + +// remotePortLabelTarget is what the label dialog names: a row of the list, or a rule. +type remotePortLabelTarget struct { + key *remotePortKey + rule *core.RemotePortRule +} + +// remotePortRecordPath is the path a record keeps of a URL's: without its query and fragment, +// which may carry a token, and "" when nothing but / remains, as Core keeps it. +func remotePortRecordPath(path string) string { + if at := strings.IndexAny(path, "?#"); at >= 0 { + path = path[:at] + } + if path == "/" { + return "" + } + return path +} + +// record is what the window remembers of row key. +func (ports *remotePorts) record(key remotePortKey) core.RemotePortRecord { + record := core.RemotePortRecord{Host: key.host, Port: key.port, Label: ports.labels[key], LocalPort: ports.localPorts[key]} + for _, added := range ports.manual { + if added.key == key { + record.Added = &core.RemotePortRecordAdded{Host: added.host, Scheme: added.scheme, Path: remotePortRecordPath(added.path)} + } + } + if running, ok := ports.running[key]; ok { + record.ForwardTarget, record.ConfirmedTarget = running.host, running.confirmed + } + return record +} + +// blankRemotePortRecord reports a record with nothing but its key, which Core removes. +func blankRemotePortRecord(record core.RemotePortRecord) bool { + return record.Added == nil && record.Label == "" && record.LocalPort == 0 && record.ForwardTarget == "" +} + +// sameRemotePortRecord reports two records that remember the same. +func sameRemotePortRecord(x, y core.RemotePortRecord) bool { + if (x.Added == nil) != (y.Added == nil) || (x.Added != nil && *x.Added != *y.Added) { + return false + } + x.Added, y.Added = nil, nil + return x == y +} + +// canonicalRuleHost is a rule's target host as two rules compare it: an IP address in canonical +// form, any other name in lower case. +func canonicalRuleHost(host string) string { + host = strings.TrimSuffix(strings.TrimPrefix(host, "["), "]") + if ip, err := netip.ParseAddr(host); err == nil { + return ip.Unmap().String() + } + return strings.ToLower(host) +} + +// sameRemotePortRule reports the same rule, whatever the labels. +func sameRemotePortRule(x, y core.RemotePortRule) bool { + return x.Kind == y.Kind && x.ListenPort == y.ListenPort && x.TargetPort == y.TargetPort && x.LocalPort == y.LocalPort && + canonicalRuleHost(x.TargetHost) == canonicalRuleHost(y.TargetHost) +} + +// remotePortRuleOf is the rule a running host or reverse forward was started as. +func remotePortRuleOf(forward core.RemoteForward) core.RemotePortRule { + rule := core.RemotePortRule{Kind: forward.Kind} + if forward.RequestedHostPort != nil { + rule.ListenPort = *forward.RequestedHostPort + } + if forward.Kind == core.RemoteForwardReverse { + rule.LocalPort = forward.LocalPort + } else { + rule.TargetHost, rule.TargetPort = forward.TargetHost, forward.TargetPort + } + return rule +} + +// rememberedRule is the remembered rule that is the same as rule, and whether there is one. +func (ports *remotePorts) rememberedRule(rule core.RemotePortRule) (int, bool) { + at := slices.IndexFunc(ports.remembered, func(remembered core.RemotePortRule) bool { return sameRemotePortRule(remembered, rule) }) + return at, at >= 0 +} + +// idleRules are the remembered rules no forward of the session runs, in the order they were added. +func (ports *remotePorts) idleRules() []core.RemotePortRule { + var idle []core.RemotePortRule + for _, rule := range ports.remembered { + if !slices.ContainsFunc(ports.rules(), func(forward core.RemoteForward) bool { return sameRemotePortRule(remotePortRuleOf(forward), rule) }) { + idle = append(idle, rule) + } + } + return idle +} + +// setRunning records the local forward of row key as running to running, or as stopped for nil. +func (ports *remotePorts) setRunning(key remotePortKey, running *remotePortRunning) { + if running == nil { + delete(ports.running, key) + return + } + if ports.running == nil { + ports.running = map[remotePortKey]remotePortRunning{} + } + ports.running[key] = *running +} + +// recordEdits are the edits that bring the document to what the window remembers: one per row and +// rule that differs from what Core last reported. There are none before the records were read. +func (ports *remotePorts) recordEdits() []core.RemotePortRecordEdit { + if ports.written == nil { + return nil + } + written := map[remotePortKey]core.RemotePortRecord{} + keys := map[remotePortKey]bool{} + for _, record := range ports.written.Ports { + key := remotePortKey{host: remotePortHost(record.Host), port: record.Port} + written[key], keys[key] = record, true + } + for _, added := range ports.manual { + keys[added.key] = true + } + for key := range ports.labels { + keys[key] = true + } + for key := range ports.localPorts { + keys[key] = true + } + for key := range ports.running { + keys[key] = true + } + sorted := make([]remotePortKey, 0, len(keys)) + for key := range keys { + sorted = append(sorted, key) + } + slices.SortFunc(sorted, func(x, y remotePortKey) int { + if x.port != y.port { + return int(x.port) - int(y.port) + } + return strings.Compare(x.host, y.host) + }) + var edits []core.RemotePortRecordEdit + for _, key := range sorted { + want := ports.record(key) + have, had := written[key] + if (!had && blankRemotePortRecord(want)) || (had && sameRemotePortRecord(have, want)) { + continue + } + edits = append(edits, core.RemotePortRecordEdit{Port: &want}) + } + for _, rule := range ports.remembered { + at := slices.IndexFunc(ports.written.Rules, func(have core.RemotePortRule) bool { return sameRemotePortRule(have, rule) }) + if at < 0 || ports.written.Rules[at].Label != rule.Label { + edits = append(edits, core.RemotePortRecordEdit{Rule: &rule}) + } + } + for _, rule := range ports.written.Rules { + if _, kept := ports.rememberedRule(rule); !kept { + edits = append(edits, core.RemotePortRecordEdit{RemoveRule: &rule}) + } + } + return edits +} + +// merge takes in the records read when the workspace opened, filling only what the window does +// not remember yet. +func (ports *remotePorts) merge(records core.RemotePortRecords) { + for _, record := range records.Ports { + key := remotePortKey{host: remotePortHost(record.Host), port: record.Port} + if record.Added != nil && !slices.ContainsFunc(ports.manual, func(added remotePortAdded) bool { return added.key == key }) { + ports.manual = append(ports.manual, remotePortAdded{key: key, host: record.Added.Host, scheme: record.Added.Scheme, path: record.Added.Path}) + } + if _, known := ports.labels[key]; record.Label != "" && !known { + if ports.labels == nil { + ports.labels = map[remotePortKey]string{} + } + ports.labels[key] = record.Label + } + if _, known := ports.localPorts[key]; record.LocalPort != 0 && !known { + if ports.localPorts == nil { + ports.localPorts = map[remotePortKey]uint16{} + } + ports.localPorts[key] = record.LocalPort + } + if _, known := ports.running[key]; record.ForwardTarget != "" && !known { + ports.setRunning(key, &remotePortRunning{host: record.ForwardTarget, confirmed: record.ConfirmedTarget}) + } + } + for _, rule := range records.Rules { + if _, known := ports.rememberedRule(rule); !known { + ports.remembered = append(ports.remembered, rule) + } + } +} + +// writeRemotePortEdits applies edits in order to the port records under root, each against the +// bytes it read, and reads again when another window changed the document meanwhile. after is +// what Core reported after the last edit applied, nil when none was; it stops at the first edit +// that fails. It runs off the window thread. +func writeRemotePortEdits(ctx context.Context, kernel remoteconn.PortsKernel, root, session, workspace string, edits []core.RemotePortRecordEdit) (*core.RemotePortRecords, error) { + var after *core.RemotePortRecords + for _, edit := range edits { + for attempt := 1; ; attempt++ { + records, err := remoteconn.ReadPortRecords(ctx, kernel, root, session, workspace) + if err == nil { + var updated core.RemotePortRecords + if updated, _, err = records.Edit(ctx, kernel, edit); err == nil { + after = &updated + break + } + } + if errors.Is(err, remoteconn.ErrConflict) && attempt < remotePortRecordsRetries { + continue + } + return after, err + } + } + return after, nil +} + +// remotePortsChanged records that what the window remembers changed, and writes it. +func (a *App) remotePortsChanged(p *project) { + if p.remote == nil { + return + } + p.remote.ports.recordsRevision++ + a.syncRemotePorts(p) +} + +// syncRemotePorts reads the records and restores the forwards once a session attached, or writes +// what changed since Core last reported the records. One runs at a time; the one that ends starts +// the next. +func (a *App) syncRemotePorts(p *project) { + r := p.remote + if r == nil || r.closed || r.session == "" || r.ports.recordsBusy { + // log-exempt: 非用户操作:没有会话或上一次记录读写还在进行,它结束时会再同步。 + return + } + ports := &r.ports + if ports.recordsAttach { + ports.recordsAttach = false + a.restoreRemotePorts(p) + return + } + edits := ports.recordEdits() + if len(edits) == 0 { + return + } + ports.recordsBusy = true + revision := ports.recordsRevision + session, kernel, root, workspace := r.session, a.kernel, a.globalToolchainRoot(), r.binding.RemoteRoot() + a.background(p, remotePortRecordsTimeout, func(ctx context.Context) func(*App) { + after, err := writeRemotePortEdits(ctx, kernel, root, session, workspace, edits) + return func(a *App) { + ports.recordsBusy = false + if r.closed { + // log-exempt: 用户取消:工作区已关闭,写入结果不再显示。 + return + } + a.remotePortsWritten(p, session, after, err) + // Only a change made meanwhile or a new session writes again, so an edit Core keeps + // differently from the window never loops. + if ports.recordsRevision != revision || ports.recordsAttach { + a.syncRemotePorts(p) + } + } + }) +} + +// remotePortsWritten records how writing the records over session ended: after is what Core +// reported after the last edit applied, nil when none was. +func (a *App) remotePortsWritten(p *project, session string, after *core.RemotePortRecords, err error) { + r := p.remote + ports := &r.ports + if after != nil { + ports.written = after + } + switch { + case err == nil: + case errors.Is(err, remoteconn.ErrUnavailable): + // log-exempt: 非用户操作:没有用户偏好目录,端口记录只留在内存里,与远程偏好相同。 + ports.written = nil + case remoteConnectionClosed(err): + if r.session == session { + a.loseRemote(p, session, err) + } + default: + a.backgroundFailed("remote_port_records", remoteLogError(err)) + ports.notice = a.remotePortRecordsNotice(err) + if errors.Is(err, remoteconn.ErrDamaged) { + // A document Core cannot decode is never overwritten. + ports.written = nil + } + } +} + +// remotePortRecordsNotice is the window's message about records that could not be read or kept. +func (a *App) remotePortRecordsNotice(err error) string { + if errors.Is(err, remoteconn.ErrDamaged) { + return i18n.Shared(a.language(), "desktop.remote.ports.recordsDamaged") + } + return i18n.SharedFormat(a.language(), "desktop.remote.ports.recordsFailed", map[string]string{"reason": remotePortsReason(err)}) +} + +// restoreRemotePorts runs once a session attached: it writes what changed while there was none, +// reads the records — taking them in when the workspace has just opened — and has Core start again +// the local forwards left running. +func (a *App) restoreRemotePorts(p *project) { + r := p.remote + ports := &r.ports + ports.recordsBusy = true + edits := ports.recordEdits() + session, kernel, root, workspace := r.session, a.kernel, a.globalToolchainRoot(), r.binding.RemoteRoot() + a.background(p, remotePortRecordsTimeout, func(ctx context.Context) func(*App) { + after, writeErr := writeRemotePortEdits(ctx, kernel, root, session, workspace, edits) + var state remoteconn.PortRecords + var readErr, restoreErr error + var restored []core.RemoteRestoredForward + if writeErr == nil || !remoteConnectionClosed(writeErr) { + if state, readErr = remoteconn.ReadPortRecords(ctx, kernel, root, session, workspace); readErr == nil { + restored, restoreErr = state.Restore(ctx, kernel) + } + } + return func(a *App) { + ports.recordsBusy = false + if r.closed { + // log-exempt: 用户取消:工作区已关闭,读到的记录和恢复的转发不再显示,Core 已随会话停止转发。 + return + } + if len(edits) > 0 { + a.remotePortsWritten(p, session, after, writeErr) + } + if r.session != session { + // log-exempt: 非用户操作:会话已换,新会话接上时会重新读取并恢复。 + a.syncRemotePorts(p) + return + } + if readErr == nil { + records := state.State.Records + if ports.written == nil { + ports.merge(records) + } + ports.written = &records + } + if writeErr == nil || !remoteConnectionClosed(writeErr) { + a.remotePortsRestored(p, session, readErr, restored, restoreErr) + } + a.syncRemotePorts(p) + } + }) +} + +// remotePortsRestored records how reading the records and restoring the forwards over session +// ended. A forward that did not start is shown as failed and forgotten. +func (a *App) remotePortsRestored(p *project, session string, readErr error, restored []core.RemoteRestoredForward, restoreErr error) { + ports := &p.remote.ports + err := readErr + if err == nil { + err = restoreErr + } + switch { + case err == nil: + case errors.Is(err, remoteconn.ErrUnavailable): + // log-exempt: 非用户操作:没有用户偏好目录,没有可恢复的记录。 + return + case remoteConnectionClosed(err): + a.loseRemote(p, session, err) + return + default: + a.backgroundFailed("remote_port_records", remoteLogError(err)) + ports.notice = a.remotePortRecordsNotice(err) + return + } + var failed *core.Error + count := 0 + for _, item := range restored { + key := remotePortKey{host: remotePortHost(item.Host), port: item.Port} + if item.Forward != nil { + ports.putForward(*item.Forward) + ports.setRunning(forwardKey(*item.Forward), &remotePortRunning{host: item.Forward.TargetHost, confirmed: !item.Forward.LoopbackTarget}) + ports.setFailed(key, "") + continue + } + count++ + if failed == nil { + failed = item.Err + } + ports.setRunning(key, nil) + reason := item.Err.Message + if item.Err.Code == core.CodeInvalidRequest || reason == "" { + reason = i18n.Shared(a.language(), "desktop.remote.ports.invalidTarget") + } + ports.setFailed(key, reason) + } + if count > 0 { + a.backgroundFailed("remote_port_restore", remoteLogError(failed)) + ports.notice = i18n.SharedFormat(a.language(), "desktop.remote.ports.restoreFailed", map[string]string{"count": strconv.Itoa(count)}) + } +} + +// remotePortRuleRecord is the rule the dialog started, as the window remembers it: never with the +// choice to listen on every interface of the host. +func remotePortRuleRecord(kind remotePortRuleKind, host core.RemoteHostForwardRule, reverse core.RemoteReverseForwardRule) core.RemotePortRule { + if kind == remotePortRuleReverse { + return core.RemotePortRule{Kind: core.RemoteForwardReverse, ListenPort: reverse.ListenPort, LocalPort: reverse.LocalPort} + } + return core.RemotePortRule{Kind: core.RemoteForwardHost, ListenPort: host.ListenPort, TargetHost: host.Host, TargetPort: host.Port} +} + +// rememberRemotePortRule remembers a rule that started, keeping the label of the same rule. +func (a *App) rememberRemotePortRule(p *project, rule core.RemotePortRule) { + ports := &p.remote.ports + if _, known := ports.rememberedRule(rule); known { + return + } + ports.remembered = append(ports.remembered, rule) + a.remotePortsChanged(p) +} + +// forgetRemotePortRule forgets a remembered rule; a running one keeps running until it stops. +func (a *App) forgetRemotePortRule(p *project, rule core.RemotePortRule, surface actionSurface) { + ports := &p.remote.ports + at, known := ports.rememberedRule(rule) + if !known { + // log-exempt: 非用户操作:这条规则已被忘记,菜单项此时不显示。 + return + } + a.performed("remote.ports.ruleForget", surface) + ports.remembered = slices.Delete(ports.remembered, at, at+1) + a.remotePortsChanged(p) +} + +// startRememberedRule opens Add Forwarding Rule filled in with a remembered rule. +func (a *App) startRememberedRule(p *project, rule core.RemotePortRule, surface actionSurface) { + a.openRemotePortRule(p, &rule, surface) +} + +// remotePortRuleDraftOf fills a new dialog with rule: its direction, host port and what it +// reaches. Listening on every interface is never filled in. +func remotePortRuleDraftOf(rule core.RemotePortRule) *remotePortRuleDraft { + draft := &remotePortRuleDraft{} + if rule.ListenPort != 0 { + draft.listen.SetText(strconv.Itoa(int(rule.ListenPort))) + } + if rule.Kind == core.RemoteForwardReverse { + draft.kind = remotePortRuleReverse + draft.target.SetText(strconv.Itoa(int(rule.LocalPort))) + return draft + } + draft.target.SetText(net.JoinHostPort(rule.TargetHost, strconv.Itoa(int(rule.TargetPort)))) + return draft +} + +// labelOf is the label of what target names, "" for none. +func (ports *remotePorts) labelOf(target remotePortLabelTarget) string { + if target.key != nil { + return ports.labels[*target.key] + } + if at, known := ports.rememberedRule(*target.rule); known { + return ports.remembered[at].Label + } + return "" +} + +// ruleLabel is the label of the rule a running forward was started as, "" for none. +func (ports *remotePorts) ruleLabel(forward core.RemoteForward) string { + rule := remotePortRuleOf(forward) + return ports.labelOf(remotePortLabelTarget{rule: &rule}) +} + +// editRemotePortLabel opens the dialog the label of a row or a rule is typed in. +func (a *App) editRemotePortLabel(p *project, target remotePortLabelTarget, surface actionSurface) { + r := p.remote + if r == nil || r.closed { + // log-exempt: 非用户操作:工作区已关闭,菜单项此时不可用。 + return + } + a.performed("remote.ports.label", surface) + ports := &r.ports + ports.label, ports.labelOpen, ports.labelInvalid = &target, true, false + ports.labelField.SetText(ports.labelOf(target)) +} + +// validRemotePortLabel reports a label Core keeps: at most remotePortLabelMax characters and no +// control character. +func validRemotePortLabel(label string) bool { + return utf8.RuneCountInString(label) <= remotePortLabelMax && !strings.ContainsFunc(label, unicode.IsControl) +} + +// applyRemotePortLabel gives the dialog's label to its row or rule; an empty one removes it. +func (a *App) applyRemotePortLabel(p *project) { + ports := &p.remote.ports + target := ports.label + if target == nil { + // log-exempt: 非用户操作:标签对话框已关闭,没有要改的标签。 + return + } + label := strings.TrimSpace(ports.labelField.Text()) + if !validRemotePortLabel(label) { + a.operationRejected("remote_port_label", "invalid_label") + ports.labelInvalid = true + return + } + ports.label, ports.labelOpen, ports.labelInvalid = nil, false, false + switch { + case target.key != nil && label == "": + delete(ports.labels, *target.key) + case target.key != nil: + if ports.labels == nil { + ports.labels = map[remotePortKey]string{} + } + ports.labels[*target.key] = label + default: + rule := *target.rule + rule.Label = label + if at, known := ports.rememberedRule(rule); known { + ports.remembered[at].Label = label + } else { + ports.remembered = append(ports.remembered, rule) + } + } + a.remotePortsChanged(p) +} diff --git a/desktop/internal/workbench/remote_port_records_test.go b/desktop/internal/workbench/remote_port_records_test.go new file mode 100644 index 000000000..3edfc8373 --- /dev/null +++ b/desktop/internal/workbench/remote_port_records_test.go @@ -0,0 +1,356 @@ +package workbench + +import ( + "context" + "encoding/json" + "errors" + "io/fs" + "os" + "path/filepath" + "slices" + "strings" + "testing" + "unicode" + "unicode/utf8" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" +) + +// remoteHostRecords stands in for Core's port records (remote.portRecords, remote.editPortRecords +// and remote.restoreForwards): the document is a JSON object of each workspace's records, read and +// edited as Core does, and the forwards left running start again through the host's ports. +type remoteHostRecords struct { + // edits are the edits the window asked for, and restores how often it restored forwards. + edits []core.RemotePortRecordEdit + restores int + // failRestore are the ports whose forwards do not start again. + failRestore map[uint16]bool +} + +// remoteTestRecordsStorage is where the stand-in names the document. +var remoteTestRecordsStorage = core.RemotePreferenceStorage{RelativePath: "remote/ports.json", MaximumBytes: 256 * 1024} + +// remoteTestRecords decodes document into the records of every workspace. +func remoteTestRecords(document *string) (map[string]core.RemotePortRecords, error) { + all := map[string]core.RemotePortRecords{} + if document == nil { + return all, nil + } + if err := json.Unmarshal([]byte(*document), &all); err != nil { + return nil, &core.Error{Command: "remote.portRecords", Code: core.CodeParseFailed, Message: "damaged"} + } + return all, nil +} + +func (k *remoteHostKernel) RemotePortRecords(_ context.Context, document *string, _, workspace string) (core.RemotePortRecordsState, error) { + all, err := remoteTestRecords(document) + if err != nil { + return core.RemotePortRecordsState{}, err + } + return core.RemotePortRecordsState{Records: all[workspace], Workspace: workspace, Storage: remoteTestRecordsStorage}, nil +} + +func (k *remoteHostKernel) EditRemotePortRecords(_ context.Context, document *string, _, workspace string, edit core.RemotePortRecordEdit) (bool, *string, core.RemotePortRecords, error) { + k.mu.Lock() + k.ports.records.edits = append(k.ports.records.edits, edit) + k.mu.Unlock() + all, err := remoteTestRecords(document) + if err != nil { + return false, nil, core.RemotePortRecords{}, err + } + before := all[workspace] + records := core.RemotePortRecords{Ports: slices.Clone(before.Ports), Rules: slices.Clone(before.Rules)} + refused := func(label string) bool { + return utf8.RuneCountInString(label) > remotePortLabelMax || strings.ContainsFunc(label, unicode.IsControl) + } + switch { + case edit.Port != nil: + if refused(edit.Port.Label) { + return false, nil, before, &core.Error{Command: "remote.editPortRecords", Code: core.CodeInvalidRequest, Message: "label"} + } + record := *edit.Port + record.Host = remotePortHost(record.Host) + records.Ports = slices.DeleteFunc(records.Ports, func(have core.RemotePortRecord) bool { + return have.Host == record.Host && have.Port == record.Port + }) + if !blankRemotePortRecord(record) { + records.Ports = append(records.Ports, record) + } + slices.SortFunc(records.Ports, func(x, y core.RemotePortRecord) int { + if x.Port != y.Port { + return int(x.Port) - int(y.Port) + } + return strings.Compare(x.Host, y.Host) + }) + case edit.RemovePort != nil: + host := remotePortHost(edit.RemovePort.Host) + records.Ports = slices.DeleteFunc(records.Ports, func(have core.RemotePortRecord) bool { + return have.Host == host && have.Port == edit.RemovePort.Port + }) + case edit.Rule != nil: + if refused(edit.Rule.Label) { + return false, nil, before, &core.Error{Command: "remote.editPortRecords", Code: core.CodeInvalidRequest, Message: "label"} + } + if at := slices.IndexFunc(records.Rules, func(have core.RemotePortRule) bool { return sameRemotePortRule(have, *edit.Rule) }); at >= 0 { + records.Rules[at].Label = edit.Rule.Label + } else { + records.Rules = append(records.Rules, *edit.Rule) + } + case edit.RemoveRule != nil: + records.Rules = slices.DeleteFunc(records.Rules, func(have core.RemotePortRule) bool { return sameRemotePortRule(have, *edit.RemoveRule) }) + } + was, _ := json.Marshal(before) + now, _ := json.Marshal(records) + if string(was) == string(now) { + return false, nil, records, nil + } + all[workspace] = records + text, _ := json.Marshal(all) + updated := string(text) + return true, &updated, records, nil +} + +func (k *remoteHostKernel) RestoreRemoteForwards(_ context.Context, document *string, session, workspace string) ([]core.RemoteRestoredForward, error) { + all, err := remoteTestRecords(document) + if err != nil { + return nil, err + } + k.mu.Lock() + defer k.mu.Unlock() + k.ports.records.restores++ + var restored []core.RemoteRestoredForward + for _, record := range all[workspace].Ports { + if record.ForwardTarget == "" { + continue + } + item := core.RemoteRestoredForward{Host: record.Host, Port: record.Port} + if k.ports.records.failRestore[record.Port] { + item.Err = &core.Error{Command: "remote.restoreForwards", Code: core.CodeForwardLimitReached, Message: "too many forwards"} + restored = append(restored, item) + continue + } + forward, created, err := k.ports.start(session, core.RemoteForwardTarget{Host: record.ForwardTarget, Port: record.Port, + LocalPort: record.LocalPort, AllowNonLoopback: record.ConfirmedTarget}) + if err != nil { + item.Err = err.(*core.Error) + } else { + item.Forward, item.Created = &forward, created + } + restored = append(restored, item) + } + return restored, nil +} + +// remoteTestRecordsFile is the port records document under the harness's preference directory. +func remoteTestRecordsFile(h *harness) string { + return filepath.Join(h.store.Dir(), filepath.FromSlash(remoteTestRecordsStorage.RelativePath)) +} + +// remoteTestRecordsOnDisk is the one workspace's records the document on disk holds. +func remoteTestRecordsOnDisk(t *testing.T, h *harness) core.RemotePortRecords { + t.Helper() + data, err := os.ReadFile(remoteTestRecordsFile(h)) + if errors.Is(err, fs.ErrNotExist) { + return core.RemotePortRecords{} + } + if err != nil { + t.Fatal(err) + } + all := map[string]core.RemotePortRecords{} + if err := json.Unmarshal(data, &all); err != nil || len(all) != 1 { + t.Fatalf("the document holds %d workspaces, want one", len(all)) + } + for _, records := range all { + return records + } + return core.RemotePortRecords{} +} + +// labelRemotePort types label into the label dialog of target and saves it. +func (h *harness) labelRemotePort(t *testing.T, p *project, target remotePortLabelTarget, label string) { + t.Helper() + ports := &p.remote.ports + h.app.editRemotePortLabel(p, target, surfaceContextMenu) + h.redraw() + if !ports.labelOpen || !h.shows(i18n.Shared(h.app.language(), "desktop.remote.ports.labelTitle")) { + t.Fatal("the label dialog did not open") + } + ports.labelField.SetText(label) + h.redraw() + h.click(center(h.popupHit(i18n.Shared(h.app.language(), "desktop.remote.ports.labelApply")))) + h.settle() +} + +// awaitRemotePortRecords waits until no reading or write of the records runs. +func (h *harness) awaitRemotePortRecords(p *project) { + h.await("the port records", func() bool { return !p.remote.ports.recordsBusy }) + h.settle() +} + +// The window remembers the labels, the local forwards left running and the rules of a workspace: +// they are written to the document under the preference directory as they change, and the +// workspace opened again lists them, starts the forward again and lists the rule with Start, which +// fills in Add Forwarding Rule. A label Core would refuse is refused in the dialog, an empty label +// forgets the row's, and the log names neither the host nor a label. +func TestRemotePortsRememberLabelsForwardsAndRulesWhenTheWorkspaceOpensAgain(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: "127.0.0.1", Port: 9090}) + ports := &p.remote.ports + web := remotePortKey{port: 8080} + 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(ports.forwards) == 1 && len(ports.busy) == 0 }) + h.settle() + + h.app.editRemotePortLabel(p, remotePortLabelTarget{key: &web}, surfaceContextMenu) + ports.labelField.SetText("web\tfrontend") + h.redraw() + h.click(center(h.popupHit(i18n.Shared(lang, "desktop.remote.ports.labelApply")))) + h.settle() + if !ports.labelInvalid || !ports.labelOpen || !h.shows(i18n.Shared(lang, "desktop.remote.ports.labelInvalid")) || + !rejected(logger, "remote_port_label", "invalid_label") { + t.Fatal("a label with a tab was not refused in the dialog") + } + h.click(center(h.popupHit(i18n.Shared(lang, "desktop.remote.ports.labelCancel")))) + h.settle() + h.labelRemotePort(t, p, remotePortLabelTarget{key: &web}, " Web UI ") + h.labelRemotePort(t, p, remotePortLabelTarget{key: &remotePortKey{port: 9090}}, "metrics") + + h.openRemotePortRule(t, p) + h.submitRemotePortRule(t, p, "15432", "5432") + rule := remotePortRuleOf(ports.rules()[0]) + h.labelRemotePort(t, p, remotePortLabelTarget{rule: &rule}, "Database") + h.awaitRemotePortRecords(p) + if !h.shows("Web UI") || !h.shows("Database") { + t.Fatal("the labels are not shown") + } + disk := remoteTestRecordsOnDisk(t, h) + if len(disk.Ports) != 2 || disk.Ports[0].Label != "Web UI" || disk.Ports[0].ForwardTarget == "" || disk.Ports[1].Label != "metrics" || + len(disk.Rules) != 1 || disk.Rules[0].Label != "Database" || disk.Rules[0].ListenPort != 15432 || disk.Rules[0].TargetPort != 5432 { + t.Fatalf("the document remembers %d rows and %d rules, want the labels, the forward and the rule", len(disk.Ports), len(disk.Rules)) + } + + h.rightClickAt(h.portRowControl("127.0.0.1:9090", "127.0.0.1:9090")) + h.click(center(h.popupHit(i18n.Shared(lang, "desktop.remote.ports.editLabel")))) + h.settle() + if ports.labelField.Text() != "metrics" { + t.Fatal("Edit Label does not start from the row's label") + } + ports.labelField.SetText("") + h.redraw() + h.click(center(h.popupHit(i18n.Shared(lang, "desktop.remote.ports.labelApply")))) + h.settle() + h.awaitRemotePortRecords(p) + if disk := remoteTestRecordsOnDisk(t, h); len(disk.Ports) != 1 || h.shows("metrics") { + t.Fatal("an empty label did not forget the row's label") + } + + h.app.closeProject() + h.awaitClosed(t) + h.app.openRemote(surfaceMenu) + h.settle() + h.settle() + p = h.openRemotePortsWindow(t, k, core.RemoteListeningPort{Address: "127.0.0.1", Port: 8080}) + ports = &p.remote.ports + h.awaitRemotePortRecords(p) + if ports.labels[web] != "Web UI" || !h.shows("Web UI") || !h.shows("Database") { + t.Fatal("the workspace opened again does not show the labels") + } + if !slices.ContainsFunc(ports.forwards, func(forward core.RemoteForward) bool { + return forward.Kind != core.RemoteForwardHost && forward.TargetPort == 8080 + }) { + t.Fatal("the forward left running did not start again") + } + if idle := ports.idleRules(); len(idle) != 1 || len(ports.rules()) != 0 || !h.shows(i18n.Shared(lang, "desktop.remote.ports.statusNotRunning")) { + t.Fatal("the rule is not listed as remembered, or started without the user") + } + started := len(k.ports.rules.hostStarts) + h.click(center(h.portRowControl("127.0.0.1:15432", i18n.Shared(lang, "desktop.remote.ports.ruleStart")))) + h.settle() + h.settle() + if ports.rule == nil || ports.rule.listen.Text() != "15432" || ports.rule.target.Text() != "localhost:5432" || len(k.ports.rules.hostStarts) != started { + t.Fatal("Start did not fill in Add Forwarding Rule with the rule, or started it at once") + } + draft := ports.rule + h.click(center(h.popupHit(i18n.Shared(lang, "desktop.remote.ports.ruleSubmit")))) + h.awaitRemotePortRule(p, draft) + h.awaitRemotePortRecords(p) + if len(ports.rules()) != 1 || len(ports.idleRules()) != 0 || len(remoteTestRecordsOnDisk(t, h).Rules) != 1 { + t.Fatal("the started rule is listed twice or remembered twice") + } + + actions := remoteActions(logger) + for _, action := range []string{"remote.ports.label", "remote.ports.ruleStart"} { + if !slices.Contains(actions, action) { + t.Fatalf("performed %q, want %s", actions, action) + } + } + if event := loggedAny(t, logger, remoteTestHost, "Web UI", "Database", "metrics", "15432"); event != "" { + t.Fatalf("logged the host, a label or a port: %s", event) + } +} + +// A forward that does not start again after a reconnect is shown failed with Core's reason and +// forgotten, and the window says how many did not start. +func TestRemotePortsShowTheForwardsThatDidNotStartAgain(t *testing.T) { + h, k, timers, logger := 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.awaitRemotePortRecords(p) + + k.set(func(k *remoteHostKernel) { + k.ports.records.failRestore = map[uint16]bool{8080: true} + k.once = &core.Error{Command: "remote.serverState", Code: core.CodeConnectionClosed, Message: "closed"} + }) + h.fireAfter(t, timers, remoteHeartbeatInterval) + h.fireReconnect(t, timers, r) + h.await("the new session's reading", func() bool { + return r.session == "session-2" && !r.beating && r.ports.listed && !p.tree.reading && !r.ports.recordsBusy + }) + h.settle() + notice := i18n.SharedFormat(lang, "desktop.remote.ports.restoreFailed", map[string]string{"count": "1"}) + failed := i18n.SharedFormat(lang, "desktop.remote.ports.statusFailed", map[string]string{"reason": "too many forwards"}) + if len(r.ports.forwards) != 0 || r.ports.notice != notice || !h.showsWrapped(notice) || !h.shows(failed) { + t.Fatal("the forward that did not start again is not shown failed") + } + if got := countFailures(logger, "remote_port_restore"); got != 1 { + t.Fatalf("remote_port_restore failed %d times, want once", got) + } + h.awaitRemotePortRecords(p) + if disk := remoteTestRecordsOnDisk(t, h); len(disk.Ports) != 0 { + t.Fatal("the forward that did not start is still remembered as running") + } +} + +// A document Core cannot decode is never overwritten: the window says so, keeps what the user +// changes in memory only, and leaves the file's bytes as they were. +func TestRemotePortsNeverOverwriteADamagedDocument(t *testing.T) { + h, k, _, logger := remoteWorkspaceHarness(t) + lang := h.app.language() + damaged := []byte("{not json") + if err := os.MkdirAll(filepath.Dir(remoteTestRecordsFile(h)), 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(remoteTestRecordsFile(h), damaged, 0o600); err != nil { + t.Fatal(err) + } + p := h.openRemotePortsWindow(t, k, core.RemoteListeningPort{Address: "127.0.0.1", Port: 8080}) + ports := &p.remote.ports + h.awaitRemotePortRecords(p) + notice := i18n.Shared(lang, "desktop.remote.ports.recordsDamaged") + if ports.notice != notice || !h.showsWrapped(notice) || countFailures(logger, "remote_port_records") != 1 { + t.Fatal("the damaged document is not reported") + } + h.labelRemotePort(t, p, remotePortLabelTarget{key: &remotePortKey{port: 8080}}, "web") + 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(ports.forwards) == 1 && len(ports.busy) == 0 }) + h.awaitRemotePortRecords(p) + if data, err := os.ReadFile(remoteTestRecordsFile(h)); err != nil || string(data) != string(damaged) || !h.shows("web") { + t.Fatal("the damaged document was overwritten, or the label was not kept in memory") + } +} diff --git a/desktop/internal/workbench/remote_port_rules.go b/desktop/internal/workbench/remote_port_rules.go index a64b529c5..ed535b926 100644 --- a/desktop/internal/workbench/remote_port_rules.go +++ b/desktop/internal/workbench/remote_port_rules.go @@ -25,8 +25,9 @@ import ( // by default, and every rule is confirmed before it starts; Core checks the preferences again. // // Rules belong to the session like every forward: Core stops them when it ends, and the window -// never starts them again after a reconnect. A rule never moves to another host port: a taken -// one is refused. The log names the outcome only, never an address, a URL or a process. +// never starts them again on its own. It remembers every rule that started (remote_port_records.go) +// and lists the ones not running with Start, which opens this dialog filled in with the rule, so +// every question is asked again. A rule never moves to another host port: a taken one is refused. The log names the outcome only, never an address, a URL or a process. // remotePortRuleKind is the direction of a rule the dialog adds. type remotePortRuleKind int @@ -109,16 +110,22 @@ func (ports *remotePorts) setRuleFailed(id uint64, reason string) { ports.ruleFailed[id] = reason } -// openRemotePortRule opens the Add Forwarding Rule dialog and reads whether the remote -// preferences allow reverse rules. -func (a *App) openRemotePortRule(p *project, surface actionSurface) { +// openRemotePortRule opens the Add Forwarding Rule dialog, filled in with the remembered rule from +// when it is not nil, and reads whether the remote preferences allow reverse rules. A remembered +// reverse rule falls back to an empty host rule when they do not. +func (a *App) openRemotePortRule(p *project, from *core.RemotePortRule, surface actionSurface) { r := p.remote if r == nil || r.closed || r.session == "" { // log-exempt: 非用户操作:没有会话,按钮此时不可用。 return } - a.performed("remote.ports.addRule", surface) draft := &remotePortRuleDraft{} + if from != nil { + a.performed("remote.ports.ruleStart", surface) + draft = remotePortRuleDraftOf(*from) + } else { + a.performed("remote.ports.addRule", surface) + } r.ports.rule, r.ports.ruleOpen = draft, true kernel, root := a.kernel, a.globalToolchainRoot() a.background(p, remotePortsTimeout, func(ctx context.Context) func(*App) { @@ -131,9 +138,12 @@ func (a *App) openRemotePortRule(p *project, surface actionSurface) { if err != nil { // A damaged preference document allows nothing; the settings page reports it. a.backgroundFailed("remote_port_rule_preferences", remoteLogError(err)) - return } - draft.reverseAllowed = allowed + draft.reverseAllowed = allowed && err == nil + if !draft.reverseAllowed && draft.kind == remotePortRuleReverse { + draft.kind = remotePortRuleHost + draft.target.SetText("") + } } }) } @@ -305,8 +315,9 @@ func (a *App) startRemotePortRule(p *project) { return } if err == nil { - // The rule runs even when the dialog was closed meanwhile. + // The rule runs even when the dialog was closed meanwhile, and is remembered. r.ports.putForward(forward) + a.rememberRemotePortRule(p, remotePortRuleRecord(kind, host, reverse)) } if r.ports.rule != draft { if err != nil { diff --git a/desktop/internal/workbench/remote_port_rules_test.go b/desktop/internal/workbench/remote_port_rules_test.go index 455c101e1..417d3aa1f 100644 --- a/desktop/internal/workbench/remote_port_rules_test.go +++ b/desktop/internal/workbench/remote_port_rules_test.go @@ -190,13 +190,20 @@ func TestRemotePortRulesForwardAHostPortToAnotherServer(t *testing.T) { } h.click(center(h.portRowControl("127.0.0.1:15432", i18n.Shared(lang, "desktop.remote.ports.stop")))) - h.await("the stopped rule", func() bool { return len(ports.rules()) == 0 && len(ports.ruleStopping) == 0 }) + h.await("the stopped rule", func() bool { return len(ports.rules()) == 0 && len(ports.ruleStopping) == 0 && !ports.recordsBusy }) h.settle() - if len(k.ports.forwards[p.remote.session]) != 0 || h.shows(i18n.Shared(lang, "desktop.remote.ports.rulesHeading")) { - t.Fatal("Stop left the rule running or listed") + if len(k.ports.forwards[p.remote.session]) != 0 || len(ports.idleRules()) != 1 || + !h.shows(i18n.Shared(lang, "desktop.remote.ports.statusNotRunning")) { + t.Fatal("Stop left the rule running, or the stopped rule is not listed as remembered") + } + h.click(center(h.portRowControl("127.0.0.1:15432", i18n.Shared(lang, "desktop.remote.ports.ruleForget")))) + h.await("the forgotten rule", func() bool { return !ports.recordsBusy }) + h.settle() + if len(ports.remembered) != 0 || h.shows(i18n.Shared(lang, "desktop.remote.ports.rulesHeading")) { + t.Fatal("Forget Rule left the rule listed") } actions := remoteActions(logger) - for _, action := range []string{"remote.ports.addRule", "remote.ports.ruleHost", "remote.ports.ruleConfirm", "remote.ports.stopRule"} { + for _, action := range []string{"remote.ports.addRule", "remote.ports.ruleHost", "remote.ports.ruleConfirm", "remote.ports.stopRule", "remote.ports.ruleForget"} { if !slices.Contains(actions, action) { t.Fatalf("performed %q, want %s", actions, action) } @@ -373,7 +380,8 @@ func TestRemotePortRulesReportWhyAHostPortWasRefused(t *testing.T) { } // Rules belong to the session: Stop All Forwards stops them with the forwards of this computer, and -// a lost session takes them with it without the window starting them again on the new one. +// a lost session takes them with it without the window starting them again on the new one; the +// window still lists them as remembered, each with Start. func TestRemotePortRulesEndWithTheSessionAndAreNotRestored(t *testing.T) { h, k, timers, _ := remoteWorkspaceHarness(t) lang := h.app.language() @@ -405,12 +413,16 @@ func TestRemotePortRulesEndWithTheSessionAndAreNotRestored(t *testing.T) { h.fireAfter(t, timers, remoteHeartbeatInterval) h.fireReconnect(t, timers, r) h.await("the new session's reading", func() bool { - return r.session == "session-2" && !r.beating && r.ports.listed && !p.tree.reading + return r.session == "session-2" && !r.beating && r.ports.listed && !p.tree.reading && !ports.recordsBusy }) h.settle() - if len(ports.rules()) != 0 || ports.rule != nil || ports.ruleOpen || h.shows(i18n.Shared(lang, "desktop.remote.ports.rulesHeading")) { + if len(ports.rules()) != 0 || ports.rule != nil || ports.ruleOpen { t.Fatal("the lost session's rule or dialog outlived it") } + if len(ports.idleRules()) != 2 || !h.shows(i18n.Shared(lang, "desktop.remote.ports.statusNotRunning")) || + !h.hasControl(i18n.Shared(lang, "desktop.remote.ports.ruleStart")) { + t.Fatal("the rules of the lost session are not listed as remembered with Start") + } if got := len(k.ports.rules.hostStarts); got != started { t.Fatalf("%d rules started after the reconnect, want none", got-started) } diff --git a/desktop/internal/workbench/remote_port_rules_view.go b/desktop/internal/workbench/remote_port_rules_view.go index d3f08fd8f..4385fe5be 100644 --- a/desktop/internal/workbench/remote_port_rules_view.go +++ b/desktop/internal/workbench/remote_port_rules_view.go @@ -21,8 +21,9 @@ const ( remotePortRulesConnectionsWidth = 150 ) -// remotePortRules declares the list of the session's host and reverse rules. -func (a *App) remotePortRules(c ui.C, p *project, rules []core.RemoteForward) { +// remotePortRules declares the list of the session's host and reverse rules, then the rules the +// window remembers that are not running. +func (a *App) remotePortRules(c ui.C, p *project, rules []core.RemoteForward, idle []core.RemotePortRule) { language := a.language() k := c.Part("rules") ui.Row(k.Part("heading")).FillWidth().Height(remotePortsRowHeight).Shrink(0).Items(ui.Center).Gap(4).PadX(shellContentPad).Children(func() { @@ -43,6 +44,7 @@ func (a *App) remotePortRules(c ui.C, p *project, rules []core.RemoteForward) { }) } column("listen", i18n.Shared(language, "desktop.remote.ports.ruleColumnListen"), remotePortRulesListenWidth) + column("label", i18n.Shared(language, "desktop.remote.ports.columnLabel"), remotePortsLabelWidth) column("target", i18n.Shared(language, "desktop.remote.ports.ruleColumnTarget"), 0) column("connections", i18n.Shared(language, "desktop.remote.ports.ruleColumnConnections"), remotePortRulesConnectionsWidth) column("status", i18n.Shared(language, "desktop.remote.ports.columnStatus"), remotePortsStatusWidth) @@ -52,6 +54,87 @@ func (a *App) remotePortRules(c ui.C, p *project, rules []core.RemoteForward) { for _, rule := range rules { a.remotePortRuleRow(c.Key("rule:"+strconv.FormatUint(rule.ID, 10)), p, rule) } + for _, rule := range idle { + a.remotePortIdleRuleRow(c.Key("idle:"+remotePortIdleKey(rule)), p, rule) + } +} + +// remotePortIdleKey names a remembered rule among the list's rows. +func remotePortIdleKey(rule core.RemotePortRule) string { + return string(rule.Kind) + ":" + strconv.Itoa(int(rule.ListenPort)) + ":" + rule.TargetHost + ":" + + strconv.Itoa(int(rule.TargetPort)) + ":" + strconv.Itoa(int(rule.LocalPort)) +} + +// remotePortIdleListen is the Host Listens On column of a remembered rule: the host's loopback +// address with its port, as a running rule lists it (a remembered rule never listens on every +// interface), or that the host chooses a port. +func remotePortIdleListen(language i18n.Language, rule core.RemotePortRule) string { + if rule.ListenPort == 0 { + return i18n.Shared(language, "desktop.remote.ports.ruleListenAny") + } + return net.JoinHostPort("127.0.0.1", strconv.Itoa(int(rule.ListenPort))) +} + +// remotePortIdleTarget is the Forwards To column of a remembered rule. +func remotePortIdleTarget(language i18n.Language, rule core.RemotePortRule) string { + if rule.Kind == core.RemoteForwardReverse { + return i18n.SharedFormat(language, "desktop.remote.ports.ruleThisComputer", + map[string]string{"address": net.JoinHostPort("127.0.0.1", strconv.Itoa(int(rule.LocalPort)))}) + } + return net.JoinHostPort(rule.TargetHost, strconv.Itoa(int(rule.TargetPort))) +} + +// remotePortIdleRuleRow declares a remembered rule that is not running, its Start and Forget +// buttons and its context menu. Start opens Add Forwarding Rule filled in with it, so the rule +// starts only once the user adds it there. +func (a *App) remotePortIdleRuleRow(c ui.C, p *project, rule core.RemotePortRule) { + r := p.remote + language := a.language() + listen := remotePortIdleListen(language, rule) + status := i18n.Shared(language, "desktop.remote.ports.statusNotRunning") + unavailable := r.session == "" || r.ports.stoppingAll + icon := icons.Server + if rule.Kind == core.RemoteForwardReverse { + icon = icons.Monitor + } + 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), listen, gfx.HitOptions{Value: status, SkipFocus: true}) + line.Children(func() { + ui.Row(c.Part("listen")).Width(remotePortRulesListenWidth).Shrink(0).Items(ui.Center).Gap(6).Children(func() { + ui.Icon(c.Part("kind"), icon).Size(14, 14).Shrink(0).Color(a.colors.Subtle) + ui.Text(c.Part("listen-text"), listen).Color(a.colors.Subtle).Ellipsis() + }) + a.remotePortsLabelCell(c, rule.Label) + ui.Row(c.Part("target")).Grow(1).Shrink(1).MinWidth(0).Items(ui.Center).Children(func() { + ui.Text(c.Part("target-text"), remotePortIdleTarget(language, rule)).Color(a.colors.Subtle).Ellipsis() + }) + ui.Row(c.Part("connections")).Width(remotePortRulesConnectionsWidth).Shrink(0) + ui.Row(c.Part("status")).Width(remotePortsStatusWidth).Shrink(0).Items(ui.Center).Children(func() { + ui.Text(c.Part("status-text"), status).Color(a.colors.Subtle).Ellipsis() + }) + ui.Row(c.Part("actions")).Width(remotePortsActionWidth).Shrink(0).Items(ui.Center).Justify(ui.End).Gap(2).Children(func() { + if _, clicked := a.toolIconButton(c.Part("start"), i18n.Shared(language, "desktop.remote.ports.ruleStart"), icons.Play, false, unavailable); clicked { + c.After(func() { a.startRememberedRule(p, rule, surfaceButton) }) + } + if _, clicked := a.toolIconButton(c.Part("forget"), i18n.Shared(language, "desktop.remote.ports.ruleForget"), icons.Trash2, false, false); clicked { + c.After(func() { a.forgetRemotePortRule(p, rule, surfaceButton) }) + } + }) + }) + ui.ContextMenu(c.Part("menu"), line, func(menu *ui.MenuItems) { + menu.WidthRange(180, 280) + if menu.Item(i18n.Shared(language, "desktop.remote.ports.ruleStart")).Icon(icons.Play).Disabled(unavailable).Clicked() { + c.After(func() { a.startRememberedRule(p, rule, surfaceContextMenu) }) + } + if menu.Item(i18n.Shared(language, "desktop.remote.ports.editLabel")).Icon(icons.Tag).Clicked() { + c.After(func() { a.editRemotePortLabel(p, remotePortLabelTarget{rule: &rule}, surfaceContextMenu) }) + } + menu.Separator() + if menu.Item(i18n.Shared(language, "desktop.remote.ports.ruleForget")).Icon(icons.Trash2).Clicked() { + c.After(func() { a.forgetRemotePortRule(p, rule, surfaceContextMenu) }) + } + }) } // remotePortRuleStatus is the Status column of rule and its colour. @@ -104,6 +187,7 @@ func (a *App) remotePortRuleRow(c ui.C, p *project, rule core.RemoteForward) { ui.Icon(c.Part("kind"), icon).Size(14, 14).Shrink(0).Color(color) ui.Text(c.Part("listen-text"), listen).Color(color).Ellipsis() }) + a.remotePortsLabelCell(c, ports.ruleLabel(rule)) ui.Row(c.Part("target")).Grow(1).Shrink(1).MinWidth(0).Items(ui.Center).Children(func() { ui.Text(c.Part("target-text"), remotePortRuleTarget(language, rule)).Color(a.colors.Text).Ellipsis() }) @@ -121,6 +205,16 @@ func (a *App) remotePortRuleRow(c ui.C, p *project, rule core.RemoteForward) { }) ui.ContextMenu(c.Part("menu"), line, func(menu *ui.MenuItems) { menu.WidthRange(180, 280) + record := remotePortRuleOf(rule) + if menu.Item(i18n.Shared(language, "desktop.remote.ports.editLabel")).Icon(icons.Tag).Clicked() { + c.After(func() { a.editRemotePortLabel(p, remotePortLabelTarget{rule: &record}, surfaceContextMenu) }) + } + if _, remembered := ports.rememberedRule(record); remembered { + if menu.Item(i18n.Shared(language, "desktop.remote.ports.ruleForget")).Icon(icons.Trash2).Clicked() { + c.After(func() { a.forgetRemotePortRule(p, record, surfaceContextMenu) }) + } + } + menu.Separator() if menu.Item(i18n.Shared(language, "desktop.remote.ports.stop")).Icon(icons.Square).Disabled(busy).Clicked() { c.After(func() { a.stopRemotePortRule(p, rule.ID, surfaceContextMenu) }) } @@ -184,7 +278,8 @@ func (a *App) remotePortRuleDialog(c ui.C, p *project) { func (a *App) remotePortRuleFields(c ui.C, p *project, draft *remotePortRuleDraft, unavailable bool) { language := a.language() kinds := []remotePortRuleKind{remotePortRuleHost} - if draft.reverseAllowed { + // A remembered reverse rule is shown as one while the preferences are read. + if draft.reverseAllowed || draft.kind == remotePortRuleReverse { kinds = append(kinds, remotePortRuleReverse) } kindLabel := func(kind remotePortRuleKind) string { diff --git a/desktop/internal/workbench/remote_ports.go b/desktop/internal/workbench/remote_ports.go index eb9b6aa2c..c829b7040 100644 --- a/desktop/internal/workbench/remote_ports.go +++ b/desktop/internal/workbench/remote_ports.go @@ -24,7 +24,8 @@ import ( // 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. +// unforwarded until the next session attaches and the forwards left running start again +// (remote_port_records.go, which also keeps the ports added, labels and local ports across reopens). // // 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 @@ -233,10 +234,31 @@ type remotePorts struct { // of one failed, by forward id. ruleStopping map[uint64]bool ruleFailed map[uint64]string + // labels are the names the user gave rows, and running the local forwards the user started and + // did not stop, kept across sessions and in the port records (remote_port_records.go); + // remembered are the rules the user started, which never start on their own. + labels map[remotePortKey]string + running map[remotePortKey]remotePortRunning + remembered []core.RemotePortRule + // written is what Core last reported of the port records, nil until they were read or when + // they cannot be kept. recordsBusy is set while a reading or write runs, recordsAttach once a + // session attached and the forwards wait to be restored, and recordsRevision counts the + // changes of what the window remembers. + written *core.RemotePortRecords + recordsBusy bool + recordsAttach bool + recordsRevision uint64 + // label is the row or rule whose label the user is typing, nil while none is; labelField is + // the label typed, and labelInvalid is set when Core would not keep it. + label *remotePortLabelTarget + labelOpen bool + labelField ui.Field + labelInvalid bool } // 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. +// listing it read. What the window remembers stays: the ports the user added, the labels, local +// ports and remembered rules, and the forwards left running, which the next session restores. func (ports *remotePorts) reset() { ports.stopReading() ports.listening, ports.listed, ports.readFailed = nil, false, "" @@ -533,11 +555,16 @@ func (a *App) forwardStarted(p *project, session string, key remotePortKey, host switch code := remotePortsCode(err); { case err == nil: ports.putForward(forward) + ports.setRunning(forwardKey(forward), &remotePortRunning{host: forward.TargetHost, confirmed: !forward.LoopbackTarget}) + a.remotePortsChanged(p) + return + case code == core.CodeConnectionClosed: + // The forward that ran before stays remembered, so the next session starts it again. + a.loseRemote(p, session, err) + return 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", @@ -549,6 +576,9 @@ func (a *App) forwardStarted(p *project, session string, key remotePortKey, host a.operationFailed("remote_port_forward", remoteLogError(err)) ports.setFailed(key, remotePortsReason(err)) } + // A forward moved to another local port stopped before its new start failed. + ports.setRunning(key, nil) + a.remotePortsChanged(p) } // chooseRemoteLocalPort asks for the local port of row key, starting from the one it uses now. @@ -593,6 +623,7 @@ func (a *App) applyRemoteLocalPort(p *project) { ports.localPorts = map[remotePortKey]uint16{} } ports.localPorts[key] = port + a.remotePortsChanged(p) switch row, ok := ports.row(key); { case !ok: case row.forward == nil: @@ -680,7 +711,11 @@ func (a *App) stopRemotePort(p *project, key remotePortKey, id uint64, surface a case err == nil: // A forward Core no longer knows has stopped as well. ports.dropForward(id) + ports.setRunning(key, nil) + a.remotePortsChanged(p) case remoteConnectionClosed(err): + // The user stopped it: the next session does not start it again. + ports.setRunning(key, nil) a.loseRemote(p, session, err) default: a.operationFailed("remote_port_stop", remoteLogError(err)) @@ -702,9 +737,11 @@ func (a *App) stopAllRemotePorts(p *project, surface actionSurface) { ports := &r.ports ports.stoppingAll = true ids := make([]uint64, len(ports.forwards)) + var keys []remotePortKey for i, forward := range ports.forwards { ids[i] = forward.ID if forward.IsLocal() { + keys = append(keys, forwardKey(forward)) ports.setBusy(forwardKey(forward), remotePortStopping) } else { ports.setRuleStopping(forward.ID, true) @@ -729,6 +766,15 @@ func (a *App) stopAllRemotePorts(p *project, surface actionSurface) { clear(ports.busy) clear(ports.ruleStopping) clear(ports.ruleFailed) + // The user stopped them: only a forward the listing still shows stays remembered. + for _, key := range keys { + if listErr != nil || !slices.ContainsFunc(forwards, func(forward core.RemoteForward) bool { + return forward.IsLocal() && forwardKey(forward) == key + }) { + ports.setRunning(key, nil) + } + } + a.remotePortsChanged(p) err := errors.Join(stopErr, listErr) switch { case err != nil && (remoteConnectionClosed(stopErr) || remoteConnectionClosed(listErr)): @@ -818,6 +864,7 @@ func (a *App) addRemoteAddress(p *project, address core.RemoteForwardAddress, su 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}) + a.remotePortsChanged(p) row, _ := ports.row(key) if row.forward != nil { // log-exempt: 非用户操作:这个端口已在转发,添加只让它出现在列表里,或换成新输入的网址。 @@ -826,12 +873,15 @@ func (a *App) addRemoteAddress(p *project, address core.RemoteForwardAddress, su a.forwardRemotePort(p, key, row.target(), false, surface) } -// removeRemotePort removes a port the user added from the window. +// removeRemotePort removes a port the user added from the window, with its label and local port. 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 }) + delete(ports.labels, key) + delete(ports.localPorts, key) ports.setFailed(key, "") + a.remotePortsChanged(p) } // remotePortAddress is the local address of forward, as host:port. diff --git a/desktop/internal/workbench/remote_ports_test.go b/desktop/internal/workbench/remote_ports_test.go index 116dd9def..b6de1685c 100644 --- a/desktop/internal/workbench/remote_ports_test.go +++ b/desktop/internal/workbench/remote_ports_test.go @@ -37,6 +37,8 @@ type remoteHostPorts struct { stops []uint64 // rules are the host side of the forwarding rules (remote_port_rules_test.go). rules remoteHostRules + // records are Core's port records (remote_port_records_test.go). + records remoteHostRecords } func (k *remoteHostKernel) RemoteListeningPorts(context.Context, string) ([]core.RemoteListeningPort, error) { @@ -58,7 +60,12 @@ func (k *remoteHostKernel) RemoteForwards(_ context.Context, session string) ([] 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 + return k.ports.start(session, target) +} + +// start starts a forward of session to target as remote.startForward does; the caller holds the +// kernel's lock. +func (p *remoteHostPorts) start(session string, target core.RemoteForwardTarget) (core.RemoteForward, bool, error) { p.starts = append(p.starts, target) host, loopback := target.Host, target.Host == "localhost" if ip, err := netip.ParseAddr(host); err == nil { @@ -618,16 +625,24 @@ func TestRemotePortsStopsAllAndReportsTheLimit(t *testing.T) { } } -// 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) +// A lost session takes its forwards with it, and the window has Core start again on the new +// session the forwards the user left running, as VS Code restores its forwarded ports; a forward +// the user stopped stays stopped. +func TestRemotePortsStartTheForwardsLeftRunningAgainAfterAReconnect(t *testing.T) { + h, k, timers, logger := remoteWorkspaceHarness(t) lang := h.app.language() - p := h.openRemotePortsWindow(t, k, core.RemoteListeningPort{Address: "127.0.0.1", Port: 8080}) + p := h.openRemotePortsWindow(t, k, core.RemoteListeningPort{Address: "127.0.0.1", Port: 8080}, + core.RemoteListeningPort{Address: "127.0.0.1", Port: 9090}) 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 }) + for _, row := range []string{"127.0.0.1:8080", "127.0.0.1:9090"} { + h.click(center(h.portRowControl(row, i18n.Shared(lang, "desktop.remote.ports.forward")))) + h.await("the forward", func() bool { return len(r.ports.busy) == 0 }) + h.settle() + } + h.click(center(h.portRowControl("127.0.0.1:9090", i18n.Shared(lang, "desktop.remote.ports.stop")))) + h.await("the stopped forward", func() bool { return len(r.ports.forwards) == 1 && len(r.ports.busy) == 0 && !r.ports.recordsBusy }) h.settle() + lost := r.session k.set(func(k *remoteHostKernel) { k.once = &core.Error{Command: "remote.serverState", Code: core.CodeConnectionClosed, Message: "closed"} @@ -635,18 +650,29 @@ func TestRemotePortsForgetTheForwardsOfALostSession(t *testing.T) { h.fireAfter(t, timers, remoteHeartbeatInterval) h.fireReconnect(t, timers, r) h.await("the new session's reading", func() bool { - return r.session == "session-2" && !r.beating && r.ports.listed && !p.tree.reading + return r.session == "session-2" && !r.beating && r.ports.listed && !p.tree.reading && !r.ports.recordsBusy }) 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") + k.mu.Lock() + restores, again := k.ports.records.restores, slices.Clone(k.ports.forwards["session-2"]) + k.mu.Unlock() + if restores != 2 || len(again) != 1 || again[0].TargetPort != 8080 { + t.Fatalf("restored %d times with %d forwards: the forward left running did not start again alone", restores, len(again)) + } + if len(r.ports.forwards) != 1 || r.ports.forwards[0].ID != again[0].ID || slices.ContainsFunc(r.ports.forwards, func(forward core.RemoteForward) bool { + return slices.ContainsFunc(k.ports.forwards[lost], func(old core.RemoteForward) bool { return old.ID == forward.ID }) + }) { + t.Fatal("the window does not show the new session's forward alone") } - if !h.shows(i18n.Shared(lang, "desktop.remote.ports.statusNotForwarded")) { - t.Fatal("the port is not shown unforwarded") + if !h.shows(i18n.Shared(lang, "desktop.remote.ports.statusNotForwarded")) || !h.hasControl(i18n.Shared(lang, "desktop.remote.ports.statusLabel")) { + t.Fatal("the stopped port is not shown unforwarded, or the restored one forwarded") } if got := timers.liveAfter(remotePortsInterval); got != 1 { t.Fatalf("%d readings of the window pending, want the new session's one", got) } + if event := loggedAny(t, logger, remoteTestHost, "8080", "9090"); event != "" { + t.Fatalf("logged the host or a port: %s", event) + } } // The window reads the host while it is open, and stops once it is hidden until it is shown again. diff --git a/desktop/internal/workbench/remote_ports_view.go b/desktop/internal/workbench/remote_ports_view.go index f6d61f6d6..db3989b9a 100644 --- a/desktop/internal/workbench/remote_ports_view.go +++ b/desktop/internal/workbench/remote_ports_view.go @@ -20,6 +20,7 @@ const ( remotePortsRowHeight = 26 // The widths of the list's fixed columns; the Process column takes the rest. remotePortsRemoteWidth = 200 + remotePortsLabelWidth = 120 remotePortsLocalWidth = 150 remotePortsSourceWidth = 90 remotePortsStatusWidth = 170 @@ -37,7 +38,7 @@ func (a *App) remotePortsActions(c ui.C, p *project) { 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")) if _, clicked := a.toolIconButton(c.Part("ports-rule-add"), i18n.Shared(language, "desktop.remote.ports.ruleAdd"), icons.Plus, false, r.session == ""); clicked { - c.After(func() { a.openRemotePortRule(p, surfaceToolbar) }) + c.After(func() { a.openRemotePortRule(p, nil, surfaceToolbar) }) } 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 { @@ -46,7 +47,7 @@ func (a *App) remotePortsActions(c ui.C, p *project) { } // remotePortsView declares the body of the Ports window: the field a port is typed into, the -// window's message, the list of ports and the forwarding rules. +// window's message, the list of ports and the forwarding rules, running or remembered. func (a *App) remotePortsView(c ui.C, p *project) { r := p.remote if r == nil { @@ -77,12 +78,12 @@ func (a *App) remotePortsView(c ui.C, p *project) { a.remotePortsLine(c.Part("read-failed"), i18n.SharedFormat(language, "desktop.remote.ports.readFailed", map[string]string{"reason": ports.readFailed}), a.theme.Danger) } - rows, rules := ports.rows(), ports.rules() + rows, rules, idle := ports.rows(), ports.rules(), ports.idleRules() empty := i18n.Shared(language, "desktop.remote.ports.empty") if !ports.listed && ports.readFailed == "" { empty = i18n.Shared(language, "desktop.remote.ports.loading") } - if len(rows) == 0 && len(rules) == 0 { + if len(rows) == 0 && len(rules) == 0 && len(idle) == 0 { a.panelMessage(c, empty, a.colors.Subtle) return } @@ -96,13 +97,14 @@ func (a *App) remotePortsView(c ui.C, p *project) { for _, row := range rows { a.remotePortsRow(c.Key("port:"+row.key.host+":"+strconv.Itoa(int(row.key.port))), p, row) } - if len(rules) > 0 { - a.remotePortRules(c, p, rules) + if len(rules) > 0 || len(idle) > 0 { + a.remotePortRules(c, p, rules, idle) } }) }) a.remotePortsConfirm(c, p) a.remotePortsLocal(c, p) + a.remotePortsLabel(c, p) a.remotePortRuleDialog(c, p) } @@ -152,6 +154,7 @@ func (a *App) remotePortsHeader(c ui.C) { }) } column("remote", i18n.Shared(language, "desktop.remote.ports.columnRemote"), remotePortsRemoteWidth) + column("label", i18n.Shared(language, "desktop.remote.ports.columnLabel"), remotePortsLabelWidth) 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) @@ -275,6 +278,7 @@ func (a *App) remotePortsRow(c ui.C, p *project, row remotePortRow) { remoteCell.Children(func() { ui.Text(c.Part("remote-text"), remote).Color(a.colors.Text).Ellipsis() }) + a.remotePortsLabelCell(c, ports.labels[row.key]) localCell := ui.Row(c.Part("local")).Width(remotePortsLocalWidth).Shrink(0).Items(ui.Center) color := a.colors.Text if localTip != "" { @@ -325,8 +329,12 @@ func (a *App) remotePortsRow(c ui.C, p *project, row remotePortRow) { c.After(func() { a.chooseRemoteLocalPort(p, row.key, surfaceContextMenu) }) } } + menu.Separator() + if menu.Item(i18n.Shared(language, "desktop.remote.ports.editLabel")).Icon(icons.Tag).Clicked() { + key := row.key + c.After(func() { a.editRemotePortLabel(p, remotePortLabelTarget{key: &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) }) } @@ -424,6 +432,53 @@ func (a *App) remotePortsLocal(c ui.C, p *project) { } } +// remotePortsLabelFits is the most characters of the Label column that its width shows whole. +const remotePortsLabelFits = 14 + +// remotePortsLabelCell declares the Label column of a row or a rule: the name the user gave it. +func (a *App) remotePortsLabelCell(c ui.C, label string) { + cell := ui.Row(c.Part("label")).Width(remotePortsLabelWidth).Shrink(0).Items(ui.Center) + if utf8.RuneCountInString(label) > remotePortsLabelFits { + // The cell takes an identity for its tooltip, which gives the label the column cuts off. + cell = cell.HitWith(ui.ID(c.Part("label")), label, gfx.HitOptions{Role: gfx.RoleStatus, SkipFocus: true}).Tooltip(label) + } + cell.Children(func() { + ui.Text(c.Part("label-text"), label).Color(a.colors.Text).Ellipsis() + }) +} + +// remotePortsLabel declares the dialog the label of a row or a rule is typed in. Closing it +// changes nothing. +func (a *App) remotePortsLabel(c ui.C, p *project) { + ports := &p.remote.ports + if ports.label == nil { + ports.labelOpen = false + return + } + language := a.language() + closed := ui.Modal(c.Part("ports-label"), &ports.labelOpen, i18n.Shared(language, "desktop.remote.ports.labelTitle"), func() { + ui.Paragraph(c, i18n.Shared(language, "desktop.remote.ports.labelBody"), 5).Color(a.colors.Text) + submitted := ui.TextField(c.Part("ports-label-field"), &ports.labelField, i18n.Shared(language, "desktop.remote.ports.labelField"), + i18n.Shared(language, "desktop.remote.ports.labelField")).FillWidth().Submitted() + if ports.labelInvalid { + ui.Text(c, i18n.Shared(language, "desktop.remote.ports.labelInvalid")).FontSize(12).Color(a.theme.Danger) + } + if submitted { + c.After(func() { a.applyRemotePortLabel(p) }) + } + }, func() { + if ui.Button(c, i18n.Shared(language, "desktop.remote.ports.labelCancel")).Outline().Clicked() { + ports.labelOpen = false + } + if ui.Button(c, i18n.Shared(language, "desktop.remote.ports.labelApply")).Clicked() { + c.After(func() { a.applyRemotePortLabel(p) }) + } + }) + if closed || !ports.labelOpen { + ports.label, ports.labelOpen, ports.labelInvalid = 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) { diff --git a/desktop/internal/workbench/remote_ports_visual_test.go b/desktop/internal/workbench/remote_ports_visual_test.go index 49e2732ad..c77c86c5d 100644 --- a/desktop/internal/workbench/remote_ports_visual_test.go +++ b/desktop/internal/workbench/remote_ports_visual_test.go @@ -151,7 +151,7 @@ func TestVisualRemotePorts(t *testing.T) { kernel.set(func(k *remoteHostKernel) { k.ports.rules.allowReverse = true }) addRule := func(kind remotePortRuleKind, listen, target string, all bool) { t.Helper() - h.app.openRemotePortRule(p, surfaceToolbar) + h.app.openRemotePortRule(p, nil, surfaceToolbar) h.settleChain() draft := ports.rule draft.kind, draft.allInterfaces = kind, all @@ -177,7 +177,7 @@ func TestVisualRemotePorts(t *testing.T) { } shot("rules") - h.app.openRemotePortRule(p, surfaceToolbar) + h.app.openRemotePortRule(p, nil, surfaceToolbar) h.settleChain() draft := ports.rule draft.allInterfaces = true @@ -187,6 +187,41 @@ func TestVisualRemotePorts(t *testing.T) { h.app.submitRemotePortRule(p, surfaceButton) h.await("the question", func() bool { return !draft.starting && draft.confirm == remotePortRuleConfirmAll }) shot("rule-confirm") + ports.rule, ports.ruleOpen = nil, false + h.settleChain() + + // The user names rows and rules; the window remembers them with the forwards left + // running and the rules, and lists them again when the workspace opens again. + label := func(target remotePortLabelTarget, text string, scene string) { + t.Helper() + h.app.editRemotePortLabel(p, target, surfaceContextMenu) + h.settleChain() + ports.labelField.SetText(text) + if scene != "" { + shot(scene) + } + h.app.applyRemotePortLabel(p) + h.await("the port records", func() bool { return !ports.recordsBusy }) + } + label(remotePortLabelTarget{key: &remotePortKey{port: 8080}}, "Web UI", "label") + label(remotePortLabelTarget{key: &remotePortKey{port: 5432}}, "Database", "") + tunnel := remotePortRuleOf(ports.rules()[0]) + label(remotePortLabelTarget{rule: &tunnel}, "DB tunnel", "") + shot("labels") + + h.app.closeProject() + h.awaitClosed(t) + h.app.openRemote(surfaceMenu) + h.settleChain() + p = h.openRemoteTestProject(t) + h.app.openToolWindow(itemPorts) + h.redraw() + ports = &p.remote.ports + h.await("the remembered forwards", func() bool { return ports.listed && !ports.recordsBusy && len(ports.forwards) == 2 }) + if len(ports.idleRules()) != 3 { + t.Fatalf("%d remembered rules, want 3", len(ports.idleRules())) + } + shot("remembered") }) } } diff --git a/desktop/internal/workbench/remote_workspace.go b/desktop/internal/workbench/remote_workspace.go index 17e477595..7be4fa431 100644 --- a/desktop/internal/workbench/remote_workspace.go +++ b/desktop/internal/workbench/remote_workspace.go @@ -317,6 +317,9 @@ func (a *App) attachRemote(p *project, session core.RemoteSession) { r.watchWait = remoteWatchReady a.startRemoteWatch(p) a.resumeRemoteGit(p) + // The Ports window reads its records and restores the forwards left running. + r.ports.recordsAttach = true + a.syncRemotePorts(p) } // beatRemote asks the server of the workspace's session what still runs, and schedules the next diff --git a/docs/assets/remote-ports/README.md b/docs/assets/remote-ports/README.md index 8d3187b1e..0a0a408b8 100644 --- a/docs/assets/remote-ports/README.md +++ b/docs/assets/remote-ports/README.md @@ -5,13 +5,16 @@ - 打开工作区和窗口都不会自动转发任何端口:8080 和手动添加的网址是测试里点了“转发”之后才转发的; - 远端端口列带上主机监听的 IP 地址:同一端口在多个地址监听时显示第一个地址和其余数量(`0.0.0.0:8080 +1`),悬停提示列出全部地址; - 顶部输入框接受端口、主机:端口或网址;手动添加的 `http://localhost:5173/app` 按输入的样子显示,转发到主机上提供该端口的回环地址,“在浏览器中打开”把主机地址换成本机地址、保留路径; -- 列表列出远端端口、本机地址、进程、来源(监听发现、手动添加)和状态;8080 的本机端口被占用,改用空闲端口 40001,本机地址用警告色显示;状态栏显示已转发的数量; +- 列表列出远端端口、标签、本机地址、进程、来源(监听发现、手动添加)和状态;8080 的本机端口被占用,改用空闲端口 40001,本机地址用警告色显示;状态栏显示已转发的数量; - 已转发行的右键菜单:在浏览器中打开、复制本机地址、更改本机端口…、停止转发; - 转发 `10.0.0.5:9000` 这种主机回环地址以外的目标前先询问(S28); - “更改本机端口…”打开的对话框:说明转发到本机回环地址的哪个端口,端口被占用时改用空闲端口并在行里注明; - “转发规则”一节:主机 `127.0.0.1:15432` 转到另一台服务器 `db.internal:5432`;`0.0.0.0:9200` 监听主机的全部网卡,监听地址用警告色;反向转发把主机回环地址上由主机选择的端口转回本机 `127.0.0.1:3000`(测试里已在设置中允许反向转发); - 标题栏“+”打开的“添加转发规则”对话框:方向、主机端口、目标各有标题,勾选“监听主机的全部网卡”时显示警告; -- 添加监听全部网卡的规则前的询问:每次都问,不记住。 +- 添加监听全部网卡的规则前的询问:每次都问,不记住; +- 右键“编辑标签…”打开的对话框:标签只记在本机、只属于这个工作区,留空即删除; +- 标签列:端口行和转发规则都能起名(Web UI、Database、DB tunnel); +- 关闭工作区再打开后:标签还在,之前没停的两个本机转发自动重新转发(本机端口由测试替换的内核重新分配),三条转发规则只列出、不自动启动,状态是“未运行”,行尾有“启动”和“忘记”;原来监听全部网卡的 9200 规则按回环地址列出,全部网卡每次都要重新确认(S27)。 截图不代表 macOS/Windows 原生窗口验收,也不代表真实 SSH 主机上的整机验收。 @@ -24,3 +27,6 @@ | 转发规则列表 | [浅色英文](remote-ports-rules-light-en-US.png) | [深色中文](remote-ports-rules-dark-zh-CN.png) | | 添加转发规则 | [浅色英文](remote-ports-rule-light-en-US.png) | [深色中文](remote-ports-rule-dark-zh-CN.png) | | 监听全部网卡前询问 | [浅色英文](remote-ports-rule-confirm-light-en-US.png) | [深色中文](remote-ports-rule-confirm-dark-zh-CN.png) | +| 编辑标签 | [浅色英文](remote-ports-label-light-en-US.png) | [深色中文](remote-ports-label-dark-zh-CN.png) | +| 标签列 | [浅色英文](remote-ports-labels-light-en-US.png) | [深色中文](remote-ports-labels-dark-zh-CN.png) | +| 重新打开后恢复的转发和记住的规则 | [浅色英文](remote-ports-remembered-light-en-US.png) | [深色中文](remote-ports-remembered-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 index b5d47ad8c..4b7c03b9f 100644 Binary files a/docs/assets/remote-ports/remote-ports-confirm-dark-zh-CN.png 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 index 78dac5f0b..a058f27b4 100644 Binary files a/docs/assets/remote-ports/remote-ports-confirm-light-en-US.png and b/docs/assets/remote-ports/remote-ports-confirm-light-en-US.png differ diff --git a/docs/assets/remote-ports/remote-ports-label-dark-zh-CN.png b/docs/assets/remote-ports/remote-ports-label-dark-zh-CN.png new file mode 100644 index 000000000..19c0fab87 Binary files /dev/null and b/docs/assets/remote-ports/remote-ports-label-dark-zh-CN.png differ diff --git a/docs/assets/remote-ports/remote-ports-label-light-en-US.png b/docs/assets/remote-ports/remote-ports-label-light-en-US.png new file mode 100644 index 000000000..728c7dc9b Binary files /dev/null and b/docs/assets/remote-ports/remote-ports-label-light-en-US.png differ diff --git a/docs/assets/remote-ports/remote-ports-labels-dark-zh-CN.png b/docs/assets/remote-ports/remote-ports-labels-dark-zh-CN.png new file mode 100644 index 000000000..b216339a2 Binary files /dev/null and b/docs/assets/remote-ports/remote-ports-labels-dark-zh-CN.png differ diff --git a/docs/assets/remote-ports/remote-ports-labels-light-en-US.png b/docs/assets/remote-ports/remote-ports-labels-light-en-US.png new file mode 100644 index 000000000..9235fb1e2 Binary files /dev/null and b/docs/assets/remote-ports/remote-ports-labels-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 index 580538f41..08512f298 100644 Binary files a/docs/assets/remote-ports/remote-ports-list-dark-zh-CN.png 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 index bfc2af168..01a1e4dd0 100644 Binary files a/docs/assets/remote-ports/remote-ports-list-light-en-US.png 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 index 0027a3d1b..31dc34e24 100644 Binary files a/docs/assets/remote-ports/remote-ports-local-dark-zh-CN.png 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 index 9ff8499c2..ee98755ee 100644 Binary files a/docs/assets/remote-ports/remote-ports-local-light-en-US.png 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 index 2ad1c30ef..d904e59d0 100644 Binary files a/docs/assets/remote-ports/remote-ports-menu-dark-zh-CN.png 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 index 65dcfe3f8..510f61a69 100644 Binary files a/docs/assets/remote-ports/remote-ports-menu-light-en-US.png and b/docs/assets/remote-ports/remote-ports-menu-light-en-US.png differ diff --git a/docs/assets/remote-ports/remote-ports-remembered-dark-zh-CN.png b/docs/assets/remote-ports/remote-ports-remembered-dark-zh-CN.png new file mode 100644 index 000000000..b306eed14 Binary files /dev/null and b/docs/assets/remote-ports/remote-ports-remembered-dark-zh-CN.png differ diff --git a/docs/assets/remote-ports/remote-ports-remembered-light-en-US.png b/docs/assets/remote-ports/remote-ports-remembered-light-en-US.png new file mode 100644 index 000000000..ce10eaa8f Binary files /dev/null and b/docs/assets/remote-ports/remote-ports-remembered-light-en-US.png differ diff --git a/docs/assets/remote-ports/remote-ports-rule-confirm-dark-zh-CN.png b/docs/assets/remote-ports/remote-ports-rule-confirm-dark-zh-CN.png index b0535a58a..f85583343 100644 Binary files a/docs/assets/remote-ports/remote-ports-rule-confirm-dark-zh-CN.png and b/docs/assets/remote-ports/remote-ports-rule-confirm-dark-zh-CN.png differ diff --git a/docs/assets/remote-ports/remote-ports-rule-confirm-light-en-US.png b/docs/assets/remote-ports/remote-ports-rule-confirm-light-en-US.png index ff97269cc..a2ec6a7bd 100644 Binary files a/docs/assets/remote-ports/remote-ports-rule-confirm-light-en-US.png and b/docs/assets/remote-ports/remote-ports-rule-confirm-light-en-US.png differ diff --git a/docs/assets/remote-ports/remote-ports-rule-dark-zh-CN.png b/docs/assets/remote-ports/remote-ports-rule-dark-zh-CN.png index b7998fc02..5036f2442 100644 Binary files a/docs/assets/remote-ports/remote-ports-rule-dark-zh-CN.png and b/docs/assets/remote-ports/remote-ports-rule-dark-zh-CN.png differ diff --git a/docs/assets/remote-ports/remote-ports-rule-light-en-US.png b/docs/assets/remote-ports/remote-ports-rule-light-en-US.png index d39a86344..5c3db1cbf 100644 Binary files a/docs/assets/remote-ports/remote-ports-rule-light-en-US.png and b/docs/assets/remote-ports/remote-ports-rule-light-en-US.png differ diff --git a/docs/assets/remote-ports/remote-ports-rules-dark-zh-CN.png b/docs/assets/remote-ports/remote-ports-rules-dark-zh-CN.png index 70e562b33..1f2cc9c29 100644 Binary files a/docs/assets/remote-ports/remote-ports-rules-dark-zh-CN.png and b/docs/assets/remote-ports/remote-ports-rules-dark-zh-CN.png differ diff --git a/docs/assets/remote-ports/remote-ports-rules-light-en-US.png b/docs/assets/remote-ports/remote-ports-rules-light-en-US.png index a1adf82ee..cf29c43a8 100644 Binary files a/docs/assets/remote-ports/remote-ports-rules-light-en-US.png and b/docs/assets/remote-ports/remote-ports-rules-light-en-US.png differ diff --git a/shared/i18n/features/remote-ports.json b/shared/i18n/features/remote-ports.json index 4d2b4e709..7604ff9f0 100644 --- a/shared/i18n/features/remote-ports.json +++ b/shared/i18n/features/remote-ports.json @@ -705,6 +705,110 @@ "platforms": [ "desktop" ] + }, + { + "id": "desktop.remote.ports.columnLabel", + "description": "Header of the Ports window's column with the name the user gave a port or rule.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.ports.editLabel", + "description": "Context menu item that opens the dialog to name a port or forwarding rule.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.ports.labelTitle", + "description": "Title of the dialog that names a port or forwarding rule.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.ports.labelBody", + "description": "Explanation in the label dialog.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.ports.labelField", + "description": "Field label of the label dialog.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.ports.labelInvalid", + "description": "Error under the label field when the label is too long or has control characters.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.ports.labelApply", + "description": "Button that saves the label.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.ports.labelCancel", + "description": "Button that closes the label dialog without changes.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.ports.statusNotRunning", + "description": "Status of a remembered forwarding rule that is not running.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.ports.ruleStart", + "description": "Button and menu item that opens Add Forwarding Rule filled in with a remembered rule.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.ports.ruleForget", + "description": "Button and menu item that removes a remembered forwarding rule from the list.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.ports.recordsFailed", + "description": "Warning when the Ports window could not read or save what it remembers.", + "platforms": [ + "desktop" + ], + "parameters": { + "reason": "string" + } + }, + { + "id": "desktop.remote.ports.recordsDamaged", + "description": "Warning when the stored port records cannot be read; they are left untouched.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.ports.restoreFailed", + "description": "Warning when some forwards left running could not start again after reconnecting.", + "platforms": [ + "desktop" + ], + "parameters": { + "count": "string" + } } ], "locales": { @@ -742,7 +846,7 @@ "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.disconnected": "Not connected. Forwards end with the connection; the local forwards you left running start again when you reconnect.", "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.", @@ -792,13 +896,27 @@ "desktop.remote.ports.rulePortDenied": "The host does not allow listening on port {port}. Ports below 1024 usually need administrator rights.", "desktop.remote.ports.ruleUnsupported": "The remote server running on the host cannot listen on host ports. Reconnect to update it.", "desktop.remote.ports.rulesHeading": "Forwarding Rules", - "desktop.remote.ports.rulesHelp": "Forwarding rules listen on a host port and forward to another server or back to this computer. They stop when the connection ends and are not restored after reconnecting.", + "desktop.remote.ports.rulesHelp": "Forwarding rules listen on a host port and forward to another server or back to this computer. They stop when the connection ends; the window remembers them, and after reconnecting you start them again with Start.", "desktop.remote.ports.ruleColumnListen": "Host Listens On", "desktop.remote.ports.ruleColumnTarget": "Forwards To", "desktop.remote.ports.ruleColumnConnections": "Connections", "desktop.remote.ports.ruleThisComputer": "This computer {address}", "desktop.remote.ports.ruleConnectionsFailed": "{count} ({failed} failed)", - "desktop.remote.ports.ruleAllInterfacesTip": "Listens on every interface of the host: any computer that can reach the host can connect to this port." + "desktop.remote.ports.ruleAllInterfacesTip": "Listens on every interface of the host: any computer that can reach the host can connect to this port.", + "desktop.remote.ports.columnLabel": "Label", + "desktop.remote.ports.editLabel": "Edit Label…", + "desktop.remote.ports.labelTitle": "Edit Label", + "desktop.remote.ports.labelBody": "The label is shown in the Label column and kept on this computer for this workspace. Leave it empty to remove it.", + "desktop.remote.ports.labelField": "Label", + "desktop.remote.ports.labelInvalid": "Use at most 64 characters, without line breaks or tabs.", + "desktop.remote.ports.labelApply": "Save", + "desktop.remote.ports.labelCancel": "Cancel", + "desktop.remote.ports.statusNotRunning": "Not running", + "desktop.remote.ports.ruleStart": "Start…", + "desktop.remote.ports.ruleForget": "Forget Rule", + "desktop.remote.ports.recordsFailed": "The ports and rules of this workspace could not be remembered: {reason}", + "desktop.remote.ports.recordsDamaged": "The saved ports and rules of remote workspaces cannot be read, so they are not restored and changes are not saved. The file in the Lithe settings folder is left as it is.", + "desktop.remote.ports.restoreFailed": "{count} forwards could not start again after reconnecting. Their rows show why." }, "zh-CN": { "desktop.remote.ports.title": "端口", @@ -834,7 +952,7 @@ "desktop.remote.ports.remoteUrlListening": "{url},监听地址:{addresses}", "desktop.remote.ports.empty": "主机上没有正在监听的端口。也可以在上方输入端口直接转发。", "desktop.remote.ports.loading": "正在读取主机上的监听端口…", - "desktop.remote.ports.disconnected": "未连接。转发随连接一起结束,重新连接后需要再次转发。", + "desktop.remote.ports.disconnected": "未连接。转发随连接一起结束;重新连接后,没有停止的本地转发会自动恢复。", "desktop.remote.ports.readFailed": "无法读取主机上的监听端口:{reason}", "desktop.remote.ports.limit": "此连接已转发 {maximum} 个端口,达到上限,请先停止一个。", "desktop.remote.ports.invalidTarget": "主机或端口无效。", @@ -884,13 +1002,27 @@ "desktop.remote.ports.rulePortDenied": "主机不允许监听端口 {port}。普通用户通常不能使用 1024 以下的端口。", "desktop.remote.ports.ruleUnsupported": "这台主机上运行的远端服务不支持在主机上监听端口,请重新连接以更新远端服务。", "desktop.remote.ports.rulesHeading": "转发规则", - "desktop.remote.ports.rulesHelp": "转发规则在主机上监听端口,转到另一台服务器或转回本机。规则随连接结束而停止,重新连接后不会自动恢复。", + "desktop.remote.ports.rulesHelp": "转发规则在主机上监听端口,转到另一台服务器或转回本机。规则随连接结束而停止;窗口会记住它们,重新连接后点“启动”即可再次启动。", "desktop.remote.ports.ruleColumnListen": "主机监听", "desktop.remote.ports.ruleColumnTarget": "转到", "desktop.remote.ports.ruleColumnConnections": "连接", "desktop.remote.ports.ruleThisComputer": "本机 {address}", "desktop.remote.ports.ruleConnectionsFailed": "{count}({failed} 个失败)", - "desktop.remote.ports.ruleAllInterfacesTip": "监听主机的全部网卡:能访问主机的任何电脑都能连接这个端口。" + "desktop.remote.ports.ruleAllInterfacesTip": "监听主机的全部网卡:能访问主机的任何电脑都能连接这个端口。", + "desktop.remote.ports.columnLabel": "标签", + "desktop.remote.ports.editLabel": "编辑标签…", + "desktop.remote.ports.labelTitle": "编辑标签", + "desktop.remote.ports.labelBody": "标签显示在“标签”列,只保存在这台电脑上、只用于这个工作区。留空即删除标签。", + "desktop.remote.ports.labelField": "标签", + "desktop.remote.ports.labelInvalid": "最多 64 个字符,不能包含换行或制表符。", + "desktop.remote.ports.labelApply": "保存", + "desktop.remote.ports.labelCancel": "取消", + "desktop.remote.ports.statusNotRunning": "未运行", + "desktop.remote.ports.ruleStart": "启动…", + "desktop.remote.ports.ruleForget": "忘记规则", + "desktop.remote.ports.recordsFailed": "无法保存这个工作区的端口和规则:{reason}", + "desktop.remote.ports.recordsDamaged": "已保存的远程工作区端口和规则无法读取,因此不会恢复,改动也不会保存。Lithe 设置目录中的文件保持原样。", + "desktop.remote.ports.restoreFailed": "重新连接后有 {count} 个转发无法恢复,原因见对应行。" } } } diff --git a/shared/platform-feature-matrix/features/remote-workspace.json b/shared/platform-feature-matrix/features/remote-workspace.json index 1a9f74081..d028f6a20 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": "远程连接(SSH 主机、本机 WSL 发行版、本机及 SSH 主机与 WSL 发行版上的 Docker/Podman 容器,以及从本机文件夹的 devcontainer.json 构建并打开)、远程路径工作区、主机文件编辑与监听、按路径打开主机上的文件(工作区外只读)、主机终端、主机搜索与替换、远程信任与主机 Git(含打开和新建工作树)、主机上运行程序和脚本运行配置、端口转发(含主机侧转发规则与反向转发)、远程工作区设置(SSH 程序、断线重连与关闭时的远端进程)、关闭确认与保留远端进程", + "capability": "远程连接(SSH 主机、本机 WSL 发行版、本机及 SSH 主机与 WSL 发行版上的 Docker/Podman 容器,以及从本机文件夹的 devcontainer.json 构建并打开)、远程路径工作区、主机文件编辑与监听、按路径打开主机上的文件(工作区外只读)、主机终端、主机搜索与替换、远程信任与主机 Git(含打开和新建工作树)、主机上运行程序和脚本运行配置、端口转发(含主机侧转发规则与反向转发;标签、没停的转发与规则按工作区记在本机,重连或重新打开后恢复转发)、远程工作区设置(SSH 程序、断线重连与关闭时的远端进程)、关闭确认与保留远端进程", "macos": { "implementationStatus": "partial", "verificationStatus": "pending", @@ -82,7 +82,12 @@ "desktop/internal/workbench/remote_devcontainer_test.go", "desktop/internal/workbench/remote_worktree.go", "desktop/internal/workbench/remote_worktree_test.go", - "desktop/internal/workbench/remote_worktree_visual_test.go" + "desktop/internal/workbench/remote_worktree_visual_test.go", + "desktop/internal/core/remote_port_records.go", + "desktop/internal/remoteconn/ports.go", + "desktop/internal/remoteconn/ports_test.go", + "desktop/internal/workbench/remote_port_records.go", + "desktop/internal/workbench/remote_port_records_test.go" ] }, "windows": { @@ -138,11 +143,16 @@ "desktop/internal/workbench/remote_devcontainer.go", "desktop/internal/workbench/remote_worktree.go", "desktop/internal/workbench/remote_worktree_test.go", - "desktop/internal/workbench/remote_worktree_visual_test.go" + "desktop/internal/workbench/remote_worktree_visual_test.go", + "desktop/internal/core/remote_port_records.go", + "desktop/internal/remoteconn/ports.go", + "desktop/internal/remoteconn/ports_test.go", + "desktop/internal/workbench/remote_port_records.go", + "desktop/internal/workbench/remote_port_records_test.go" ] }, "owner": "Remote", - "verification": "在“远程开发”窗口选中已保存的 Linux SSH 连接点“连接”:SSH 询问出现在窗口中,连接后窗口改为主机的文件夹选择,从主目录开始列出子文件夹(跳过名称不是 UTF-8 的条目并说明数量),可输入 ~ 或 / 开头的路径跳转,不存在的路径说明原因且不能打开;“返回”断开这次会话回到连接表单。选中文件夹点“打开”:新标签页打开远程工作区,窗口标题为“文件夹 [SSH: 连接名]”,项目树经 Core 列出主机目录(本机占位目录始终为空),右键只有复制主机路径和刷新;以安全模式打开的文件夹,编辑器上方说明可以浏览、编辑、保存和搜索主机文件,信任文件夹后才能用 Git;受信任的文件夹说明文件、终端和 Git 都在主机上,运行、调试和语言服务器暂不可用;空白编辑区提示 Search Everywhere 和 Find in Files。在项目树双击文件:编辑器经会话读取主机文件(不超过 16 MiB),保存时带上打开时的大小和修改时间写回主机,新建的文件只在主机上不存在时创建;主机上的文件期间被别人改过时保存被拒绝并显示外部修改冲突,“加载磁盘版本”载入主机内容,本机占位目录始终为空。超过 8 MiB 的保存说明主机单次保存上限,编辑内容保留;主机上缺失、无权限、不是普通文件、超时和连接断开分别说明原因,连接断开后自动重连并把打开的文档和主机重新比对。图片、PDF 等查看器、本地历史和插件终端都被拒绝并提示,不回退到本机;在文件浏览器中显示(标签页右键、Search Everywhere 结果、Git 变更)在远程工作区里不提供。状态栏连接菜单的“打开主机上的文件…”(未连接时不可用)从窗口顶部弹出路径框,默认 ~/,经 remote.readDir 列出路径最后一个“/”之前的文件夹,按其后的文字(不分大小写)筛选名称开头,文件夹在前,以“.”开头时才列出隐藏条目,无法读取的条目说明数量;上下键移动、Tab 补全名称、回车进入文件夹或打开文件,没有匹配时回车按输入的路径打开,Esc 或点外面关闭;不以 / 或 ~/ 开头的输入说明要输入什么,名称含“\\”的路径说明在 Windows 上无法打开。工作区文件夹里的文件与项目树打开的相同、可以编辑;文件夹以外的文件(对标 Zed)在占位目录旁的 .lithe-remote-host 下以只读方式打开(S25):不能切换为可编辑(提示原因并记为拒绝),保存和新建都被拒绝并说明原因、不写主机,状态栏导航路径显示 ~ 开头的主机路径,复制相对路径不提供;重连和关闭前与其他文档一样和主机比对,主机上的改动在没有编辑时重新载入(主机监听只覆盖工作区文件夹)。日志只记 remote_open_host_file、remote_read_dir、toggle_read_only 等操作名和原因,不含主机路径。打开“终端”工具窗口:经会话的 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 和提交窗口说明要打开仓库顶层文件夹,不显示变更也不记为失败。工作树列表、锁定、解锁、删除在主机上执行,列表和详情显示主机路径,复制路径复制主机路径。打开关联工作树时“远程开发”窗口打开,用打开工作区所用的连接(或 WSL 发行版)再连一次,显示连接步骤和 OpenSSH 的询问,从未决定过的文件夹先询问是否信任,然后在本窗口的新标签页经一个新会话打开该主机文件夹;再次打开时切到已打开的标签页,不再连接;连接在工作区打开后被删除时窗口说明原因、不连接。新建工作树对话框把 Core 在仓库旁的建议显示为主机路径(如 /home/dev/project-topic),输入框下说明路径是主机上的文件夹、由主机上的 Git 创建;输入的其他主机路径原样保留,“创建”在工作区会话上由主机上的 Git 创建并选中新工作树,“创建后打开”同样经新会话在新标签页打开。在新窗口打开和在文件浏览器中显示仍被拒绝并提示。受信任的远程工作区里运行、调试、当前文件运行、测试、构建任务和插件语言服务器都不在本机启动,都记为拒绝并提示,运行、测试和构建工具窗口说明暂不可用。状态栏前端显示连接名和心跳往返时间;连续两次心跳无响应显示“无响应”,第三次结束会话并按 Core 由“自动重连时长”给出的间隔重连(默认 1、2、4、8、16、29 秒,共 60 秒),每次失败后等下一个间隔,用完后显示“已断开”和原因,菜单里可“重新连接”;连接被关闭时同样按这些间隔重连;时长设为“不自动重连”时直接显示“已断开”。关闭窗口、退出 Lithe、菜单里“断开并关闭”和切换工作区时,先经 remote.runningPrograms 读取主机上 Lithe 为这个工作区启动的进程和终端;没有时直接结束会话,有时询问“关闭远程工作区?”,正文写明连接名并逐项列出类型(终端、进程)、名称、命令(原样显示,不脱敏)和已运行时长,按钮为“结束并关闭”(默认)、“保留在远端并关闭”和“取消”,“记住我的选择”旁的 ⓘ 说明之后不再询问、只能在 设置 › 工具 › 远程工作区 修改。“取消”保留窗口和会话;“结束并关闭”经 remote.disconnect 结束主机会话;“保留在远端并关闭”让主机保留会话,把恢复凭据按连接存入系统密钥存储后通知“N 个进程保留在 <连接名> 上”,凭据存不下时改为结束并说明原因,主机拒绝保留时同样结束并说明;读取进程列表失败时不询问、照常结束。勾选“记住我的选择”把结束或保留写入 Core 的远程工作区设置,之后直接按设置执行。下次经同一连接、同一 WSL 发行版或同一容器连接时带上最新的保留凭据接回会话,打开文件夹后列出上次保留、仍在运行的进程,可“结束这些进程”(经 remote.endPrograms 只结束它们,不动这次新开的)或“继续运行”;主机上已没有该会话时开新会话并忘掉凭据;接回后没打开工作区就停止的连接再次保留该会话,进程不会未经用户选择就结束。退出 Lithe 时每个远程工作区窗口同样询问,取消的窗口保持打开。最近项目不记录远程工作区。日志只有 remote.connect、remote.workspace.open/reconnect/disconnect、remote.close.cancel/keep/end、remote.kept.end/keep 等动作和失败的操作名,不含主机、用户名、主机路径、主目录、进程名称或命令。运行 remote_close_test.go 的 7 个测试、remoteconn 的 kept_test.go 3 个测试、TestVisualRemoteClose 无头截图(询问、保留后的通知、下次连接列出保留的进程)、remote_workspace_test.go 的 5 个测试、remote_git_test.go 的 6 个测试、remoteplaceholder 的 TestHostAndLocalPathsMapBothWays 与 TestHostNamedPathNamesEveryHostPathBelowTheSibling、remote_worktree_test.go 的 3 个测试、remote_documents_test.go 的 2 个测试、remote_terminal_test.go 的 9 个测试、remote_watch_test.go 的 5 个测试、remote_search_test.go 的 4 个测试、remote_host_files_test.go 的 TestRemoteOpenFileOnHost、internal/core 的 TestRemoteTerminal*、TestRemoteWatch* 与 TestRemoteWorkspaceFiltersChangesWithoutTheHost、termview 的 TestOpenStartsTheProgramElsewhere,以及 TestVisualRemoteWorkspace 与 TestVisualRemoteWorktrees 无头截图;在 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 存储,后续阶段)。端口窗口标题栏的“+”打开“添加转发规则”:方向默认“主机端口 → 另一台服务器”,由主机自己连接目标,数据不经过本机;主机端口可留空由主机选择,目标接受端口、主机:端口或网址(由 Core 的 remote.parseForwardAddress 解析,网址里带用户名或密码时拒绝)。规则默认只在主机的回环地址 127.0.0.1 上监听;勾选“监听主机的全部网卡”时显示警告,每次添加都再次询问、不记住,列表里的监听地址用警告色显示并在悬停提示里说明;目标不是主机自身的回环地址时先询问(S28)。“主机端口 → 本机(反向转发)”只在 设置 › 工具 › 远程工作区 的“反向转发”允许时提供(默认自动,即不允许,对话框说明在哪里开启),每条都询问,主机只在回环地址监听,本机只连接回环地址上的端口。主机端口被占用、主机不允许监听(如 1024 以下)、远端服务不支持、达到会话转发上限(与本机转发合计)、反向转发未被允许分别说明原因,主机端口不是 1–65535 时就地说明,对话框保留输入。端口窗口的“转发规则”一节列出主机监听地址、转到的目标(反向转发为“本机 地址”)、连接数(有失败时注明失败数)和状态,每行可停止,标题栏的全部停止同样停止规则;规则随会话结束而停止,重连后不自动恢复,关闭工作区后也不保存。日志只记 remote.ports.addRule/ruleHost/ruleReverse/ruleConfirm/stopRule 等动作和失败的操作名,不含地址、网址或进程名。运行 remote_port_rules_test.go 的 5 个测试、settingswindow 的 TestRemoteWorkspaceReverseForwardingIsAppliedAndRestored,以及 TestVisualRemotePorts 的转发规则列表、添加对话框和全部网卡询问截图。远程 Git 的 AskPass 转交(推送、拉取时的凭据询问)、从上级目录开始的仓库尚未支持。Windows 上“远程开发”窗口在已保存的连接之后以“WSL”标题列出本机安装的 WSL 发行版(Core 的 remote.listWslDistributions,每次打开窗口读取一次;搜索时不列出,标题可折叠;macOS 和没有 WSL 的 Windows 不显示这一组)。选中发行版后右侧说明经本机 wsl.exe 打开、不保存任何信息,可填写 Linux 用户(留空为发行版默认用户),地址显示为 wsl:[用户@]发行版。“连接”经 remote.connect 的 wsl 参数启动,不经 OpenSSH、没有询问,步骤从“启动发行版”开始,不显示读取配置和身份验证;发行版没有安装或没能启动、本机找不到 wsl.exe 时分别说明,不显示 SSH 的排查提示,也没有“编辑连接”;Core 拒绝的用户名或发行版名就地说明。连接后与 SSH 相同:选择文件夹、信任询问、工作区、心跳与重连;窗口标题为“文件夹 [WSL: 发行版]”,状态栏为“WSL: 发行版”(SSH 工作区的“SSH”也由同一参数给出),列表和概览显示已打开该发行版的窗口数。发行版不写入已保存的连接,打开过的文件夹不记入最近文件夹。日志只有 remote.wsl.select、remote.connect 等动作,不含发行版名、用户名或主机路径。运行 remote_wsl_test.go 的 3 个测试、internal/core 的 TestRemoteConnectSendsWSLAloneAndCoreRefusesItByField 与 TestRemoteListWSLDistributionsIsUnavailableOutsideWindows,以及 TestVisualRemoteConnections 的 WSL 截图;真实 Windows 上的 WSL 验收(wsl.exe 的错误输出、--exec 的二进制透传、结束 wsl.exe 后 Linux 进程是否退出、未知用户)仍待完成。打开“设置 › 工具 › 远程工作区”:页面只读取、不创建任何文件。“SSH 程序”默认“自动(Core 在 PATH 上找到的 ssh 路径)”,找不到时为“自动(未找到 ssh)”;“选择…”选一个文件作为草稿,下拉菜单可回到自动;保存的程序缺失或不可执行时在行下说明。“SSH 配置文件”只显示 Core 读取的 ~/.ssh/config 路径,不存在时注明。“自动重连时长”可选“自动(1 分钟)”、不自动重连、15 秒到 1 小时,保存过的其他值也列出。“反向转发”默认“自动(不允许)”,可选允许或不允许,ⓘ 说明主机上的所有用户都能连接反向转发的端口、每条规则仍会确认。“关闭工作区”卡片里“关闭时的远端进程”可选“每次询问”(默认)、“结束”和“保留在远端”,关闭对话框勾选“记住我的选择”后只能在这里改回;“常驻会话的空闲超时”只读显示 Core 报告的远端服务超时(10 分钟),ⓘ 说明断线且没人保留的会话多久后由主机结束。“保存位置”显示偏好目录下的 remote/preferences.json,还没有文件时注明修改后才创建。修改只是草稿:侧栏和底部显示未应用数量,“应用”或“好”经 Core 的 remote.editPreferences 写入(程序先于时长),写入后重新读取显示;Core 拒绝相对路径、不存在、不可执行的程序或超出 0–3600 秒的时长时在页面说明原因并保留草稿,不写文件;文件期间被改过时重新读取并请用户再次应用;文件损坏时说明路径、不提供编辑,此时连接、测试连接、读取有效设置和导入 SSH 主机都失败并说明原因,不用未经用户选择的程序启动 OpenSSH。选中的 SSH 程序用于连接、测试连接、有效设置和 SSH 配置导入(WSL 经 wsl.exe 启动,不使用它)。日志只记 remote_preferences_settings_load/save 等操作名和 Core 错误码,不记路径。运行 settingswindow 的 TestRemoteWorkspace* 6 个测试、remoteconn 的 preferences_test.go、internal/core 的 TestRemotePreferences*,以及 TestVisualRemoteWorkspace 无头截图(中英文、深浅色,自动值、草稿和关闭时保留远端进程三种状态)。真实 SSH 主机上关闭后保留、重连接回和结束保留进程的整机验收,以及保留进程的输出重新接回终端和运行窗口(后续阶段),仍待完成。“远程开发”窗口在 WSL 发行版之后以“容器”标题列出本机 Docker 和 Podman 正在运行的容器(Core 的 remote.listContainers,每次打开窗口读取一次,两个引擎在同一个后台任务里依次读取,一个超时或报错时跳过它并记一次 remote_containers_list 失败,另一个照常列出;搜索时不列出,标题可折叠;两个引擎都没有时不显示这一组)。每行显示容器名和“引擎 · 镜像”,已有窗口打开它时显示绿点。选中容器后右侧显示引擎标签、地址 引擎:[用户@]容器、镜像与引擎给出的状态,说明经本机引擎进入正在运行的容器、不启动不创建不改动容器、不挂载目录、不保存任何信息,可填写容器内用户(用户名、uid 或 用户:组,留空为镜像默认用户)。“连接”经 remote.connect 的 container 参数进入,不经 OpenSSH、没有询问、不发送 SSH 偏好,步骤从“进入容器”开始;容器已停止或暂停、引擎没有应答时说明这几种可能,找不到引擎命令行时说明需要安装哪个引擎,引擎输出只显示在步骤下方,不显示 SSH 的排查提示,也没有“编辑连接”;Core 拒绝的用户或容器名就地说明。连接后与 SSH 相同:选择文件夹、信任询问(信任记录包含容器)、工作区、心跳与重连;窗口标题为“文件夹 [容器: 容器名]”,状态栏为“容器: 容器名”,列表和概览按引擎和容器名显示已打开的窗口数。按容器名连接,所以同名重建的容器仍能接上;容器不写入已保存的连接,打开过的文件夹不记入最近文件夹。日志只有 remote.container.select、remote.connect 等动作,不含容器名、镜像、状态或用户名。测试替换的内核不运行本机的 docker 或 podman。运行 remote_container_test.go 的 4 个测试、internal/core 的 TestRemoteConnectSendsAContainerAloneAndCoreRefusesItByField 与 TestRemoteListContainersNamesTheSessionAndTheEngine,以及 TestVisualRemoteConnections 的容器截图;真实 Docker、Podman 与 Windows 上的整机验收仍待完成。“远程开发”窗口列表工具栏和空白页的“从 devcontainer.json 打开…”打开“在 Dev Container 中打开”页(窗口标题为“远程开发 › 在 Dev Container 中打开”):说明用官方 Dev Container CLI 按本机文件夹的 devcontainer.json 构建并启动容器、构建会运行文件夹的 Dockerfile、features 和命令所以文件夹必须受信任、Lithe 不额外挂载目录也不额外加参数。“选择文件夹…”打开系统文件夹选择,也可输入路径后按回车;相对路径、不存在的路径就地说明。读取文件夹时经 Core 的 remote.devcontainerConfigs 按规范顺序列出 .devcontainer/devcontainer.json、.devcontainer.json 和 .devcontainer 下一层文件夹里的配置,配置有 name 时显示“名称(路径)”,默认选第一个;没有配置时说明并且不能构建。容器引擎可选 Docker 或 Podman。同时读取文件夹的信任:未受信任时说明并把按钮换成“信任并构建”,先以与打开受信任项目相同的方式写入本机信任记录(记一次 workspace.trust.grant),再构建;读取信任失败时说明原因、不能构建。“构建并打开”经 remote.devcontainerUp 运行 CLI(带 projectCodeAllowed),CLI 的输出逐行显示在“构建日志”里(Core 已隐藏敏感信息,最多保留最近 5000 行,Core 截断时在下方说明),只显示、不写入 Lithe 的日志;构建期间左侧列表、配置、引擎和文件夹都不能改,底部显示“正在构建 dev container…”和“停止”。“停止”取消这次构建,日志保留并说明已经启动的容器会继续运行,不记失败;“取消”和关闭窗口也会先停止构建。找不到 devcontainer CLI 时说明用 npm 安装,CLI 报告失败时显示它的输出,超过一小时、结果里没有容器或工作区文件夹、文件夹不受信任分别说明,各记一次 remote_devcontainer_up 失败。成功后选中 CLI 返回的容器(重新读取容器列表,显示镜像),以 CLI 返回的 remoteUser 为容器内用户,按容器连接并直接打开 CLI 返回的工作区文件夹(与容器入口相同的信任询问、工作区、心跳与重连)。日志只有 remote.devcontainer.open/choose/build/stop、remote.connect 等动作,不含文件夹、配置名、容器名、用户名或 CLI 输出。测试替换的内核不运行本机的 devcontainer、docker 或 podman。运行 remote_devcontainer_test.go 的 5 个测试、internal/core 的 TestRemoteDevcontainer*,以及 TestVisualRemoteConnections 的 devcontainer 截图;装有 Dev Container CLI 的真实 Docker、Podman 上的整机验收仍待完成。在 SSH 主机或 WSL 发行版的文件夹选择里,标题栏的“主机上的容器”在文件夹的位置列出那台主机上 Docker 和 Podman 正在运行的容器(经浏览会话的 remote.listContainers 依次读取两个引擎,在远端服务的环境里运行,所以列出的容器就是能进入的;主机没有引擎命令行时说明没有找到 Docker 或 Podman,引擎报错时显示它的输出、不写日志),每行显示容器名、“引擎 · 镜像”和状态,可填写容器内用户(留空为镜像默认用户)。“进入容器”或双击一行结束浏览会话,重新连接主机并经主机上的引擎 exec 进入容器(OpenSSH 会再次询问它要问的内容;步骤与主机相同,地址显示为“主机 › 引擎:[用户@]容器”),随后在容器里选择文件夹;“返回文件夹”回到主机的文件夹。主机连不上或容器已停止、暂停、引擎没有应答时用同一段文字说明并点名引擎,具体原因在诊断输出里;没有“编辑连接”,“重试”进入同一台主机上的同一个容器。工作区身份为“已保存连接或发行版的身份/引擎:[用户@]容器”,窗口名为“容器名(主机名)”,不写入已保存的连接,打开过的文件夹不记入最近文件夹;信任记录包含主机与容器。Core 同样只进正在运行的容器,不提权、不改容器、不挂载(S32)。主机上不支持从 devcontainer.json 构建(devcontainer up 只在本机运行)。日志只有 remote.browse.containers/folders、remote.browse.container.enter、remote.connect 等动作和 remote_host_containers_list 失败名,不含主机、容器名、镜像、用户名或主机路径。运行 remote_host_containers_test.go 的 3 个测试和 TestVisualRemoteConnections 的主机容器截图;真实 SSH 主机与 Windows WSL 上的容器验收仍待完成。在远程工作区的标题栏选中程序或脚本运行配置点“运行”:程序在主机上启动(工作目录为主机文件夹下的相对目录,环境为主机登录环境加配置的变量),输出进入运行窗口,标签页带“主机”徽标;脚本写到主机临时目录,运行结束后删除;“停止”先发 SIGTERM,超过停止等待时间再强制结束;输出里的主机路径可点击并经占位路径在编辑器打开。配置的“执行前”列表里引用的其他程序或脚本运行配置按顺序在主机上先运行,步骤标题和输出写在同一个控制台,全部以 0 退出后才启动配置本身;某一步以非零退出码结束时说明步骤名和退出码,配置不启动;运行步骤时“停止”先给步骤的主机进程发 SIGTERM。列表里有插件提供的任务时说明远程工作区暂不支持插件任务,请从“执行前”列表删除后再运行。构建工具、插件提供的运行和调试在远程工作区说明暂不支持。", + "verification": "在“远程开发”窗口选中已保存的 Linux SSH 连接点“连接”:SSH 询问出现在窗口中,连接后窗口改为主机的文件夹选择,从主目录开始列出子文件夹(跳过名称不是 UTF-8 的条目并说明数量),可输入 ~ 或 / 开头的路径跳转,不存在的路径说明原因且不能打开;“返回”断开这次会话回到连接表单。选中文件夹点“打开”:新标签页打开远程工作区,窗口标题为“文件夹 [SSH: 连接名]”,项目树经 Core 列出主机目录(本机占位目录始终为空),右键只有复制主机路径和刷新;以安全模式打开的文件夹,编辑器上方说明可以浏览、编辑、保存和搜索主机文件,信任文件夹后才能用 Git;受信任的文件夹说明文件、终端和 Git 都在主机上,运行、调试和语言服务器暂不可用;空白编辑区提示 Search Everywhere 和 Find in Files。在项目树双击文件:编辑器经会话读取主机文件(不超过 16 MiB),保存时带上打开时的大小和修改时间写回主机,新建的文件只在主机上不存在时创建;主机上的文件期间被别人改过时保存被拒绝并显示外部修改冲突,“加载磁盘版本”载入主机内容,本机占位目录始终为空。超过 8 MiB 的保存说明主机单次保存上限,编辑内容保留;主机上缺失、无权限、不是普通文件、超时和连接断开分别说明原因,连接断开后自动重连并把打开的文档和主机重新比对。图片、PDF 等查看器、本地历史和插件终端都被拒绝并提示,不回退到本机;在文件浏览器中显示(标签页右键、Search Everywhere 结果、Git 变更)在远程工作区里不提供。状态栏连接菜单的“打开主机上的文件…”(未连接时不可用)从窗口顶部弹出路径框,默认 ~/,经 remote.readDir 列出路径最后一个“/”之前的文件夹,按其后的文字(不分大小写)筛选名称开头,文件夹在前,以“.”开头时才列出隐藏条目,无法读取的条目说明数量;上下键移动、Tab 补全名称、回车进入文件夹或打开文件,没有匹配时回车按输入的路径打开,Esc 或点外面关闭;不以 / 或 ~/ 开头的输入说明要输入什么,名称含“\\”的路径说明在 Windows 上无法打开。工作区文件夹里的文件与项目树打开的相同、可以编辑;文件夹以外的文件(对标 Zed)在占位目录旁的 .lithe-remote-host 下以只读方式打开(S25):不能切换为可编辑(提示原因并记为拒绝),保存和新建都被拒绝并说明原因、不写主机,状态栏导航路径显示 ~ 开头的主机路径,复制相对路径不提供;重连和关闭前与其他文档一样和主机比对,主机上的改动在没有编辑时重新载入(主机监听只覆盖工作区文件夹)。日志只记 remote_open_host_file、remote_read_dir、toggle_read_only 等操作名和原因,不含主机路径。打开“终端”工具窗口:经会话的 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 和提交窗口说明要打开仓库顶层文件夹,不显示变更也不记为失败。工作树列表、锁定、解锁、删除在主机上执行,列表和详情显示主机路径,复制路径复制主机路径。打开关联工作树时“远程开发”窗口打开,用打开工作区所用的连接(或 WSL 发行版)再连一次,显示连接步骤和 OpenSSH 的询问,从未决定过的文件夹先询问是否信任,然后在本窗口的新标签页经一个新会话打开该主机文件夹;再次打开时切到已打开的标签页,不再连接;连接在工作区打开后被删除时窗口说明原因、不连接。新建工作树对话框把 Core 在仓库旁的建议显示为主机路径(如 /home/dev/project-topic),输入框下说明路径是主机上的文件夹、由主机上的 Git 创建;输入的其他主机路径原样保留,“创建”在工作区会话上由主机上的 Git 创建并选中新工作树,“创建后打开”同样经新会话在新标签页打开。在新窗口打开和在文件浏览器中显示仍被拒绝并提示。受信任的远程工作区里运行、调试、当前文件运行、测试、构建任务和插件语言服务器都不在本机启动,都记为拒绝并提示,运行、测试和构建工具窗口说明暂不可用。状态栏前端显示连接名和心跳往返时间;连续两次心跳无响应显示“无响应”,第三次结束会话并按 Core 由“自动重连时长”给出的间隔重连(默认 1、2、4、8、16、29 秒,共 60 秒),每次失败后等下一个间隔,用完后显示“已断开”和原因,菜单里可“重新连接”;连接被关闭时同样按这些间隔重连;时长设为“不自动重连”时直接显示“已断开”。关闭窗口、退出 Lithe、菜单里“断开并关闭”和切换工作区时,先经 remote.runningPrograms 读取主机上 Lithe 为这个工作区启动的进程和终端;没有时直接结束会话,有时询问“关闭远程工作区?”,正文写明连接名并逐项列出类型(终端、进程)、名称、命令(原样显示,不脱敏)和已运行时长,按钮为“结束并关闭”(默认)、“保留在远端并关闭”和“取消”,“记住我的选择”旁的 ⓘ 说明之后不再询问、只能在 设置 › 工具 › 远程工作区 修改。“取消”保留窗口和会话;“结束并关闭”经 remote.disconnect 结束主机会话;“保留在远端并关闭”让主机保留会话,把恢复凭据按连接存入系统密钥存储后通知“N 个进程保留在 <连接名> 上”,凭据存不下时改为结束并说明原因,主机拒绝保留时同样结束并说明;读取进程列表失败时不询问、照常结束。勾选“记住我的选择”把结束或保留写入 Core 的远程工作区设置,之后直接按设置执行。下次经同一连接、同一 WSL 发行版或同一容器连接时带上最新的保留凭据接回会话,打开文件夹后列出上次保留、仍在运行的进程,可“结束这些进程”(经 remote.endPrograms 只结束它们,不动这次新开的)或“继续运行”;主机上已没有该会话时开新会话并忘掉凭据;接回后没打开工作区就停止的连接再次保留该会话,进程不会未经用户选择就结束。退出 Lithe 时每个远程工作区窗口同样询问,取消的窗口保持打开。最近项目不记录远程工作区。日志只有 remote.connect、remote.workspace.open/reconnect/disconnect、remote.close.cancel/keep/end、remote.kept.end/keep 等动作和失败的操作名,不含主机、用户名、主机路径、主目录、进程名称或命令。运行 remote_close_test.go 的 7 个测试、remoteconn 的 kept_test.go 3 个测试、TestVisualRemoteClose 无头截图(询问、保留后的通知、下次连接列出保留的进程)、remote_workspace_test.go 的 5 个测试、remote_git_test.go 的 6 个测试、remoteplaceholder 的 TestHostAndLocalPathsMapBothWays 与 TestHostNamedPathNamesEveryHostPathBelowTheSibling、remote_worktree_test.go 的 3 个测试、remote_documents_test.go 的 2 个测试、remote_terminal_test.go 的 9 个测试、remote_watch_test.go 的 5 个测试、remote_search_test.go 的 4 个测试、remote_host_files_test.go 的 TestRemoteOpenFileOnHost、internal/core 的 TestRemoteTerminal*、TestRemoteWatch* 与 TestRemoteWorkspaceFiltersChangesWithoutTheHost、termview 的 TestOpenStartsTheProgramElsewhere,以及 TestVisualRemoteWorkspace 与 TestVisualRemoteWorktrees 无头截图;在 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 上限时说明上限;状态栏显示已转发数量,点击打开端口窗口;会话结束时转发随之结束;重连或重新打开工作区后,用户没停的本机转发按记住的本机端口和确认自动重新转发,没能重新转发的行标为失败并给出 Core 的原因,窗口说明有几个没能恢复。日志只记 remote.ports.forward/localPort/move/stop/status 等动作和失败操作名,不含主机、地址或进程名。运行 remote_ports_test.go 的 12 个测试、internal/core 的 TestRemoteSessionCommandsOfAnUnknownSession 与 TestRemoteParseForwardAddressReadsPortsAndURLs,以及 TestVisualRemotePorts 无头截图。手动添加的端口、本机端口选择、行和规则的标签(右键“编辑标签…”,标签列显示,最多 64 个字符,不能含控制字符,留空即删除)、没停的本机转发和启动过的规则,按连接目标和主机上工作区的真实路径记在本机偏好目录的 remote/ports.json(Core 的 remote.portRecords、remote.editPortRecords、remote.restoreForwards),不写主机、工作区、应用包或安装目录;文件无法解析时窗口说明且从不覆盖,之后的修改只留在内存。端口窗口标题栏的“+”打开“添加转发规则”:方向默认“主机端口 → 另一台服务器”,由主机自己连接目标,数据不经过本机;主机端口可留空由主机选择,目标接受端口、主机:端口或网址(由 Core 的 remote.parseForwardAddress 解析,网址里带用户名或密码时拒绝)。规则默认只在主机的回环地址 127.0.0.1 上监听;勾选“监听主机的全部网卡”时显示警告,每次添加都再次询问、不记住,列表里的监听地址用警告色显示并在悬停提示里说明;目标不是主机自身的回环地址时先询问(S28)。“主机端口 → 本机(反向转发)”只在 设置 › 工具 › 远程工作区 的“反向转发”允许时提供(默认自动,即不允许,对话框说明在哪里开启),每条都询问,主机只在回环地址监听,本机只连接回环地址上的端口。主机端口被占用、主机不允许监听(如 1024 以下)、远端服务不支持、达到会话转发上限(与本机转发合计)、反向转发未被允许分别说明原因,主机端口不是 1–65535 时就地说明,对话框保留输入。端口窗口的“转发规则”一节列出主机监听地址、转到的目标(反向转发为“本机 地址”)、连接数(有失败时注明失败数)和状态,每行可停止,标题栏的全部停止同样停止规则;规则随会话结束而停止,重连或重新打开后列为“未运行”,从不自动启动:行尾“启动”把规则填进“添加转发规则”由用户再提交,“忘记”删除记录;监听全部网卡从不记住,再启动时按回环地址填入,要全部网卡须重新勾选并确认(S27)。日志只记 remote.ports.addRule/ruleHost/ruleReverse/ruleConfirm/stopRule 等动作和失败的操作名,不含地址、网址或进程名。运行 remote_port_rules_test.go 的 5 个测试、remote_port_records_test.go 的 3 个测试、remoteconn/ports_test.go、settingswindow 的 TestRemoteWorkspaceReverseForwardingIsAppliedAndRestored,以及 TestVisualRemotePorts 的转发规则列表、添加对话框和全部网卡询问截图。远程 Git 的 AskPass 转交(推送、拉取时的凭据询问)、从上级目录开始的仓库尚未支持。Windows 上“远程开发”窗口在已保存的连接之后以“WSL”标题列出本机安装的 WSL 发行版(Core 的 remote.listWslDistributions,每次打开窗口读取一次;搜索时不列出,标题可折叠;macOS 和没有 WSL 的 Windows 不显示这一组)。选中发行版后右侧说明经本机 wsl.exe 打开、不保存任何信息,可填写 Linux 用户(留空为发行版默认用户),地址显示为 wsl:[用户@]发行版。“连接”经 remote.connect 的 wsl 参数启动,不经 OpenSSH、没有询问,步骤从“启动发行版”开始,不显示读取配置和身份验证;发行版没有安装或没能启动、本机找不到 wsl.exe 时分别说明,不显示 SSH 的排查提示,也没有“编辑连接”;Core 拒绝的用户名或发行版名就地说明。连接后与 SSH 相同:选择文件夹、信任询问、工作区、心跳与重连;窗口标题为“文件夹 [WSL: 发行版]”,状态栏为“WSL: 发行版”(SSH 工作区的“SSH”也由同一参数给出),列表和概览显示已打开该发行版的窗口数。发行版不写入已保存的连接,打开过的文件夹不记入最近文件夹。日志只有 remote.wsl.select、remote.connect 等动作,不含发行版名、用户名或主机路径。运行 remote_wsl_test.go 的 3 个测试、internal/core 的 TestRemoteConnectSendsWSLAloneAndCoreRefusesItByField 与 TestRemoteListWSLDistributionsIsUnavailableOutsideWindows,以及 TestVisualRemoteConnections 的 WSL 截图;真实 Windows 上的 WSL 验收(wsl.exe 的错误输出、--exec 的二进制透传、结束 wsl.exe 后 Linux 进程是否退出、未知用户)仍待完成。打开“设置 › 工具 › 远程工作区”:页面只读取、不创建任何文件。“SSH 程序”默认“自动(Core 在 PATH 上找到的 ssh 路径)”,找不到时为“自动(未找到 ssh)”;“选择…”选一个文件作为草稿,下拉菜单可回到自动;保存的程序缺失或不可执行时在行下说明。“SSH 配置文件”只显示 Core 读取的 ~/.ssh/config 路径,不存在时注明。“自动重连时长”可选“自动(1 分钟)”、不自动重连、15 秒到 1 小时,保存过的其他值也列出。“反向转发”默认“自动(不允许)”,可选允许或不允许,ⓘ 说明主机上的所有用户都能连接反向转发的端口、每条规则仍会确认。“关闭工作区”卡片里“关闭时的远端进程”可选“每次询问”(默认)、“结束”和“保留在远端”,关闭对话框勾选“记住我的选择”后只能在这里改回;“常驻会话的空闲超时”只读显示 Core 报告的远端服务超时(10 分钟),ⓘ 说明断线且没人保留的会话多久后由主机结束。“保存位置”显示偏好目录下的 remote/preferences.json,还没有文件时注明修改后才创建。修改只是草稿:侧栏和底部显示未应用数量,“应用”或“好”经 Core 的 remote.editPreferences 写入(程序先于时长),写入后重新读取显示;Core 拒绝相对路径、不存在、不可执行的程序或超出 0–3600 秒的时长时在页面说明原因并保留草稿,不写文件;文件期间被改过时重新读取并请用户再次应用;文件损坏时说明路径、不提供编辑,此时连接、测试连接、读取有效设置和导入 SSH 主机都失败并说明原因,不用未经用户选择的程序启动 OpenSSH。选中的 SSH 程序用于连接、测试连接、有效设置和 SSH 配置导入(WSL 经 wsl.exe 启动,不使用它)。日志只记 remote_preferences_settings_load/save 等操作名和 Core 错误码,不记路径。运行 settingswindow 的 TestRemoteWorkspace* 6 个测试、remoteconn 的 preferences_test.go、internal/core 的 TestRemotePreferences*,以及 TestVisualRemoteWorkspace 无头截图(中英文、深浅色,自动值、草稿和关闭时保留远端进程三种状态)。真实 SSH 主机上关闭后保留、重连接回和结束保留进程的整机验收,以及保留进程的输出重新接回终端和运行窗口(后续阶段),仍待完成。“远程开发”窗口在 WSL 发行版之后以“容器”标题列出本机 Docker 和 Podman 正在运行的容器(Core 的 remote.listContainers,每次打开窗口读取一次,两个引擎在同一个后台任务里依次读取,一个超时或报错时跳过它并记一次 remote_containers_list 失败,另一个照常列出;搜索时不列出,标题可折叠;两个引擎都没有时不显示这一组)。每行显示容器名和“引擎 · 镜像”,已有窗口打开它时显示绿点。选中容器后右侧显示引擎标签、地址 引擎:[用户@]容器、镜像与引擎给出的状态,说明经本机引擎进入正在运行的容器、不启动不创建不改动容器、不挂载目录、不保存任何信息,可填写容器内用户(用户名、uid 或 用户:组,留空为镜像默认用户)。“连接”经 remote.connect 的 container 参数进入,不经 OpenSSH、没有询问、不发送 SSH 偏好,步骤从“进入容器”开始;容器已停止或暂停、引擎没有应答时说明这几种可能,找不到引擎命令行时说明需要安装哪个引擎,引擎输出只显示在步骤下方,不显示 SSH 的排查提示,也没有“编辑连接”;Core 拒绝的用户或容器名就地说明。连接后与 SSH 相同:选择文件夹、信任询问(信任记录包含容器)、工作区、心跳与重连;窗口标题为“文件夹 [容器: 容器名]”,状态栏为“容器: 容器名”,列表和概览按引擎和容器名显示已打开的窗口数。按容器名连接,所以同名重建的容器仍能接上;容器不写入已保存的连接,打开过的文件夹不记入最近文件夹。日志只有 remote.container.select、remote.connect 等动作,不含容器名、镜像、状态或用户名。测试替换的内核不运行本机的 docker 或 podman。运行 remote_container_test.go 的 4 个测试、internal/core 的 TestRemoteConnectSendsAContainerAloneAndCoreRefusesItByField 与 TestRemoteListContainersNamesTheSessionAndTheEngine,以及 TestVisualRemoteConnections 的容器截图;真实 Docker、Podman 与 Windows 上的整机验收仍待完成。“远程开发”窗口列表工具栏和空白页的“从 devcontainer.json 打开…”打开“在 Dev Container 中打开”页(窗口标题为“远程开发 › 在 Dev Container 中打开”):说明用官方 Dev Container CLI 按本机文件夹的 devcontainer.json 构建并启动容器、构建会运行文件夹的 Dockerfile、features 和命令所以文件夹必须受信任、Lithe 不额外挂载目录也不额外加参数。“选择文件夹…”打开系统文件夹选择,也可输入路径后按回车;相对路径、不存在的路径就地说明。读取文件夹时经 Core 的 remote.devcontainerConfigs 按规范顺序列出 .devcontainer/devcontainer.json、.devcontainer.json 和 .devcontainer 下一层文件夹里的配置,配置有 name 时显示“名称(路径)”,默认选第一个;没有配置时说明并且不能构建。容器引擎可选 Docker 或 Podman。同时读取文件夹的信任:未受信任时说明并把按钮换成“信任并构建”,先以与打开受信任项目相同的方式写入本机信任记录(记一次 workspace.trust.grant),再构建;读取信任失败时说明原因、不能构建。“构建并打开”经 remote.devcontainerUp 运行 CLI(带 projectCodeAllowed),CLI 的输出逐行显示在“构建日志”里(Core 已隐藏敏感信息,最多保留最近 5000 行,Core 截断时在下方说明),只显示、不写入 Lithe 的日志;构建期间左侧列表、配置、引擎和文件夹都不能改,底部显示“正在构建 dev container…”和“停止”。“停止”取消这次构建,日志保留并说明已经启动的容器会继续运行,不记失败;“取消”和关闭窗口也会先停止构建。找不到 devcontainer CLI 时说明用 npm 安装,CLI 报告失败时显示它的输出,超过一小时、结果里没有容器或工作区文件夹、文件夹不受信任分别说明,各记一次 remote_devcontainer_up 失败。成功后选中 CLI 返回的容器(重新读取容器列表,显示镜像),以 CLI 返回的 remoteUser 为容器内用户,按容器连接并直接打开 CLI 返回的工作区文件夹(与容器入口相同的信任询问、工作区、心跳与重连)。日志只有 remote.devcontainer.open/choose/build/stop、remote.connect 等动作,不含文件夹、配置名、容器名、用户名或 CLI 输出。测试替换的内核不运行本机的 devcontainer、docker 或 podman。运行 remote_devcontainer_test.go 的 5 个测试、internal/core 的 TestRemoteDevcontainer*,以及 TestVisualRemoteConnections 的 devcontainer 截图;装有 Dev Container CLI 的真实 Docker、Podman 上的整机验收仍待完成。在 SSH 主机或 WSL 发行版的文件夹选择里,标题栏的“主机上的容器”在文件夹的位置列出那台主机上 Docker 和 Podman 正在运行的容器(经浏览会话的 remote.listContainers 依次读取两个引擎,在远端服务的环境里运行,所以列出的容器就是能进入的;主机没有引擎命令行时说明没有找到 Docker 或 Podman,引擎报错时显示它的输出、不写日志),每行显示容器名、“引擎 · 镜像”和状态,可填写容器内用户(留空为镜像默认用户)。“进入容器”或双击一行结束浏览会话,重新连接主机并经主机上的引擎 exec 进入容器(OpenSSH 会再次询问它要问的内容;步骤与主机相同,地址显示为“主机 › 引擎:[用户@]容器”),随后在容器里选择文件夹;“返回文件夹”回到主机的文件夹。主机连不上或容器已停止、暂停、引擎没有应答时用同一段文字说明并点名引擎,具体原因在诊断输出里;没有“编辑连接”,“重试”进入同一台主机上的同一个容器。工作区身份为“已保存连接或发行版的身份/引擎:[用户@]容器”,窗口名为“容器名(主机名)”,不写入已保存的连接,打开过的文件夹不记入最近文件夹;信任记录包含主机与容器。Core 同样只进正在运行的容器,不提权、不改容器、不挂载(S32)。主机上不支持从 devcontainer.json 构建(devcontainer up 只在本机运行)。日志只有 remote.browse.containers/folders、remote.browse.container.enter、remote.connect 等动作和 remote_host_containers_list 失败名,不含主机、容器名、镜像、用户名或主机路径。运行 remote_host_containers_test.go 的 3 个测试和 TestVisualRemoteConnections 的主机容器截图;真实 SSH 主机与 Windows WSL 上的容器验收仍待完成。在远程工作区的标题栏选中程序或脚本运行配置点“运行”:程序在主机上启动(工作目录为主机文件夹下的相对目录,环境为主机登录环境加配置的变量),输出进入运行窗口,标签页带“主机”徽标;脚本写到主机临时目录,运行结束后删除;“停止”先发 SIGTERM,超过停止等待时间再强制结束;输出里的主机路径可点击并经占位路径在编辑器打开。配置的“执行前”列表里引用的其他程序或脚本运行配置按顺序在主机上先运行,步骤标题和输出写在同一个控制台,全部以 0 退出后才启动配置本身;某一步以非零退出码结束时说明步骤名和退出码,配置不启动;运行步骤时“停止”先给步骤的主机进程发 SIGTERM。列表里有插件提供的任务时说明远程工作区暂不支持插件任务,请从“执行前”列表删除后再运行。构建工具、插件提供的运行和调试在远程工作区说明暂不支持。", "legacy": { "revision": "5a54c41aa37a4e6e6b68918a4b05765b9dd07a36", "macos": { @@ -179,5 +189,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 上,会话丢失或失去信任时取消。 端口:remote.startForward/stopForward/forwards 与 ports.listening 都带会话发送;Core 只在本机 127.0.0.1 监听,请求的本机端口被占用时选空闲端口并返回 localPortChanged 与 requestedLocalPort;同一目标再次转发返回已有转发(created=false),所以更改本机端口是先停止再转发。顶部输入由 Core 的 remote.parseForwardAddress 解析为目标端口、主机、协议和路径,不连接主机;桌面端把网址的主机换成主机上提供该端口的回环地址再转发。非回环目标需 allowNonLoopback(S28),超过上限返回 forward_limit_reached 并带 maximum。读取在窗口的后台任务里进行,只在窗口打开且被绘制过时排下一次,不做空闲轮询。 转发规则:remote.startHostForward 让主机在回环地址(allInterfaces 时在全部网卡)监听并由主机连接目标,remote.startReverseForward 让主机只在回环地址监听、把每个连接带回本机回环地址上的端口;两者与 remote.startForward 共用会话转发上限,remote.forwards 用 kind 区分三种转发,端口窗口的端口列表只列本机转发。主机端口被占用、被拒绝、远端服务不支持和反向转发未允许分别是 forward_host_port_in_use、forward_host_port_denied、forward_host_unsupported、reverse_forward_disabled。remote.preferences 返回 reverseForwarding(来源与是否允许):打开对话框时据此决定是否提供反向方向,startReverseForward 也带上偏好文档由 Core 再校验一次。 WSL:remote.connect 的 connection 与 wsl 二选一,Core 经 wsl.exe --distribution … --exec 启动同一个远端服务,会话身份为 wsl:[用户@]发行版;桌面端的 remoteHost 在 SSH 连接与 WSL 发行版之间二选一,步骤、文件夹选择、信任、工作区和重连共用同一流程。remote.listWslDistributions 在 Windows 以外直接返回不可用,不运行任何程序。 远程工作区设置:Core 的 remote.preferences 读取偏好文档并解析 SSH 程序(found/missing/notExecutable)、~/.ssh/config 是否存在和重连间隔,remote.editPreferences 一次修改一个字段并返回新文档或 null(全部为自动时删除文件);桌面端只把文档按版本写到偏好目录的 remote/preferences.json(不超过 16 KiB),期间被改过时以冲突拒绝。每次连接、测试连接、读取有效设置和 SSH 配置导入都在后台重新读取文档并随请求发送;连接丢失时在后台读取重连间隔,读取失败时工作区保持断开并说明原因。页面的“自动(…)”另用不带文档的 remote.preferences 求出 Core 的默认值,所以保存了其他值时也能显示自动值。 关闭确认:连接都以常驻会话建立,Core 的 remote.connect 返回 sessionKey、sessionToken 和 resumed;关闭时 remote.runningPrograms 列出主机进程,remote.disconnect 带 programs=end/keep,keep 由 Core 发 server.keep,主机拒绝时返回错误、桌面端改为结束。保留的 sessionKey 与 sessionToken 按连接存入系统密钥存储(每个连接最多 8 条、整项不超过 2560 字节以适配 Windows 凭据管理器,最新的排最后),下次连接带上最新一条作为 resume;resumed=false 时忘掉这条。resumed 会话的 keptPrograms 在打开文件夹后列出,remote.endPrograms 按列出的 ID 只结束这些进程;空闲超时来自 Core 的 closing.idleTimeoutSeconds。记住的选择经 remote.editPreferences 的 closePrograms 写入同一份偏好文档。进程名称和命令只在对话框里显示,不写日志。 容器:remote.connect 的 container 单独出现时由 Core 在本机运行 exec -i [-u 用户] 容器 进入(S32:只进正在运行的容器,不提权、不改容器、不挂载),会话身份为 engine:[用户@]容器;container 跟在 connection 或 wsl 后面时 Core 在那台主机上、远端服务的非登录环境里运行同样的 exec,信任键包含主机与容器,remote.listContainers 带 sessionId 时也在那里列出。桌面端 remoteHost 由 SSH 连接或 WSL 发行版加可选的容器组成:overSSH() 决定是否发送 SSH 偏好、显示配置与认证步骤,saved() 决定是否提供编辑和记住文件夹,hosted() 区分主机上的容器(失败文字、重试目标)。列表键为 引擎:完整 ID,请求只发容器名。 devcontainer.json:Core 的 remote.devcontainerConfigs 只读文件夹并列出配置,remote.devcontainerUp 要求 projectCodeAllowed,在本机运行 devcontainer up(只传 --workspace-folder、选中的 --config,选 Podman 时加 --docker-path podman,不加挂载或其他参数),按流式事件返回已隐藏敏感信息的输出,结束时给出容器 ID、名称、remoteUser 和 remoteWorkspaceFolder;桌面端随后走与容器入口相同的 remote.connect 的 container 参数。未受信任的文件夹由桌面端先写本机信任记录再构建。 工作树:打开远程工作区的工作树等于用同一个连接打开另一个主机文件夹,每个文件夹一个会话、一个标签页,已有标签页的会话还活着时直接切换;新建对话框把仓库、目标和建议路径都用 remoteplaceholder.HostNamedPath 映射到占位根旁的 .lithe-remote-host 下发给 Core,Core 按仓库路径推出的建议也落在那里,显示前换回主机路径,所以不用改 Core 的建议和映射规则,Windows 与 WSL 上的主机路径也是本机绝对路径。 运行配置在远程工作区由 Core 路由到主机(runConfig.*,计划按主机平台生成),桌面端用 remote.runProcess 启动内置的程序和脚本运行,输出经有界缓冲(8 MiB,超出丢弃最旧部分并提示)进入运行窗口;进程 id 不是本机的,不采样端口和资源。“执行前”列表里的内置运行配置步骤同样经 remote.runProcess 在主机上运行(各自的临时目录在下一步开始前删除,停止或超出准备时间先发 SIGTERM);插件任务步骤、构建工具、插件运行和调试要在本机插件后端计划主机上的进程(#2231 R3/R4),本阶段不做。" + "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。读取在窗口的后台任务里进行,只在窗口打开且被绘制过时排下一次,不做空闲轮询。 转发规则:remote.startHostForward 让主机在回环地址(allInterfaces 时在全部网卡)监听并由主机连接目标,remote.startReverseForward 让主机只在回环地址监听、把每个连接带回本机回环地址上的端口;两者与 remote.startForward 共用会话转发上限,remote.forwards 用 kind 区分三种转发,端口窗口的端口列表只列本机转发。主机端口被占用、被拒绝、远端服务不支持和反向转发未允许分别是 forward_host_port_in_use、forward_host_port_denied、forward_host_unsupported、reverse_forward_disabled。remote.preferences 返回 reverseForwarding(来源与是否允许):打开对话框时据此决定是否提供反向方向,startReverseForward 也带上偏好文档由 Core 再校验一次。 WSL:remote.connect 的 connection 与 wsl 二选一,Core 经 wsl.exe --distribution … --exec 启动同一个远端服务,会话身份为 wsl:[用户@]发行版;桌面端的 remoteHost 在 SSH 连接与 WSL 发行版之间二选一,步骤、文件夹选择、信任、工作区和重连共用同一流程。remote.listWslDistributions 在 Windows 以外直接返回不可用,不运行任何程序。 远程工作区设置:Core 的 remote.preferences 读取偏好文档并解析 SSH 程序(found/missing/notExecutable)、~/.ssh/config 是否存在和重连间隔,remote.editPreferences 一次修改一个字段并返回新文档或 null(全部为自动时删除文件);桌面端只把文档按版本写到偏好目录的 remote/preferences.json(不超过 16 KiB),期间被改过时以冲突拒绝。每次连接、测试连接、读取有效设置和 SSH 配置导入都在后台重新读取文档并随请求发送;连接丢失时在后台读取重连间隔,读取失败时工作区保持断开并说明原因。页面的“自动(…)”另用不带文档的 remote.preferences 求出 Core 的默认值,所以保存了其他值时也能显示自动值。 关闭确认:连接都以常驻会话建立,Core 的 remote.connect 返回 sessionKey、sessionToken 和 resumed;关闭时 remote.runningPrograms 列出主机进程,remote.disconnect 带 programs=end/keep,keep 由 Core 发 server.keep,主机拒绝时返回错误、桌面端改为结束。保留的 sessionKey 与 sessionToken 按连接存入系统密钥存储(每个连接最多 8 条、整项不超过 2560 字节以适配 Windows 凭据管理器,最新的排最后),下次连接带上最新一条作为 resume;resumed=false 时忘掉这条。resumed 会话的 keptPrograms 在打开文件夹后列出,remote.endPrograms 按列出的 ID 只结束这些进程;空闲超时来自 Core 的 closing.idleTimeoutSeconds。记住的选择经 remote.editPreferences 的 closePrograms 写入同一份偏好文档。进程名称和命令只在对话框里显示,不写日志。 容器:remote.connect 的 container 单独出现时由 Core 在本机运行 exec -i [-u 用户] 容器 进入(S32:只进正在运行的容器,不提权、不改容器、不挂载),会话身份为 engine:[用户@]容器;container 跟在 connection 或 wsl 后面时 Core 在那台主机上、远端服务的非登录环境里运行同样的 exec,信任键包含主机与容器,remote.listContainers 带 sessionId 时也在那里列出。桌面端 remoteHost 由 SSH 连接或 WSL 发行版加可选的容器组成:overSSH() 决定是否发送 SSH 偏好、显示配置与认证步骤,saved() 决定是否提供编辑和记住文件夹,hosted() 区分主机上的容器(失败文字、重试目标)。列表键为 引擎:完整 ID,请求只发容器名。 devcontainer.json:Core 的 remote.devcontainerConfigs 只读文件夹并列出配置,remote.devcontainerUp 要求 projectCodeAllowed,在本机运行 devcontainer up(只传 --workspace-folder、选中的 --config,选 Podman 时加 --docker-path podman,不加挂载或其他参数),按流式事件返回已隐藏敏感信息的输出,结束时给出容器 ID、名称、remoteUser 和 remoteWorkspaceFolder;桌面端随后走与容器入口相同的 remote.connect 的 container 参数。未受信任的文件夹由桌面端先写本机信任记录再构建。 工作树:打开远程工作区的工作树等于用同一个连接打开另一个主机文件夹,每个文件夹一个会话、一个标签页,已有标签页的会话还活着时直接切换;新建对话框把仓库、目标和建议路径都用 remoteplaceholder.HostNamedPath 映射到占位根旁的 .lithe-remote-host 下发给 Core,Core 按仓库路径推出的建议也落在那里,显示前换回主机路径,所以不用改 Core 的建议和映射规则,Windows 与 WSL 上的主机路径也是本机绝对路径。 运行配置在远程工作区由 Core 路由到主机(runConfig.*,计划按主机平台生成),桌面端用 remote.runProcess 启动内置的程序和脚本运行,输出经有界缓冲(8 MiB,超出丢弃最旧部分并提示)进入运行窗口;进程 id 不是本机的,不采样端口和资源。“执行前”列表里的内置运行配置步骤同样经 remote.runProcess 在主机上运行(各自的临时目录在下一步开始前删除,停止或超出准备时间先发 SIGTERM);插件任务步骤、构建工具、插件运行和调试要在本机插件后端计划主机上的进程(#2231 R3/R4),本阶段不做。 端口记录:文件由 Core 校验、按连接目标与主机上工作区的真实路径分组,桌面端只按读到的字节整体原子替换(configfile),与读到时不一致就重读后重试;桌面端把内存状态和上次写入的记录比较得出编辑,所以停止、移除、改标签和规则启停都只写变化的部分;remote.restoreForwards 在每次接上会话(打开、重连)时按行重新转发,失败的单独报告,其余照常启动,规则从不自动启动。日志不记主机、标签、端口或转发地址。" }