diff --git a/.agents/notes/implemented/feature/2026-11-22-remote-workspace-close-keeps-host-programs.md b/.agents/notes/implemented/feature/2026-11-22-remote-workspace-close-keeps-host-programs.md new file mode 100644 index 000000000..557836288 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-11-22-remote-workspace-close-keeps-host-programs.md @@ -0,0 +1,113 @@ +# Agent 笔记:关闭远程工作区时确认远端进程,保留的会话下次接回 + +状态:已实现 + +## 先说结论 + +关闭远程工作区的窗口、标签、项目,退出 Lithe,或在同一窗口打开别的文件夹时,只要主机上还有 Lithe 为这个工作区启动的终端或进程,就先问用户:结束它们、保留在远端,还是取消。勾选“记住我的选择”后不再询问,只能在“设置 › 工具 › 远程工作区”的“关闭时的远端进程”改回。 + +选择保留时,主机上的会话继续运行;接回它所需的恢复凭据(会话键和令牌)按连接存进系统密钥存储。下次经同一连接或同一 WSL 发行版连接时自动接回,并列出上次保留的进程,让用户结束它们或继续运行。 + +开发者要记住三件事: +- 会话令牌只能进系统密钥存储,不能写进偏好文件或日志。 +- 保留失败时一律按“结束”处理,并且要告诉用户。 +- 进程名称和命令只在对话框里原样显示,不写进日志。 + +## 问题 + +Issue #2231 §9.1、§9.2 和 S33、S35 要求:关闭远程工作区不能悄悄结束用户在主机上跑着的程序(例如长时间的构建或 `npm run dev`),也不能悄悄留下用户找不到的程序。 + +原来的做法是“断开并关闭”直接结束主机会话。退出 Lithe 时也是关闭所有远程会话。这样用户的进程会被直接结束。 + +反过来,如果只是不结束进程,又会带来两个问题: +- 下次连接拿不到原来的会话,进程只能等主机的空闲超时结束; +- 用户也看不到哪些进程还在跑。 + +## 决策 + +### 什么时候问、问什么 + +- 询问放在本机的退出确认之后、拆掉项目之前。本机退出确认覆盖运行中的任务和忙碌的本机终端;拆项目会关闭工作区的终端,关掉终端就会挂断主机上的 shell。 +- 先经 Core 的 `remote.runningPrograms` 读取主机进程。列表为空就直接结束;读取失败也照常结束,并记一次失败。不能因为读不到列表就把用户困在窗口里。 +- 对话框原样列出每个进程的类型、名称、命令和已运行时长,不脱敏。这和本机退出确认弹窗的约定一致。 +- 按钮依次是“取消”“保留在远端并关闭”“结束并关闭”,默认按钮是“结束并关闭”。“记住我的选择”旁有 ⓘ,说明在哪里改回。 +- 记住的选择经 Core 的 `remote.editPreferences`(`closePrograms` 字段)写进同一份 `remote/preferences.json`,设置页读回同一个字段。这样不会有第二份影子配置。 + +### 保留怎么做 + +- 先停掉工作区自己的监听、Git 观察和端口转发,再从绑定上解开会话(`binding.Detach()`),让工作区不再向主机发任何请求。然后再拆项目,这样关闭终端不会挂断主机上的 shell。 +- **先存凭据,再让主机保留。** 存不下或者主机没给令牌时,改为 `remote.disconnect` 带 `programs=end`,并通知用户“无法保留”。否则主机会保留一个以后谁也接不回的会话。 +- 主机明确回答没有保留(`kept=false`)时忘掉这条凭据,并通知用户。主机没回答时凭据留着:主机可能已经保留了,下次连接发现主机上没有这个会话再忘掉。 +- 连接在保留前已经断开时,按结束处理并提示。没人接回的会话会在主机的空闲超时(Core 的 `closing.idleTimeoutSeconds`,默认 10 分钟)后结束,设置页只读显示这个时长。 + +### 凭据的存储与生命周期 + +`desktop/internal/remoteconn/kept.go` 负责凭据存储: +- **命名空间:** `@host/remote-sessions`。 +- **每个连接一项:** 账户名是连接 id 的 SHA-256 前 128 位,所以密钥存储的列表里看不出主机或发行版名。 +- **内容:** 秘密是该连接保留会话的 JSON 列表,最新的排在最后。 +- **上限:** 每个连接最多 8 条,整项不超过 Windows 凭据管理器的 2560 字节。保留第 9 个会话时忘掉最旧的一条,那条会话的进程就只能在主机上手动结束。 + +凭据的生命周期如下: +1. 连接时取最新一条作为 `resume` 发给 `remote.connect`。 +2. 无论接回与否,这条都作废:接回了,它就属于这次连接;没接回,说明主机上已经没有这个会话。 +3. 接回后(`resumed=true`),打开文件夹时列出 `keptPrograms`。“结束这些进程”经 `remote.endPrograms` 只结束这些 ID,不动这次新开的。 +4. 接回后没打开工作区就停止的连接,把会话再保留一次。这样进程不会在用户没选择的情况下结束。 + +### 日志 + +日志只记以下内容: +- 动作 `remote.close.cancel/keep/end` 和 `remote.kept.end/keep`; +- 失败的操作名,如 `remote_close_programs`、`remote_keep_programs`、`remote_kept_sessions`; +- Core 错误码。 + +日志不记连接名、主机、命令、进程名或令牌。 + +## 考虑过的备选方案 + +- **令牌写进 `remote/preferences.json` 或连接文件。** 被否:令牌是能接管主机会话的秘密,偏好文件可能被同步或备份。 +- **只在内存里记住保留的会话。** 被否:退出 Lithe 再打开就找不到会话了,正好违背“下次连接列出保留的进程”。 +- **先告诉主机保留,再存凭据。** 被否:存储失败时主机已经保留了一个没人能接回的会话,它的进程只能等空闲超时。 +- **保留失败时保持窗口打开,让用户重选。** 被否:用户已经决定关闭。这时按结束处理并说明原因,比把窗口卡住更可预期;需要保留的用户可以修好密钥存储后再试。 +- **记住的选择存在桌面端自己的设置里。** 被否:这样设置页和关闭逻辑会读两份配置;Core 的远程偏好已经是这些设置的唯一来源。 + +## 后果 + +- 收益: + - 主机上的程序不会被悄悄结束,也不会被悄悄遗留; + - 下次连接能看到并结束它们; + - 令牌只在系统密钥存储里; + - Windows 和 macOS 共用同一份 Go 代码。 +- 代价: + - 关闭远程工作区多一次 `remote.runningPrograms` 往返; + - 每个连接只接回最新一条保留会话,更早的要依次连接才能接回; + - 超过 8 条时最旧的会话无法从 Lithe 接回。 +- 保留的进程输出重新接回终端和运行窗口、真实 SSH 主机与 Windows 上的整机验收在后续阶段完成。 + +## 验证 + +- `desktop/internal/workbench/remote_close_test.go`: + - 主机没进程时不询问; + - 有进程时询问,取消后保留窗口; + - 保留后下次连接接回并列出进程,只结束列出的进程; + - 接回但没打开工作区时再保留; + - 记住选择后不再询问; + - 凭据存不下时结束并提示; + - 列表读取失败时照常关闭。 +- `desktop/internal/remoteconn/kept_test.go`:最新一条优先、同键替换与忘掉、超过上限时忘掉最旧的、解不开的秘密读作空列表。 +- `desktop/internal/settingswindow/remote_workspace_view_test.go` 的 `TestRemoteWorkspaceClosingChoiceIsAppliedAndRestored`:设置页写入并读回关闭选择。 +- `remote_close_visual_test.go` 生成 `docs/assets/remote-close/` 的截图,`remote_workspace_visual_test.go` 生成 `docs/assets/remote-settings/` 的关闭卡片截图。 + +```bash +scripts/desktop/desktop-go.sh test ./internal/workbench ./internal/remoteconn ./internal/settingswindow -run 'RemoteClose|Kept|RemoteWorkspace' -count=1 +``` + +## 适用范围 + +本 Note 覆盖以下代码: +- `desktop/internal/workbench/remote_close.go`; +- `desktop/internal/remoteconn/kept.go`; +- `desktop/internal/workbench/remote_browse.go` 和 `remote_workspace.go` 中接回会话的部分; +- 设置页“关闭工作区”卡片。 + +之后运行、构建等会在主机上启动进程的功能,也必须让 Core 把进程登记进 `remote.runningPrograms`,才会出现在关闭确认里。不要在桌面端另记一份进程列表。 diff --git a/desktop/internal/core/remote_preferences.go b/desktop/internal/core/remote_preferences.go index 53cf7582c..da3b19d13 100644 --- a/desktop/internal/core/remote_preferences.go +++ b/desktop/internal/core/remote_preferences.go @@ -34,7 +34,8 @@ type RemotePreferenceValues struct { SSHProgram *string `json:"sshProgram"` ReconnectLimitSeconds *uint32 `json:"reconnectLimitSeconds"` // AllowReverseForwarding is whether the Ports window may start reverse forwards. - AllowReverseForwarding *bool `json:"allowReverseForwarding"` + AllowReverseForwarding *bool `json:"allowReverseForwarding"` + ClosePrograms *RemoteClosePrograms `json:"closePrograms"` } // RemoteSSHProgram is the OpenSSH client Core starts. Path is nil only when the automatic @@ -53,6 +54,16 @@ type RemoteReconnect struct { DelaysMilliseconds []uint64 `json:"delaysMilliseconds"` } +// RemoteClosing is what closing a window does to the processes and terminals still running on +// the host. Programs is RemoteCloseAsk when automatic: the client asks every time. +// IdleTimeoutSeconds is how long the host keeps a session whose connection was lost and whose +// programs nobody kept; the remote server sets it, so no edit changes it. +type RemoteClosing struct { + Source RemotePreferenceSource `json:"source"` + Programs RemoteClosePrograms `json:"programs"` + IdleTimeoutSeconds uint64 `json:"idleTimeoutSeconds"` +} + // RemoteReverseForwarding is whether reverse forwards may start. The automatic value refuses // them, because a port a reverse forward opens is open to every user of the host. type RemoteReverseForwarding struct { @@ -79,6 +90,7 @@ type RemotePreferences struct { SSH RemoteSSHProgram `json:"ssh"` Reconnect RemoteReconnect `json:"reconnect"` Reverse RemoteReverseForwarding `json:"reverseForwarding"` + Closing RemoteClosing `json:"closing"` Storage RemotePreferenceStorage `json:"storage"` SSHConfig *RemoteSSHConfigFile `json:"sshConfig"` } @@ -94,15 +106,19 @@ func (c *Client) RemotePreferences(ctx context.Context, document *string, homeDi HomeDirectory string `json:"homeDirectory,omitempty"` }{document, homeDirectory}, &result) result.Reconnect.DelaysMilliseconds = nonNil(result.Reconnect.DelaysMilliseconds) + if result.Closing.Programs == "" { + result.Closing.Programs = RemoteCloseAsk + } return result, err } -// RemotePreferenceEdit changes one value: set exactly one field. A nil Path or Seconds makes the -// value automatic again. +// RemotePreferenceEdit changes one value: set exactly one field. A nil Path, Seconds or Programs +// makes the value automatic again. type RemotePreferenceEdit struct { SSHProgram *RemoteSSHProgramEdit `json:"sshProgram,omitempty"` ReconnectLimit *RemoteReconnectLimitEdit `json:"reconnectLimit,omitempty"` Reverse *RemoteReverseForwardingEdit `json:"reverseForwarding,omitempty"` + ClosePrograms *RemoteCloseProgramsEdit `json:"closePrograms,omitempty"` } // RemoteReverseForwardingEdit allows or refuses reverse forwards; a nil Allowed is automatic, @@ -111,6 +127,11 @@ type RemoteReverseForwardingEdit struct { Allowed *bool `json:"allowed"` } +// RemoteCloseProgramsEdit stores what closing a window does to the host's programs. +type RemoteCloseProgramsEdit struct { + Programs *RemoteClosePrograms `json:"programs"` +} + // RemoteSSHProgramEdit sets the SSH program to an absolute path of an executable file. type RemoteSSHProgramEdit struct { Path *string `json:"path"` diff --git a/desktop/internal/core/remote_session.go b/desktop/internal/core/remote_session.go index 7fcc2440d..c22c67a97 100644 --- a/desktop/internal/core/remote_session.go +++ b/desktop/internal/core/remote_session.go @@ -41,6 +41,18 @@ type RemoteConnectRequest struct { // Preferences is the remote workspace preference document, or nil. It names the SSH program; // a WSL connection ignores it. Preferences *string `json:"preferences,omitempty"` + // Resume attaches to the host session an earlier connection kept; nil starts a new session. + // Core refuses a malformed key or token as CodeInvalidRequest naming resume in + // RemoteConnectionFieldError, before anything starts, and connects once more without it when + // the host refuses the token. + Resume *RemoteResume `json:"resume,omitempty"` +} + +// RemoteResume names a host session an earlier connection kept, with the values its RemoteSession +// returned. Token is a secret: it is stored like a password and never logged. +type RemoteResume struct { + Key string `json:"key"` + Token string `json:"token"` } // WSLConnection is a distribution of the Windows Subsystem for Linux on this machine, as @@ -100,6 +112,47 @@ type RemoteSession struct { UserName string `json:"userName"` // HomeDirectory is that account's home directory, empty when unknown. HomeDirectory string `json:"homeDirectory"` + // SessionKey names the persistent session on the host, for a later Resume. + SessionKey string `json:"sessionKey"` + // SessionToken is the secret a later Resume presents, nil when the host issued none. It is + // stored like a password and never logged. + SessionToken *string `json:"sessionToken"` + // Resumed says this connection attached to the session Resume named; false after a Resume + // means that session had ended and a new one started. + Resumed bool `json:"resumed"` + // KeptPrograms are the processes and terminals the resumed session still runs, which an + // earlier connection kept; empty for a new session. + KeptPrograms []RemoteProgram `json:"keptPrograms"` +} + +// Resume is what a later connection presents to attach to this session again, nil when the host +// issued no token. +func (s RemoteSession) Resume() *RemoteResume { + if s.SessionKey == "" || s.SessionToken == nil || *s.SessionToken == "" { + return nil + } + return &RemoteResume{Key: s.SessionKey, Token: *s.SessionToken} +} + +// RemoteProgramKind says whether a host program is a process or a terminal. +type RemoteProgramKind string + +const ( + RemoteProgramProcess RemoteProgramKind = "process" + RemoteProgramTerminal RemoteProgramKind = "terminal" +) + +// RemoteProgram is a process or terminal a host session still runs. +type RemoteProgram struct { + Kind RemoteProgramKind `json:"kind"` + // ID is the id the program was started with, unique per kind. + ID uint64 `json:"id"` + // Argv is the program and its arguments, user content shown as it is and never logged. + Argv []string `json:"argv"` + // Label is the label the program was started with, or nil. + Label *RemoteResourceLabel `json:"label"` + // RunningMs is how long the program has run, on the host's clock. + RunningMs uint64 `json:"runningMs"` } // RemoteConnectResult is the outcome of remote.connect. Session is set only when Status is @@ -130,10 +183,18 @@ func (c *Client) RemoteConnect(ctx context.Context, request RemoteConnectRequest } if observationErr != nil { if result.Session != nil { - _, _ = c.RemoteDisconnect(context.Background(), result.Session.ID) + // A resumed session holds what the user kept, so it is left as it was. + programs := RemoteCloseEnd + if result.Session.Resumed { + programs = RemoteCloseKeep + } + _, _ = c.RemoteDisconnect(context.Background(), result.Session.ID, programs) } return RemoteConnectResult{}, observationErr } + if result.Session != nil { + result.Session.KeptPrograms = nonNil(result.Session.KeptPrograms) + } return result, nil } @@ -212,16 +273,79 @@ func (c *Client) executeRemoteWithPrompts(ctx context.Context, command string, p return c.ExecuteWithEvents(ctx, command, payload, result, observer) } -// RemoteDisconnect ends the session sessionID and its OpenSSH process tree. closed is false when -// Core no longer knew the session. -func (c *Client) RemoteDisconnect(ctx context.Context, sessionID string) (closed bool, err error) { +// RemoteClosePrograms is what closing a connection does to the processes and terminals its host +// session still runs. +type RemoteClosePrograms string + +const ( + // RemoteCloseAsk asks the user every time; it is the automatic choice. RemoteDisconnect + // treats it as RemoteCloseEnd. + RemoteCloseAsk RemoteClosePrograms = "ask" + // RemoteCloseEnd ends the host session with everything it runs. + RemoteCloseEnd RemoteClosePrograms = "end" + // RemoteCloseKeep tells the host to keep them, for a later RemoteResume. + RemoteCloseKeep RemoteClosePrograms = "keep" +) + +// RemoteDisconnectResult is what remote.disconnect did. Closed is false when Core no longer knew +// the session; Kept says the host keeps the session's programs, false for RemoteCloseEnd and when +// the host could not be told, whose programs then end after the server's idle timeout. +type RemoteDisconnectResult struct { + Closed bool `json:"closed"` + Kept bool `json:"kept"` +} + +// RemoteDisconnect closes the session sessionID and its OpenSSH or wsl.exe process tree, ending +// the host session with programs RemoteCloseEnd or keeping what it runs with RemoteCloseKeep. Core +// bounds the request to the host, so closing a window does not hang. +func (c *Client) RemoteDisconnect(ctx context.Context, sessionID string, programs RemoteClosePrograms) (RemoteDisconnectResult, error) { + if programs != RemoteCloseKeep { + programs = RemoteCloseEnd + } + var result RemoteDisconnectResult + err := c.Execute(ctx, "remote.disconnect", struct { + SessionID string `json:"sessionId"` + Programs RemoteClosePrograms `json:"programs"` + }{sessionID, programs}, &result) + return result, err +} + +// RemoteRunningPrograms lists the processes and terminals the host session of sessionID still +// runs, processes first. +func (c *Client) RemoteRunningPrograms(ctx context.Context, sessionID string) ([]RemoteProgram, error) { var result struct { - Closed bool `json:"closed"` + Programs []RemoteProgram `json:"programs"` } - err = c.Execute(ctx, "remote.disconnect", struct { + err := c.Execute(ctx, "remote.runningPrograms", struct { SessionID string `json:"sessionId"` }{sessionID}, &result) - return result.Closed, err + return nonNil(result.Programs), err +} + +// RemoteEndPrograms ends the processes and terminals the host session of sessionID runs, every +// one when programs is nil and otherwise those of programs, as RemoteRunningPrograms listed them: +// SIGTERM for each process session and a hang-up for each terminal. ended counts those that were +// still running; one that ignores the signal is still listed afterwards. +func (c *Client) RemoteEndPrograms(ctx context.Context, sessionID string, programs []RemoteProgram) (ended int, err error) { + type program struct { + Kind RemoteProgramKind `json:"kind"` + ID uint64 `json:"id"` + } + var named []program + if programs != nil { + named = make([]program, len(programs)) + for i, p := range programs { + named[i] = program{p.Kind, p.ID} + } + } + var result struct { + Ended int `json:"ended"` + } + err = c.Execute(ctx, "remote.endPrograms", struct { + SessionID string `json:"sessionId"` + Programs []program `json:"programs,omitempty"` + }{sessionID, named}, &result) + return result.Ended, err } // RemoteCloseAll ends every session Core keeps open and returns how many it closed. The diff --git a/desktop/internal/core/remote_session_test.go b/desktop/internal/core/remote_session_test.go index 92ce629e5..0ffa38059 100644 --- a/desktop/internal/core/remote_session_test.go +++ b/desktop/internal/core/remote_session_test.go @@ -97,11 +97,19 @@ func TestCoreRefusesUnadaptedCommandsAndAClosedSessionDetachesTheBinding(t *test func TestRemoteSessionCommandsOfAnUnknownSession(t *testing.T) { client := NewClient() ctx := testContext(t) - closed, err := client.RemoteDisconnect(ctx, "no-such-session") - if err != nil || closed { - t.Fatalf("disconnect = %v, %v, want nothing closed", closed, err) + for _, programs := range []RemoteClosePrograms{RemoteCloseEnd, RemoteCloseKeep, RemoteCloseAsk} { + result, err := client.RemoteDisconnect(ctx, "no-such-session", programs) + if err != nil || result.Closed || result.Kept { + t.Fatalf("disconnect %s = %+v, %v, want nothing closed or kept", programs, result, err) + } } var coreErr *Error + if programs, err := client.RemoteRunningPrograms(ctx, "no-such-session"); programs == nil || len(programs) != 0 || !errors.As(err, &coreErr) || coreErr.Code != CodeConnectionClosed { + t.Fatalf("runningPrograms = %d, %v, want an empty list and connection_closed", len(programs), err) + } + if ended, err := client.RemoteEndPrograms(ctx, "no-such-session", nil); ended != 0 || !errors.As(err, &coreErr) || coreErr.Code != CodeConnectionClosed { + t.Fatalf("endPrograms = %d, %v, want connection_closed", ended, err) + } if _, err := client.RemoteReadDir(ctx, "no-such-session", "/"); !errors.As(err, &coreErr) || coreErr.Code != CodeConnectionClosed { t.Fatalf("readDir = %v, want connection_closed", err) } diff --git a/desktop/internal/i18n/shared.generated.go b/desktop/internal/i18n/shared.generated.go index ed5bb1608..087d84514 100644 --- a/desktop/internal/i18n/shared.generated.go +++ b/desktop/internal/i18n/shared.generated.go @@ -1605,6 +1605,24 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.remote.choose": "Choose File…", "desktop.remote.chooseFailed": "Cannot open the file picker: {reason}", "desktop.remote.close": "Close", + "desktop.remote.close.end": "End and Close", + "desktop.remote.close.item": "• {kind} “{name}”: {command} ({duration})", + "desktop.remote.close.itemUnnamed": "• {kind}: {command} ({duration})", + "desktop.remote.close.keep": "Keep on Host and Close", + "desktop.remote.close.keepFailed": "Could not store the session of {connection}, so its programs ended with the workspace.", + "desktop.remote.close.keepLost": "The connection to {connection} was lost, so its programs could not be kept. The host ends them after its idle timeout.", + "desktop.remote.close.keepRefused": "{connection} did not confirm it kept the session. If it did not, the host ends its programs.", + "desktop.remote.close.kept": "Programs left running on {connection}: {count}", + "desktop.remote.close.kindProcess": "Process", + "desktop.remote.close.kindTerminal": "Terminal", + "desktop.remote.close.ranHours": "running for {hours} h {minutes} min", + "desktop.remote.close.ranMinutes": "running for {count} min", + "desktop.remote.close.ranUnderMinute": "running for less than a minute", + "desktop.remote.close.remember": "Remember my choice", + "desktop.remote.close.rememberFailed": "Could not remember this choice. Closing a remote workspace will ask again.", + "desktop.remote.close.rememberHelp": "Don't ask again. You can change this in Settings › Tools › Remote Workspace.", + "desktop.remote.close.running": "These programs are still running on {connection}:", + "desktop.remote.close.title": "Close the remote workspace?", "desktop.remote.color": "Color", "desktop.remote.color.blue": "Blue", "desktop.remote.color.green": "Green", @@ -1745,6 +1763,12 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.remote.keepAlive": "Keep-Alive (s)", "desktop.remote.keepAliveHelp": "How often OpenSSH checks that the server still answers (ServerAliveInterval), so a dropped network is noticed.", "desktop.remote.keepAlivePlaceholder": "Auto (SSH config)", + "desktop.remote.kept.end": "End Them", + "desktop.remote.kept.endFailed": "Could not end the programs kept on {connection}.", + "desktop.remote.kept.ended": "Ended programs on {connection}: {count}", + "desktop.remote.kept.keep": "Keep Running", + "desktop.remote.kept.text": "A closed window kept these programs running on {connection} ({count}):", + "desktop.remote.kept.title": "Programs Kept on the Host", "desktop.remote.kind.ssh": "SSH", "desktop.remote.listFooter": "{count} saved · on this computer only", "desktop.remote.menuItem": "Remote Development…", @@ -1977,11 +2001,20 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.remoteAuth.title": "SSH Authentication", "desktop.remoteSettings.chooseProgram": "Choose…", "desktop.remoteSettings.chooseProgramTitle": "Choose SSH Program", + "desktop.remoteSettings.closeAsk": "Automatic (ask every time)", + "desktop.remoteSettings.closeAskSaved": "Ask every time", + "desktop.remoteSettings.closeEnd": "End them", + "desktop.remoteSettings.closeKeep": "Keep on host", + "desktop.remoteSettings.closePrograms": "Host programs on close", + "desktop.remoteSettings.closeProgramsHelp": "What happens to the terminals and processes still running on the host when you close a remote workspace or its window, or quit Lithe. Kept programs are listed the next time you connect to the same host, where you can end them. Remember my choice in the close question changes this too.", + "desktop.remoteSettings.closing": "Closing", "desktop.remoteSettings.conflict": "The preference file changed meanwhile and was read again. Apply your change again.", "desktop.remoteSettings.connection": "Connection", "desktop.remoteSettings.damaged": "{path} cannot be read. Fix or delete the file; until then no host is connected with it.", "desktop.remoteSettings.failed": "The remote workspace settings could not be read or saved: {reason}", "desktop.remoteSettings.forwarding": "Port Forwarding", + "desktop.remoteSettings.idleTimeout": "Idle timeout of host sessions", + "desktop.remoteSettings.idleTimeoutHelp": "After a connection is lost, the host keeps its session and programs this long, so reconnecting picks them up; then it ends them. A session whose programs you kept on the host does not time out. The remote server sets this, so it cannot be changed.", "desktop.remoteSettings.keywords": "remote ssh openssh host server reconnect reconnection connection wsl", "desktop.remoteSettings.minutes": "{count} min", "desktop.remoteSettings.programAutomatic": "Automatic ({path})", @@ -5395,6 +5428,24 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.remote.choose": "选择文件…", "desktop.remote.chooseFailed": "无法打开文件选择器:{reason}", "desktop.remote.close": "关闭", + "desktop.remote.close.end": "结束并关闭", + "desktop.remote.close.item": "• {kind}“{name}”:{command}({duration})", + "desktop.remote.close.itemUnnamed": "• {kind}:{command}({duration})", + "desktop.remote.close.keep": "保留在远端并关闭", + "desktop.remote.close.keepFailed": "无法保存 {connection} 的会话,进程已随工作区结束。", + "desktop.remote.close.keepLost": "与 {connection} 的连接已断开,进程没能保留;主机会在空闲超时后结束它们。", + "desktop.remote.close.keepRefused": "{connection} 没有确认保留会话;如果没有保留,主机会结束这些进程。", + "desktop.remote.close.kept": "{count} 个进程保留在 {connection} 上", + "desktop.remote.close.kindProcess": "进程", + "desktop.remote.close.kindTerminal": "终端", + "desktop.remote.close.ranHours": "已运行 {hours} 小时 {minutes} 分钟", + "desktop.remote.close.ranMinutes": "已运行 {count} 分钟", + "desktop.remote.close.ranUnderMinute": "已运行不到 1 分钟", + "desktop.remote.close.remember": "记住我的选择", + "desktop.remote.close.rememberFailed": "没能记住这个选择,下次关闭远程工作区时仍会询问。", + "desktop.remote.close.rememberHelp": "之后不再询问,可在 设置 › 工具 › 远程工作区 中修改", + "desktop.remote.close.running": "以下进程仍在 {connection} 上运行:", + "desktop.remote.close.title": "关闭远程工作区?", "desktop.remote.color": "颜色", "desktop.remote.color.blue": "蓝色", "desktop.remote.color.green": "绿色", @@ -5535,6 +5586,12 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.remote.keepAlive": "保活间隔(秒)", "desktop.remote.keepAliveHelp": "OpenSSH 每隔多久确认一次服务器仍有响应(ServerAliveInterval),以便发现网络已断开。", "desktop.remote.keepAlivePlaceholder": "自动(SSH 配置)", + "desktop.remote.kept.end": "结束这些进程", + "desktop.remote.kept.endFailed": "无法结束 {connection} 上保留的进程。", + "desktop.remote.kept.ended": "已结束 {connection} 上的 {count} 个进程", + "desktop.remote.kept.keep": "继续运行", + "desktop.remote.kept.text": "上次关闭时保留在 {connection} 上的 {count} 个进程仍在运行:", + "desktop.remote.kept.title": "上次保留的进程", "desktop.remote.kind.ssh": "SSH", "desktop.remote.listFooter": "{count} 个连接 · 只保存在本机", "desktop.remote.menuItem": "远程开发…", @@ -5767,11 +5824,20 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.remoteAuth.title": "SSH 身份验证", "desktop.remoteSettings.chooseProgram": "选择…", "desktop.remoteSettings.chooseProgramTitle": "选择 SSH 程序", + "desktop.remoteSettings.closeAsk": "自动(每次询问)", + "desktop.remoteSettings.closeAskSaved": "每次询问", + "desktop.remoteSettings.closeEnd": "结束", + "desktop.remoteSettings.closeKeep": "保留在远端", + "desktop.remoteSettings.closePrograms": "关闭时的远端进程", + "desktop.remoteSettings.closeProgramsHelp": "关闭远程工作区、它的窗口或退出 Lithe 时,主机上仍在运行的终端和进程怎么处理。保留在远端的进程,下次连接同一主机时会列出来,可以再结束。关闭时勾选“记住我的选择”也会改这里。", + "desktop.remoteSettings.closing": "关闭工作区", "desktop.remoteSettings.conflict": "设置文件在此期间被改过,已重新读取。请再次应用你的修改。", "desktop.remoteSettings.connection": "连接", "desktop.remoteSettings.damaged": "无法读取 {path}。请修正或删除这个文件;修好之前不会用它连接主机。", "desktop.remoteSettings.failed": "无法读取或保存远程工作区设置:{reason}", "desktop.remoteSettings.forwarding": "端口转发", + "desktop.remoteSettings.idleTimeout": "常驻会话的空闲超时", + "desktop.remoteSettings.idleTimeoutHelp": "连接断开后,主机在这段时间内保留会话和其中的进程,期间重连会接回它们,超时后结束。选择保留在远端的会话不会超时。这个时长由远端服务决定,不能修改。", "desktop.remoteSettings.keywords": "远程 主机 服务器 重连 断线 连接 remote ssh openssh wsl", "desktop.remoteSettings.minutes": "{count} 分钟", "desktop.remoteSettings.programAutomatic": "自动({path})", diff --git a/desktop/internal/remoteconn/kept.go b/desktop/internal/remoteconn/kept.go new file mode 100644 index 000000000..960485256 --- /dev/null +++ b/desktop/internal/remoteconn/kept.go @@ -0,0 +1,123 @@ +package remoteconn + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "slices" + "sync" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" +) + +// A window closed with "Keep on Host" leaves its programs running in the host session, and the +// next connection to the same target resumes that session (#2231, §9.2). What resumes it is the +// session's key and token, which this file remembers in the platform secret store, one item per +// connection: the token is a secret, so it never goes into a preference file or the log. +// +// The item's account is a digest of the connection's id, so the store's list of items names no +// host or WSL distribution. Its secret is a JSON list of the connection's kept sessions, newest +// last. keptLimit caps the list so the item fits Windows Credential Manager's 2560 bytes: keeping a +// ninth session on one connection forgets the oldest, whose programs then run until they are ended +// on the host. Each connection presents one stored session: a connection resumes the newest, and +// whichever session it ends up with, the entry is forgotten; giving the session back without +// opening a workspace stores it again (workbench, remote_close.go). + +// KeptNamespace is the secret-store namespace of the kept sessions; "@host/" namespaces are the +// application's own and cannot clash with a plugin's id. +const KeptNamespace = "@host/remote-sessions" + +// keptLimit is how many kept sessions one connection remembers. +const keptLimit = 8 + +// KeptSecrets is the secret store the kept sessions are remembered in, credentials.Store in the +// application. Get reports found false for an item that is not there. +type KeptSecrets interface { + Get(ctx context.Context, namespace, key string) (string, bool, error) + Set(ctx context.Context, namespace, key, secret string) error + Delete(ctx context.Context, namespace, key string) error +} + +// keptLock makes each change of a connection's list one read and one write, so two windows of the +// application closing at once do not drop each other's session. +var keptLock sync.Mutex + +// keptAccount is the store's key of connectionID's item: "kept." and the first 128 bits of the +// id's SHA-256, which the store's key alphabet allows. +func keptAccount(connectionID string) string { + sum := sha256.Sum256([]byte(connectionID)) + return "kept." + hex.EncodeToString(sum[:16]) +} + +// readKept is connectionID's list, oldest first. A secret that does not decode holds no session +// that can be resumed, so it reads as an empty list, which the next change replaces. +func readKept(ctx context.Context, secrets KeptSecrets, connectionID string) ([]core.RemoteResume, error) { + secret, found, err := secrets.Get(ctx, KeptNamespace, keptAccount(connectionID)) + if err != nil || !found { + return nil, err + } + var kept []core.RemoteResume + if json.Unmarshal([]byte(secret), &kept) != nil { + return nil, nil + } + return slices.DeleteFunc(kept, func(resume core.RemoteResume) bool { return resume.Key == "" || resume.Token == "" }), nil +} + +// writeKept stores kept as connectionID's list, removing the item when it is empty. +func writeKept(ctx context.Context, secrets KeptSecrets, connectionID string, kept []core.RemoteResume) error { + account := keptAccount(connectionID) + if len(kept) == 0 { + return secrets.Delete(ctx, KeptNamespace, account) + } + secret, err := json.Marshal(kept) + if err != nil { + return err + } + return secrets.Set(ctx, KeptNamespace, account, string(secret)) +} + +// NewestKept is the session connectionID kept last, nil when it keeps none. +func NewestKept(ctx context.Context, secrets KeptSecrets, connectionID string) (*core.RemoteResume, error) { + keptLock.Lock() + defer keptLock.Unlock() + kept, err := readKept(ctx, secrets, connectionID) + if err != nil || len(kept) == 0 { + return nil, err + } + newest := kept[len(kept)-1] + return &newest, nil +} + +// RememberKept adds resume as connectionID's newest kept session, replacing an entry of the same +// key and forgetting the oldest beyond keptLimit. +func RememberKept(ctx context.Context, secrets KeptSecrets, connectionID string, resume core.RemoteResume) error { + keptLock.Lock() + defer keptLock.Unlock() + kept, err := readKept(ctx, secrets, connectionID) + if err != nil { + return err + } + kept = slices.DeleteFunc(kept, func(entry core.RemoteResume) bool { return entry.Key == resume.Key }) + kept = append(kept, resume) + if len(kept) > keptLimit { + kept = kept[len(kept)-keptLimit:] + } + return writeKept(ctx, secrets, connectionID, kept) +} + +// ForgetKept removes the session key from connectionID's list; forgetting one that is not there +// succeeds. +func ForgetKept(ctx context.Context, secrets KeptSecrets, connectionID, key string) error { + keptLock.Lock() + defer keptLock.Unlock() + kept, err := readKept(ctx, secrets, connectionID) + if err != nil { + return err + } + left := slices.DeleteFunc(slices.Clone(kept), func(entry core.RemoteResume) bool { return entry.Key == key }) + if len(left) == len(kept) { + return nil + } + return writeKept(ctx, secrets, connectionID, left) +} diff --git a/desktop/internal/remoteconn/kept_test.go b/desktop/internal/remoteconn/kept_test.go new file mode 100644 index 000000000..cf39f7f30 --- /dev/null +++ b/desktop/internal/remoteconn/kept_test.go @@ -0,0 +1,128 @@ +package remoteconn + +import ( + "context" + "fmt" + "regexp" + "strings" + "testing" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" +) + +// keptStore is a secret store held in a map, keyed by namespace and key. +type keptStore map[string]string + +func (s keptStore) Get(_ context.Context, namespace, key string) (string, bool, error) { + secret, found := s[namespace+"/"+key] + return secret, found, nil +} + +func (s keptStore) Set(_ context.Context, namespace, key, secret string) error { + s[namespace+"/"+key] = secret + return nil +} + +func (s keptStore) Delete(_ context.Context, namespace, key string) error { + delete(s, namespace+"/"+key) + return nil +} + +func resumeOf(n int) core.RemoteResume { + return core.RemoteResume{Key: fmt.Sprintf("key-%d", n), Token: fmt.Sprintf("token-%d", n)} +} + +// The newest kept session is the one a connection resumes; keeping one of the same key again +// moves it to the newest; forgetting removes it and the item once the list is empty. Each +// connection has its own list, under an account that names no connection. +func TestKeptSessionsNewestReplaceAndForget(t *testing.T) { + ctx, store := testContext(t), keptStore{} + if got, err := NewestKept(ctx, store, "build"); err != nil || got != nil { + t.Fatalf("a connection that kept nothing has %+v, %v", got, err) + } + for _, n := range []int{1, 2, 1} { + if err := RememberKept(ctx, store, "build", resumeOf(n)); err != nil { + t.Fatal(err) + } + } + if err := RememberKept(ctx, store, "other", resumeOf(9)); err != nil { + t.Fatal(err) + } + if got, _ := NewestKept(ctx, store, "build"); got == nil || *got != resumeOf(1) { + t.Fatalf("newest %+v, want the session kept again last", got) + } + if len(store) != 2 { + t.Fatalf("the store holds %d items, want one per connection", len(store)) + } + account := regexp.MustCompile(`^` + regexp.QuoteMeta(KeptNamespace) + `/kept\.[0-9a-f]{32}$`) + for item := range store { + if !account.MatchString(item) || strings.Contains(item, "build") || strings.Contains(item, "other") { + t.Fatal("an item's account is not a digest of the connection") + } + } + + if err := ForgetKept(ctx, store, "build", "key-1"); err != nil { + t.Fatal(err) + } + if got, _ := NewestKept(ctx, store, "build"); got == nil || *got != resumeOf(2) { + t.Fatalf("after forgetting the newest, newest %+v, want the one before", got) + } + if err := ForgetKept(ctx, store, "build", "key-absent"); err != nil { + t.Fatalf("forgetting a session that is not kept: %v", err) + } + if err := ForgetKept(ctx, store, "build", "key-2"); err != nil { + t.Fatal(err) + } + if got, _ := NewestKept(ctx, store, "build"); got != nil || len(store) != 1 { + t.Fatal("forgetting the last session did not remove the connection's item") + } +} + +// A connection remembers keptLimit sessions, forgetting the oldest beyond them. +func TestKeptSessionsForgetTheOldestBeyondTheLimit(t *testing.T) { + ctx, store := testContext(t), keptStore{} + for n := 1; n <= keptLimit+2; n++ { + if err := RememberKept(ctx, store, "build", resumeOf(n)); err != nil { + t.Fatal(err) + } + } + kept, err := readKept(ctx, store, "build") + if err != nil { + t.Fatal(err) + } + if len(kept) != keptLimit || kept[0] != resumeOf(3) || kept[len(kept)-1] != resumeOf(keptLimit+2) { + t.Fatalf("kept %d sessions from %+v, want the newest %d", len(kept), kept[0], keptLimit) + } + // The whole list fits Windows Credential Manager's 2560 bytes with keys and tokens of the size + // Core issues (32 and 43 characters). + long := make([]core.RemoteResume, keptLimit) + for i := range long { + long[i] = core.RemoteResume{Key: strings.Repeat("k", 32), Token: strings.Repeat("t", 43)} + long[i].Key = fmt.Sprintf("%d%s", i, long[i].Key[1:]) + } + if err := writeKept(ctx, store, "long", long); err != nil { + t.Fatal(err) + } + if secret, _, _ := store.Get(ctx, KeptNamespace, keptAccount("long")); len(secret) > 2560 { + t.Fatalf("a full list takes %d bytes", len(secret)) + } +} + +// A secret that does not decode, or holds entries without a key or a token, reads as no session, +// and the next keep replaces it. +func TestKeptSessionsIgnoreWhatDoesNotDecode(t *testing.T) { + ctx, store := testContext(t), keptStore{} + account := keptAccount("build") + for _, secret := range []string{"not json", `[{"key":"","token":"t"},{"key":"k","token":""}]`} { + _ = store.Set(ctx, KeptNamespace, account, secret) + if got, err := NewestKept(ctx, store, "build"); err != nil || got != nil { + t.Fatalf("%q reads as %+v, %v", secret, got, err) + } + } + if err := RememberKept(ctx, store, "build", resumeOf(1)); err != nil { + t.Fatal(err) + } + if got, _ := NewestKept(ctx, store, "build"); got == nil || *got != resumeOf(1) { + t.Fatalf("after a keep, newest %+v", got) + } +} diff --git a/desktop/internal/remoteconn/preferences.go b/desktop/internal/remoteconn/preferences.go index 7dede9f71..88c1a0b15 100644 --- a/desktop/internal/remoteconn/preferences.go +++ b/desktop/internal/remoteconn/preferences.go @@ -15,8 +15,8 @@ import ( // only the values the user changed, and only ever replaced whole, atomically, against the bytes // they were read from. They are never written to a host, a workspace, the app bundle or the // installation directory, so they do not affect code signing or Sparkle delta updates, and they -// are not copied across worktrees. They hold no secret, only the SSH program's path and the -// reconnect limit. +// are not copied across worktrees. They hold no secret, only the SSH program's path, the +// reconnect limit and what closing a window does to the host's programs. // PreferencesKernel is the part of the Core client the remote workspace preferences use. type PreferencesKernel interface { diff --git a/desktop/internal/remoteconn/preferences_test.go b/desktop/internal/remoteconn/preferences_test.go index 7149ec686..ef9e9b152 100644 --- a/desktop/internal/remoteconn/preferences_test.go +++ b/desktop/internal/remoteconn/preferences_test.go @@ -91,6 +91,33 @@ func TestRefusedPreferenceNamesTheField(t *testing.T) { } } +// What closing a window does to the host's programs asks by default, is stored as the user +// chooses it and asks again once made automatic. +func TestClosingChoiceIsStoredAndRestored(t *testing.T) { + ctx := testContext(t) + kernel := core.NewClient() + read, err := ReadPreferences(ctx, kernel, t.TempDir(), "") + if err != nil { + t.Fatal(err) + } + if closing := read.State.Closing; closing.Source != core.RemotePreferenceAutomatic || closing.Programs != core.RemoteCloseAsk || closing.IdleTimeoutSeconds != 600 || read.State.Preferences.ClosePrograms != nil { + t.Fatalf("automatic closing = %+v", closing) + } + keep := core.RemoteCloseKeep + kept, committed, err := read.Edit(ctx, kernel, core.RemotePreferenceEdit{ClosePrograms: &core.RemoteCloseProgramsEdit{Programs: &keep}}) + if err != nil || !committed { + t.Fatalf("keep: committed = %v, err = %v", committed, err) + } + stored := kept.State.Preferences.ClosePrograms + if closing := kept.State.Closing; closing.Source != core.RemotePreferenceFromSetting || closing.Programs != core.RemoteCloseKeep || stored == nil || *stored != keep { + t.Fatalf("kept closing = %+v", closing) + } + asked, committed, err := kept.Edit(ctx, kernel, core.RemotePreferenceEdit{ClosePrograms: &core.RemoteCloseProgramsEdit{}}) + if err != nil || !committed || asked.State.Closing.Source != core.RemotePreferenceAutomatic || asked.State.Closing.Programs != core.RemoteCloseAsk { + t.Fatalf("automatic again: committed = %v, closing = %+v, err = %v", committed, asked.State.Closing, err) + } +} + // A saved program that is executable takes effect; one that later disappears is reported, not // treated as a damaged document. func TestSavedProgramIsReportedWhenItDisappears(t *testing.T) { diff --git a/desktop/internal/settingswindow/remote_preferences_state.go b/desktop/internal/settingswindow/remote_preferences_state.go index bf529c43f..79a0e365e 100644 --- a/desktop/internal/settingswindow/remote_preferences_state.go +++ b/desktop/internal/settingswindow/remote_preferences_state.go @@ -47,14 +47,16 @@ type remotePreferencesState struct { damagedPath string source RemotePreferences - // program, limit and reverse are the drafts; set says the user changed the value, and a nil - // value drafts Automatic. + // program, limit, reverse and closing are the drafts; set says the user changed the value, + // and a nil value drafts Automatic. program *string programSet bool limit *uint32 limitSet bool reverse *bool reverseSet bool + closing *core.RemoteClosePrograms + closingSet bool saveEffect *ui.EffectState[RemotePreferences, int] saveKey int @@ -160,11 +162,35 @@ func (r *remotePreferencesState) setLimit(seconds *uint32) { r.limit, r.limitSet = seconds, !sameUint32(seconds, r.source.Saved.State.Preferences.ReconnectLimitSeconds) } -func sameString(a, b *string) bool { return (a == nil) == (b == nil) && (a == nil || *a == *b) } +// shownClosing is what closing a workspace does to the host's programs as the page shows it: the +// draft, or the saved choice; nil is Automatic, which asks every time. +func (r *remotePreferencesState) shownClosing() *core.RemoteClosePrograms { + if r.closingSet { + return r.closing + } + return r.source.Saved.State.Preferences.ClosePrograms +} + +// setClosing drafts the closing choice, nil for Automatic; choosing the saved value drops the +// draft. +func (r *remotePreferencesState) setClosing(programs *core.RemoteClosePrograms) { + if !r.available() || !r.loaded || r.busy() { + return + } + r.failed = nil + r.closing, r.closingSet = programs, !samePointer(programs, r.source.Saved.State.Preferences.ClosePrograms) +} -func sameUint32(a, b *uint32) bool { return (a == nil) == (b == nil) && (a == nil || *a == *b) } +func sameString(a, b *string) bool { return samePointer(a, b) } -func sameBool(a, b *bool) bool { return (a == nil) == (b == nil) && (a == nil || *a == *b) } +func sameUint32(a, b *uint32) bool { return samePointer(a, b) } + +// samePointer says a and b are both nil or point to equal values. +func samePointer[T comparable](a, b *T) bool { + return (a == nil) == (b == nil) && (a == nil || *a == *b) +} + +func sameBool(a, b *bool) bool { return samePointer(a, b) } func (r *remotePreferencesState) drafts() int { if !r.available() { @@ -180,6 +206,9 @@ func (r *remotePreferencesState) drafts() int { if r.reverseSet { n++ } + if r.closingSet { + n++ + } return n } @@ -195,6 +224,9 @@ func (r *remotePreferencesState) edits() []core.RemotePreferenceEdit { if r.reverseSet { edits = append(edits, core.RemotePreferenceEdit{Reverse: &core.RemoteReverseForwardingEdit{Allowed: r.reverse}}) } + if r.closingSet { + edits = append(edits, core.RemotePreferenceEdit{ClosePrograms: &core.RemoteCloseProgramsEdit{Programs: r.closing}}) + } return edits } @@ -222,6 +254,9 @@ func (r *remotePreferencesState) keepChanged() { if r.reverseSet && sameBool(r.reverse, stored.AllowReverseForwarding) { r.reverse, r.reverseSet = nil, false } + if r.closingSet && samePointer(r.closing, stored.ClosePrograms) { + r.closing, r.closingSet = nil, false + } } // take applies the page's finished requests and reports a write that failed, so the footer's @@ -251,6 +286,7 @@ func (r *remotePreferencesState) take() (saveFailed error) { r.source, r.loaded, r.stale = source, true, false r.program, r.programSet, r.limit, r.limitSet = nil, false, nil, false r.reverse, r.reverseSet = nil, false + r.closing, r.closingSet = nil, false } } return saveFailed diff --git a/desktop/internal/settingswindow/remote_workspace_view.go b/desktop/internal/settingswindow/remote_workspace_view.go index 27a1a92fc..55ff959a5 100644 --- a/desktop/internal/settingswindow/remote_workspace_view.go +++ b/desktop/internal/settingswindow/remote_workspace_view.go @@ -47,6 +47,10 @@ func (w *window) remoteWorkspacePage(c ui.C) { w.card(c.Part("forwarding"), i18n.Shared(language, "desktop.remoteSettings.forwarding"), "", func() { w.remoteReverseRow(c.Part("reverse"), language, r) }) + w.card(c.Part("closing"), i18n.Shared(language, "desktop.remoteSettings.closing"), "", func() { + w.remoteCloseRow(c.Part("close-programs"), language, r) + w.remoteIdleTimeoutRow(c.Part("idle-timeout"), language, r) + }) w.card(c.Part("storage"), i18n.Shared(language, "desktop.remoteSettings.storage"), "", func() { title := i18n.Shared(language, "desktop.remoteSettings.storage") note := "" @@ -217,7 +221,58 @@ func (w *window) remoteReverseRow(c ui.C, language i18n.Language, r *remotePrefe }) } -// remoteDuration is a reconnect time in whole minutes when it is one, else in seconds. +// remoteCloseRow chooses what closing a remote workspace does to the programs still running on +// the host: Automatic, which asks every time, End them or Keep on host. A saved "ask" is listed +// as its own choice so the row shows what the file holds; Remember my choice in the close +// question writes End or Keep here (workbench, remote_close.go). +func (w *window) remoteCloseRow(c ui.C, language i18n.Language, r *remotePreferencesState) { + title := i18n.Shared(language, "desktop.remoteSettings.closePrograms") + value := core.RemoteClosePrograms("") + if shown := r.shownClosing(); shown != nil { + value = *shown + } + choices := []core.RemoteClosePrograms{"", core.RemoteCloseEnd, core.RemoteCloseKeep} + for _, programs := range []*core.RemoteClosePrograms{r.source.Saved.State.Preferences.ClosePrograms, r.shownClosing()} { + if programs != nil && !slices.Contains(choices, *programs) { + choices = append(choices, *programs) + } + } + label := func(programs core.RemoteClosePrograms) string { + switch programs { + case "": + return i18n.Shared(language, "desktop.remoteSettings.closeAsk") + case core.RemoteCloseEnd: + return i18n.Shared(language, "desktop.remoteSettings.closeEnd") + case core.RemoteCloseKeep: + return i18n.Shared(language, "desktop.remoteSettings.closeKeep") + } + return i18n.Shared(language, "desktop.remoteSettings.closeAskSaved") + } + w.settingsRow(c, title, i18n.Shared(language, "desktop.remoteSettings.closeProgramsHelp"), func() { + if ui.Select(c.Part("programs"), &value, choices, label).FillWidth().Label(title).Disabled(r.busy()).Changed() { + if value == "" { + r.setClosing(nil) + } else { + programs := value + r.setClosing(&programs) + } + } + }) +} + +// remoteIdleTimeoutRow shows how long the host keeps a session whose connection was lost, as the +// remote server reports it; nothing on this machine changes it. +func (w *window) remoteIdleTimeoutRow(c ui.C, language i18n.Language, r *remotePreferencesState) { + seconds := r.source.Saved.State.Closing.IdleTimeoutSeconds + if seconds == 0 { + return + } + w.settingsRow(c, i18n.Shared(language, "desktop.remoteSettings.idleTimeout"), i18n.Shared(language, "desktop.remoteSettings.idleTimeoutHelp"), func() { + ui.Text(c.Part("value"), remoteDuration(language, int(seconds))).FontSize(12).Color(w.pal.text) + }) +} + +// remoteDuration is a time in whole minutes when it is one, else in seconds. func remoteDuration(language i18n.Language, seconds int) string { if seconds >= 60 && seconds%60 == 0 { return i18n.SharedFormat(language, "desktop.remoteSettings.minutes", map[string]string{"count": strconv.Itoa(seconds / 60)}) diff --git a/desktop/internal/settingswindow/remote_workspace_view_test.go b/desktop/internal/settingswindow/remote_workspace_view_test.go index afb430a70..78b3819f0 100644 --- a/desktop/internal/settingswindow/remote_workspace_view_test.go +++ b/desktop/internal/settingswindow/remote_workspace_view_test.go @@ -223,3 +223,44 @@ func TestRemoteWorkspaceReverseForwardingIsAppliedAndRestored(t *testing.T) { t.Fatalf("reverse = %+v: Automatic was not restored", reverse) } } + +// The Closing card shows Automatic, which asks every time, and the host's idle timeout Core +// reports; choosing Keep on host is a draft Apply writes, and the row then shows the saved choice. +// Choosing Automatic again removes it from the file. +func TestRemoteWorkspaceClosingChoiceIsAppliedAndRestored(t *testing.T) { + loader := newCorePreferencesLoader(t) + w, d, r := remoteWorkspaceWindow(t, loader) + if !d.text(en("desktop.remoteSettings.closeAsk")) || !d.text(en("desktop.remoteSettings.closePrograms")) { + t.Fatal("the closing row does not show that closing asks every time") + } + if !d.text(en("desktop.remoteSettings.idleTimeout")) || !d.text(remoteDuration(i18n.English, 600)) { + t.Fatal("the idle timeout row does not show the host's ten minutes") + } + keep := core.RemoteCloseKeep + r.setClosing(&keep) + d.w.inv.Invalidate() + d.pump() + if r.drafts() != 1 { + t.Fatalf("drafts = %d, want the closing choice", r.drafts()) + } + d.click(en("desktop.buildSettings.apply")) + d.until("the apply to end", func() bool { return !w.apply.active() && !r.busy() }) + d.pump() + closing := r.source.Saved.State.Closing + if r.failed != nil || r.drafts() != 0 || closing.Source != core.RemotePreferenceFromSetting || closing.Programs != core.RemoteCloseKeep { + t.Fatalf("failed = %v, drafts = %d, closing = %+v", r.failed, r.drafts(), closing) + } + if !d.text(en("desktop.remoteSettings.closeKeep")) { + t.Fatal("the row does not show the saved choice") + } + + r.setClosing(nil) + d.w.inv.Invalidate() + d.pump() + d.click(en("desktop.buildSettings.apply")) + d.until("the second apply to end", func() bool { return !w.apply.active() && !r.busy() }) + d.pump() + if r.source.Saved.State.Preferences.ClosePrograms != nil || r.source.Saved.State.Closing.Programs != core.RemoteCloseAsk { + t.Fatal("Automatic was not restored") + } +} diff --git a/desktop/internal/settingswindow/remote_workspace_visual_test.go b/desktop/internal/settingswindow/remote_workspace_visual_test.go index b8b0369be..2cf68a9f2 100644 --- a/desktop/internal/settingswindow/remote_workspace_visual_test.go +++ b/desktop/internal/settingswindow/remote_workspace_visual_test.go @@ -7,12 +7,14 @@ import ( "path/filepath" "testing" + "github.com/1lck/Lithe-IDEA/desktop/internal/core" "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" "github.com/vivaui/viva/headless" ) // TestVisualRemoteWorkspace renders the Remote Workspace page under Tools: the automatic values as -// Core resolves them on this machine, then drafts that choose an SSH program and a reconnect time. +// Core resolves them on this machine, then drafts that choose an SSH program and a reconnect time, +// and one that keeps the host's programs when a workspace closes. // The preference directory is a test directory and the home directory is fictional. func TestVisualRemoteWorkspace(t *testing.T) { out := os.Getenv("LITHE_VISUAL_OUTPUT_DIR") @@ -59,6 +61,14 @@ func TestVisualRemoteWorkspace(t *testing.T) { r.setLimit(&seconds) d.until("the drafts to be painted", func() bool { return d.text(program) }) shot("drafts") + // Closing a remote workspace keeps the host's programs instead of asking. + keep := core.RemoteCloseKeep + r.setClosing(&keep) + d.w.inv.Invalidate() + d.until("the closing draft to be painted", func() bool { + return d.text(i18n.Shared(language, "desktop.remoteSettings.closeKeep")) + }) + shot("closing") }) } } diff --git a/desktop/internal/workbench/app.go b/desktop/internal/workbench/app.go index b802aed3e..275140390 100644 --- a/desktop/internal/workbench/app.go +++ b/desktop/internal/workbench/app.go @@ -40,6 +40,7 @@ import ( "github.com/1lck/Lithe-IDEA/desktop/internal/pluginpkg" "github.com/1lck/Lithe-IDEA/desktop/internal/pluginservice" "github.com/1lck/Lithe-IDEA/desktop/internal/projectgen" + "github.com/1lck/Lithe-IDEA/desktop/internal/remoteconn" "github.com/1lck/Lithe-IDEA/desktop/internal/remoteserver" "github.com/1lck/Lithe-IDEA/desktop/internal/settingswindow" "github.com/1lck/Lithe-IDEA/desktop/internal/store" @@ -215,7 +216,9 @@ type Kernel interface { RemoteListWSLDistributions(ctx context.Context) (core.RemoteWSLDistributions, error) RemoteAuthRespond(ctx context.Context, requestID string, answer *string) (bool, error) RemoteConnect(ctx context.Context, request core.RemoteConnectRequest) (core.RemoteConnectResult, error) - RemoteDisconnect(ctx context.Context, sessionID string) (bool, error) + RemoteDisconnect(ctx context.Context, sessionID string, programs core.RemoteClosePrograms) (core.RemoteDisconnectResult, error) + RemoteRunningPrograms(ctx context.Context, sessionID string) ([]core.RemoteProgram, error) + RemoteEndPrograms(ctx context.Context, sessionID string, programs []core.RemoteProgram) (int, error) RemoteCloseAll(ctx context.Context) (int, error) RemoteReadDir(ctx context.Context, sessionID, path string) (core.RemoteDirectory, error) RemoteStat(ctx context.Context, sessionID, path string) (core.RemoteFileMetadata, error) @@ -814,6 +817,9 @@ type App struct { remoteBundle func() (remoteserver.Bundle, error) remoteAnchor func() (string, error) remoteAfter func(time.Duration, func()) func() bool + // remoteKeptSecrets replaces the platform secret store the kept host sessions are remembered + // in (remote_close.go); tests set it. + remoteKeptSecrets remoteconn.KeptSecrets // gitAuth holds the questions of the Git operations the user started (git_auth.go). gitAuth gitAuthState newProject newProjectState @@ -1768,7 +1774,10 @@ func (a *App) requestCloseProject(after func()) { if after != nil { lifecycle = exitContextQuit } - a.confirmProcessExit(p, lifecycle, func() { a.finishCloseProject(p, after) }) + a.confirmProcessExit(p, lifecycle, func() { + // A remote workspace then decides the programs its host runs (remote_close.go). + a.confirmRemoteClose(p, func() { a.finishCloseProject(p, after) }) + }) }) } diff --git a/desktop/internal/workbench/app_test.go b/desktop/internal/workbench/app_test.go index 084c799f8..e10e26444 100644 --- a/desktop/internal/workbench/app_test.go +++ b/desktop/internal/workbench/app_test.go @@ -106,6 +106,8 @@ func newHarnessWithDriver(t testing.TB, options Options, open func(app.Config) ( options.DisablePluginRecommendations = true } h.app = New(options) + // Kept host sessions are remembered in memory, never in this computer's secret store. + h.app.remoteKeptSecrets = &memoryKeptSecrets{} h.config = h.app.Config() driver, closeDriver, err := open(h.config) if err != nil { diff --git a/desktop/internal/workbench/pluginprompt.go b/desktop/internal/workbench/pluginprompt.go index 529b1c574..596744dd0 100644 --- a/desktop/internal/workbench/pluginprompt.go +++ b/desktop/internal/workbench/pluginprompt.go @@ -4,6 +4,7 @@ import ( "context" "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/1lck/Lithe-IDEA/desktop/internal/icons" "github.com/1lck/Lithe-IDEA/desktop/internal/pluginservice" "github.com/vivaui/viva/ui" ) @@ -21,9 +22,11 @@ type pluginPrompt struct { mono bool actions []string // check, when set, is the label of a checkbox under the text, such as "Don't ask - // again"; checked is its state, which onAnswer reads. - check string - checked bool + // again"; checked is its state, which onAnswer reads. checkHelp, when set, is shown by an + // information button beside it. + check string + checked bool + checkHelp string // open is the flag the modal that shows the prompt keeps. open bool // answer receives the chosen index, or nil for a dismissal. It is buffered, so @@ -125,7 +128,13 @@ func (a *App) pluginPromptView(c ui.C) { } }) if prompt.check != "" { - ui.Checkbox(c.Part("check"), &prompt.checked, prompt.check) + ui.Row(c.Part("checkRow")).Items(ui.Center).Gap(4).Children(func() { + ui.Checkbox(c.Part("check"), &prompt.checked, prompt.check) + if prompt.checkHelp != "" { + ui.Button(c.Part("checkHelp"), i18n.Shared(a.language(), "native.moreInformation")).Icon(icons.Info).IconOnly().Ghost().Size(18, 18).Shrink(0). + Tooltip(prompt.checkHelp) + } + }) } }, func() { for i, action := range prompt.actions { diff --git a/desktop/internal/workbench/remote_browse.go b/desktop/internal/workbench/remote_browse.go index 567d37eff..644fed17a 100644 --- a/desktop/internal/workbench/remote_browse.go +++ b/desktop/internal/workbench/remote_browse.go @@ -108,17 +108,29 @@ func (a *App) connectRemote(folder string) { } }) }) - generation, kernel, root := r.generation, a.kernel, a.globalToolchainRoot() + generation, kernel, root, secrets := r.generation, a.kernel, a.globalToolchainRoot(), a.remoteSecrets() a.background(nil, 0, func(context.Context) func(*App) { defer cancel() - result, err := a.connectRemoteHost(a.gitAuthentication(ctx), kernel, root, host) + // A session a window closed with "Keep on Host" resumes (§9.2). Whichever session the + // connection ends up with, the stored one is spent: resumed, it is this connection's; not + // resumed, the host no longer has it. + resume, keptErr := remoteconn.NewestKept(ctx, secrets, entry.ID) + result, err := a.connectRemoteHost(a.gitAuthentication(ctx), kernel, root, host, resume) + if resume != nil && result.Session != nil { + if forgetErr := remoteconn.ForgetKept(ctx, secrets, entry.ID, resume.Key); keptErr == nil { + keptErr = forgetErr + } + } return func(a *App) { + if keptErr != nil { + a.backgroundFailed("remote_kept_sessions", keptErr) + } r := &a.remote if !r.open || r.generation != generation || r.connect != attempt { if result.Session != nil { - a.releaseRemoteSession(result.Session.ID) + a.returnRemoteSession(entry.ID, *result.Session) } - // log-exempt: 用户取消:连接已停止、换了连接或窗口已关闭,已打开的会话随即结束。 + // log-exempt: 用户取消:连接已停止、换了连接或窗口已关闭,已打开的会话随即交还。 return } r.connect = nil @@ -131,7 +143,7 @@ func (a *App) connectRemote(folder string) { return } if result.Session != nil { - a.releaseRemoteSession(result.Session.ID) + a.returnRemoteSession(entry.ID, *result.Session) } if field, reason, ok := core.RemoteConnectionFieldError(err); ok { a.operationRejected("remote_connect", "field_refused") @@ -191,12 +203,12 @@ func (a *App) browseRemote(entry core.SavedRemoteConnection, host remoteHost, se a.listRemoteFolder(path.Clean(start)) } -// leaveRemoteBrowser stops choosing a folder and ends its session. +// leaveRemoteBrowser stops choosing a folder and gives its session back (returnRemoteSession). func (a *App) leaveRemoteBrowser() { r := &a.remote if b := r.browser; b != nil { r.browser = nil - a.releaseRemoteSession(b.session.ID) + a.returnRemoteSession(b.entryID, b.session) } } @@ -485,10 +497,11 @@ func (a *App) openRemoteWorkspace(target remoteTarget) { p := open.project if r := p.remote; r != nil && !r.closed && r.session == "" && r.reconnecting == nil { r.stopRemoteTimer() - open.attachRemote(p, target.session.ID) + open.attachRemote(p, target.session) open.refreshRemoteTree(p) + open.offerKeptPrograms(p, target.session) } else { - a.releaseRemoteSession(target.session.ID) + a.returnRemoteSession(target.connectionID, target.session) } open.applyProjectTrust(p, target.trusted) return diff --git a/desktop/internal/workbench/remote_close.go b/desktop/internal/workbench/remote_close.go new file mode 100644 index 000000000..c7eaf0ae1 --- /dev/null +++ b/desktop/internal/workbench/remote_close.go @@ -0,0 +1,410 @@ +package workbench + +import ( + "context" + "errors" + "strconv" + "strings" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/credentials" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/1lck/Lithe-IDEA/desktop/internal/remoteconn" +) + +// Closing a remote workspace decides what happens to the programs it started on the host (#2231, +// §9.1): the shells of its terminals and the processes it runs there. While the host still runs +// any, closing the project, its tab or the window, quitting Lithe or opening another folder in its +// place asks whether they end with the workspace or keep running on the host, unless the user +// once chose with "Remember my choice"; Settings › Tools › Remote Workspace changes that choice. +// +// Keeping them leaves the host session running with no connection and no idle timeout, and +// remembers its resume token in the platform secret store (remoteconn.RememberKept). The next +// connection to the same target attaches to it again and offers to end the programs it still +// runs (§9.2, S35); a connection that gives such a session back without opening a workspace keeps +// it again, so they never end without the user choosing it. +// +// The question comes after the local exit confirmation, which covers the runs and the busy local +// terminals, and before the project is taken apart. Taking it apart closes the workspace's +// terminals, which hangs up their shells on the host, so a keep detaches the connection first. + +// remoteProgramsTimeout bounds listing or ending the programs the host runs. +const remoteProgramsTimeout = remoteDisconnectTimeout + +var ( + // errRemoteNoResumeToken: the host issued no token for its session, so a later connection + // could not attach to it and keeping it would leave its programs out of reach. + errRemoteNoResumeToken = errors.New("remote keep: the host issued no resume token") + // errRemoteNotKept: the host closed the connection without keeping the session. + errRemoteNotKept = errors.New("remote keep: the host did not keep the session") +) + +// remoteSecrets is the secret store the kept host sessions are remembered in. +func (a *App) remoteSecrets() remoteconn.KeptSecrets { + if a.remoteKeptSecrets != nil { + return a.remoteKeptSecrets + } + return credentials.Default() +} + +// shownWorkbench is the workbench the window shows: a notification of a tab that is closing goes +// to the one shown in its place. +func (a *App) shownWorkbench() *App { + if a.sessions != nil && a.sessions.active != nil { + return a.sessions.active + } + return a +} + +// confirmRemoteClose decides the programs the host runs for the remote workspace p before its +// project closes, then calls proceed. A local project, or a remote one without a session, goes on +// at once. With no programs running, or a remembered "End", proceed runs and taking the project +// apart ends the session; a remembered "Keep on Host" keeps them; otherwise the user is asked. A +// list that cannot be had is no reason to trap the user in the window: proceed runs and the error +// is logged. +func (a *App) confirmRemoteClose(p *project, proceed func()) { + r := p.remote + if r == nil || r.closed || r.session == "" { + proceed() + return + } + if r.leaving { + // log-exempt: 用户重复操作:这次关闭的决定已经在进行,先开始的那次会接着关闭。 + return + } + r.leaving = true + session, kernel, root := r.session, a.kernel, a.globalToolchainRoot() + a.background(nil, remoteProgramsTimeout, func(ctx context.Context) func(*App) { + programs, err := kernel.RemoteRunningPrograms(ctx, session) + choice, choiceErr := core.RemoteCloseAsk, error(nil) + if err == nil && len(programs) > 0 { + choice, choiceErr = remoteCloseChoice(ctx, kernel, root) + } + return func(a *App) { + r.leaving = false + switch { + case a.project != p || r.closed: + // log-exempt: 用户取消:项目已经关闭或被替换,没有可决定的远端进程。 + case r.session != session: + // The connection was lost meanwhile: the host ends the unattached session after + // its idle timeout, and nothing can be asked of it now. + a.backgroundFailed("remote_close_programs", errRemoteSessionClosed) + proceed() + case err != nil: + a.backgroundFailed("remote_close_programs", remoteLogError(err)) + proceed() + case len(programs) == 0: + proceed() + default: + if choiceErr != nil { + a.backgroundFailed("remote_close_preferences", documentLogError(choiceErr)) + } + switch choice { + case core.RemoteCloseEnd: + proceed() + case core.RemoteCloseKeep: + a.keepRemoteAndClose(p, len(programs), proceed) + default: + a.askRemoteClose(p, programs, proceed) + } + } + } + }) +} + +// askRemoteClose asks whether the programs the host runs for p end with the workspace or keep +// running on the host; End is the default. "Remember my choice" stores the answer. +func (a *App) askRemoteClose(p *project, programs []core.RemoteProgram, proceed func()) { + r := p.remote + r.leaving = true + language := a.language() + running := i18n.SharedFormat(language, "desktop.remote.close.running", map[string]string{"connection": r.name}) + prompt := &pluginPrompt{ + title: i18n.Shared(language, "desktop.remote.close.title"), + text: running + "\n\n" + remoteProgramLines(language, programs), + actions: []string{ + i18n.Shared(language, "desktop.exit.cancel"), + i18n.Shared(language, "desktop.remote.close.keep"), + i18n.Shared(language, "desktop.remote.close.end"), + }, + check: i18n.Shared(language, "desktop.remote.close.remember"), + checkHelp: i18n.Shared(language, "desktop.remote.close.rememberHelp"), + } + prompt.onAnswer = func(choice *int) { + r.leaving = false + if choice == nil { + // log-exempt: 用户取消:对话框被关闭或随标签页撤下,关闭不再继续。 + return + } + if *choice == 0 { + a.performed("remote.close.cancel", surfaceButton) + return + } + keep := *choice == 1 + action, decided := "remote.close.end", core.RemoteCloseEnd + if keep { + action, decided = "remote.close.keep", core.RemoteCloseKeep + } + a.performed(action, surfaceButton) + if prompt.checked { + a.rememberRemoteClose(decided) + } + if a.project != p || r.closed { + // log-exempt: 用户取消:等待回答时项目已经关闭,没有可决定的远端进程。 + return + } + if keep { + a.keepRemoteAndClose(p, len(programs), proceed) + return + } + proceed() + } + a.prompts.queue = append(a.prompts.queue, prompt) +} + +// keepRemoteAndClose keeps the programs of p's session running on the host, then lets the project +// close. The workspace lets go of the session first, so nothing of it reaches the host any more, +// and the host is told to keep the session as the connection closes. The resume token is stored +// before that, so the host never keeps a session no later connection can find. When it cannot be +// stored, or the host does not keep the session, the programs end as if the user chose End, and a +// notification says so; so does a connection that was lost before the keep. +func (a *App) keepRemoteAndClose(p *project, count int, proceed func()) { + r := p.remote + session, resume, name := r.session, r.resume, r.name + if session == "" { + a.operationRejected("remote_keep_programs", "disconnected") + proceed() + a.shownWorkbench().notify(i18n.SharedFormat(a.language(), "desktop.remote.close.keepLost", map[string]string{"connection": name})) + return + } + r.leaving = true + r.stopRemoteTimer() + a.stopRemoteWatch(p) + a.closeGitObservation(p) + // Core stops the session's forwards with the connection. + r.ports.reset() + r.binding.Detach() + r.session, r.resume = "", nil + kernel, secrets, connectionID := a.kernel, a.remoteSecrets(), r.connectionID + a.background(nil, remoteDisconnectTimeout, func(ctx context.Context) func(*App) { + kept, err := keepRemoteSession(ctx, kernel, secrets, connectionID, session, resume) + return func(a *App) { + r.leaving = false + if err != nil { + a.operationFailed("remote_keep_programs", err) + } + proceed() + language, counted := a.language(), strconv.Itoa(count) + shown := a.shownWorkbench() + switch kept { + case remoteKept: + shown.notifyInfo(i18n.SharedFormat(language, "desktop.remote.close.kept", map[string]string{"connection": name, "count": counted})) + case remoteKeepUnstored: + shown.notify(i18n.SharedFormat(language, "desktop.remote.close.keepFailed", map[string]string{"connection": name})) + default: + shown.notify(i18n.SharedFormat(language, "desktop.remote.close.keepRefused", map[string]string{"connection": name})) + } + } + }) +} + +// remoteKeep is how keeping a host session ended. +type remoteKeep int + +const ( + // remoteKept: the host keeps the session and its token is stored. + remoteKept remoteKeep = iota + // remoteKeepUnstored: the token could not be stored, or the host issued none, so the session + // ended. + remoteKeepUnstored + // remoteKeepRefused: the host did not keep the session, or did not say it did. + remoteKeepRefused +) + +// keepRemoteSession stores the resume token of session for connectionID and tells the host to +// keep the session as its connection closes. Without a token, or when it cannot be stored, the +// session ends instead. A host that answers it did not keep the session has its token forgotten; +// one that does not answer keeps it stored, since the host may have kept the session, and the next +// connection forgets it if the host did not. It runs off the window thread; err is what the log +// keeps. +func keepRemoteSession(ctx context.Context, kernel Kernel, secrets remoteconn.KeptSecrets, connectionID, session string, resume *core.RemoteResume) (remoteKeep, error) { + stored := errRemoteNoResumeToken + if resume != nil { + stored = remoteconn.RememberKept(ctx, secrets, connectionID, *resume) + } + if stored != nil { + _, err := kernel.RemoteDisconnect(ctx, session, core.RemoteCloseEnd) + return remoteKeepUnstored, errors.Join(stored, remoteLogErrorOf(err)) + } + result, err := kernel.RemoteDisconnect(ctx, session, core.RemoteCloseKeep) + switch { + case err != nil: + return remoteKeepRefused, remoteLogError(err) + case !result.Kept: + return remoteKeepRefused, errors.Join(errRemoteNotKept, remoteconn.ForgetKept(ctx, secrets, connectionID, resume.Key)) + } + return remoteKept, nil +} + +// remoteLogErrorOf is remoteLogError for an error that may be nil. +func remoteLogErrorOf(err error) error { + if err == nil { + return nil + } + return remoteLogError(err) +} + +// returnRemoteSession gives back a session no workspace took. One that attached to a kept session +// whose programs still run is kept again, so they do not end without the user choosing it +// (§9.2); any other ends. +func (a *App) returnRemoteSession(connectionID string, session core.RemoteSession) { + if !session.Resumed || len(session.KeptPrograms) == 0 { + a.releaseRemoteSession(session.ID) + return + } + kernel, secrets, resume := a.kernel, a.remoteSecrets(), session.Resume() + a.background(nil, remoteDisconnectTimeout, func(ctx context.Context) func(*App) { + _, err := keepRemoteSession(ctx, kernel, secrets, connectionID, session.ID, resume) + if err == nil { + return nil + } + return func(a *App) { a.backgroundFailed("remote_keep_session", err) } + }) +} + +// offerKeptPrograms tells, once workspace p attached a session an earlier window kept, which +// programs that window left running on the host, and offers to end them (§9.2, S35): those alone, +// not the ones p started since. Keeping them needs nothing; closing p lists them again. +func (a *App) offerKeptPrograms(p *project, session core.RemoteSession) { + if !session.Resumed || len(session.KeptPrograms) == 0 { + return + } + r, kept, language := p.remote, session.KeptPrograms, a.language() + a.prompts.queue = append(a.prompts.queue, &pluginPrompt{ + title: i18n.Shared(language, "desktop.remote.kept.title"), + text: i18n.SharedFormat(language, "desktop.remote.kept.text", map[string]string{ + "connection": r.name, + "count": strconv.Itoa(len(kept)), + }) + "\n\n" + remoteProgramLines(language, kept), + actions: []string{ + i18n.Shared(language, "desktop.remote.kept.end"), + i18n.Shared(language, "desktop.remote.kept.keep"), + }, + onAnswer: func(choice *int) { + switch { + case choice == nil: + // log-exempt: 用户取消:对话框被关闭或随标签页撤下,保留的进程照常运行。 + case *choice == 0: + a.performed("remote.kept.end", surfaceButton) + a.endKeptPrograms(p, kept) + default: + a.performed("remote.kept.keep", surfaceButton) + } + }, + }) +} + +// endKeptPrograms ends programs, which an earlier window kept on the host of p, over the +// workspace's session; one that already ended is not counted. +func (a *App) endKeptPrograms(p *project, programs []core.RemoteProgram) { + r := p.remote + name := r.name + if r.closed || r.session == "" { + a.operationRejected("remote_end_programs", "disconnected") + a.notifyError(i18n.SharedFormat(a.language(), "desktop.remote.kept.endFailed", map[string]string{"connection": name})) + return + } + session, kernel := r.session, a.kernel + a.background(p, remoteProgramsTimeout, func(ctx context.Context) func(*App) { + ended, err := kernel.RemoteEndPrograms(ctx, session, programs) + return func(a *App) { + if err != nil { + a.operationFailed("remote_end_programs", remoteLogError(err)) + a.notifyError(i18n.SharedFormat(a.language(), "desktop.remote.kept.endFailed", map[string]string{"connection": name})) + return + } + a.notifySuccess(i18n.SharedFormat(a.language(), "desktop.remote.kept.ended", map[string]string{ + "connection": name, + "count": strconv.Itoa(ended), + })) + } + }) +} + +// rememberRemoteClose stores decided as what closing a remote workspace does to the host's +// programs, so the question is not asked again; Settings › Tools › Remote Workspace changes it. +func (a *App) rememberRemoteClose(decided core.RemoteClosePrograms) { + kernel, root := a.kernel, a.globalToolchainRoot() + a.background(nil, remoteReadTimeout, func(ctx context.Context) func(*App) { + read, err := remoteconn.ReadPreferences(ctx, kernel, root, "") + if err == nil { + _, _, err = read.Edit(ctx, kernel, core.RemotePreferenceEdit{ClosePrograms: &core.RemoteCloseProgramsEdit{Programs: &decided}}) + } + if err == nil { + return nil + } + return func(a *App) { + a.operationFailed("remote_close_remember", documentLogError(err)) + a.shownWorkbench().notify(i18n.Shared(a.language(), "desktop.remote.close.rememberFailed")) + } + }) +} + +// remoteCloseChoice is what closing a remote workspace does to the host's programs, as the +// preferences under root say; RemoteCloseAsk when they cannot be read, with the error. It runs off +// the window thread. +func remoteCloseChoice(ctx context.Context, kernel Kernel, root string) (core.RemoteClosePrograms, error) { + state, err := remotePreferenceState(ctx, kernel, root) + if err != nil { + return core.RemoteCloseAsk, err + } + switch choice := state.Closing.Programs; choice { + case core.RemoteCloseEnd, core.RemoteCloseKeep: + return choice, nil + } + return core.RemoteCloseAsk, nil +} + +// remoteProgramLines lists programs one per line, for the close question and the offer to end +// the kept ones: kind, name, command and how long each has run. The command is user content shown +// as it is; neither it nor the name is ever logged. +func remoteProgramLines(language i18n.Language, programs []core.RemoteProgram) string { + lines := make([]string, len(programs)) + for i, program := range programs { + kind := i18n.Shared(language, "desktop.remote.close.kindProcess") + if program.Kind == core.RemoteProgramTerminal { + kind = i18n.Shared(language, "desktop.remote.close.kindTerminal") + } + command, duration := strings.Join(program.Argv, " "), remoteRunningTime(language, program.RunningMs) + if program.Label != nil && program.Label.Name != "" { + lines[i] = i18n.SharedFormat(language, "desktop.remote.close.item", map[string]string{ + "kind": kind, + "name": program.Label.Name, + "command": command, + "duration": duration, + }) + continue + } + lines[i] = i18n.SharedFormat(language, "desktop.remote.close.itemUnnamed", map[string]string{ + "kind": kind, + "command": command, + "duration": duration, + }) + } + return strings.Join(lines, "\n") +} + +// remoteRunningTime is how long a program has run, in whole minutes, or hours and minutes. +func remoteRunningTime(language i18n.Language, milliseconds uint64) string { + minutes := milliseconds / 60_000 + switch { + case minutes == 0: + return i18n.Shared(language, "desktop.remote.close.ranUnderMinute") + case minutes < 60: + return i18n.SharedFormat(language, "desktop.remote.close.ranMinutes", map[string]string{"count": strconv.FormatUint(minutes, 10)}) + } + return i18n.SharedFormat(language, "desktop.remote.close.ranHours", map[string]string{ + "hours": strconv.FormatUint(minutes/60, 10), + "minutes": strconv.FormatUint(minutes%60, 10), + }) +} diff --git a/desktop/internal/workbench/remote_close_test.go b/desktop/internal/workbench/remote_close_test.go new file mode 100644 index 000000000..1230561ff --- /dev/null +++ b/desktop/internal/workbench/remote_close_test.go @@ -0,0 +1,384 @@ +package workbench + +import ( + "context" + "errors" + "slices" + "strings" + "sync" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/1lck/Lithe-IDEA/desktop/internal/remoteconn" +) + +// memoryKeptSecrets is the secret store of the tests' kept host sessions; failSet fails every +// write. +type memoryKeptSecrets struct { + mu sync.Mutex + items map[string]string + failSet error +} + +func (s *memoryKeptSecrets) Get(_ context.Context, namespace, key string) (string, bool, error) { + s.mu.Lock() + defer s.mu.Unlock() + secret, found := s.items[namespace+"\x00"+key] + return secret, found, nil +} + +func (s *memoryKeptSecrets) Set(_ context.Context, namespace, key, secret string) error { + s.mu.Lock() + defer s.mu.Unlock() + if s.failSet != nil { + return s.failSet + } + if s.items == nil { + s.items = map[string]string{} + } + s.items[namespace+"\x00"+key] = secret + return nil +} + +func (s *memoryKeptSecrets) Delete(_ context.Context, namespace, key string) error { + s.mu.Lock() + defer s.mu.Unlock() + delete(s.items, namespace+"\x00"+key) + return nil +} + +// remoteTestPrograms are what the host runs for the workspace: a named terminal that has run for +// two hours and five minutes, and an unnamed process started half a minute ago. +var remoteTestPrograms = []core.RemoteProgram{ + {Kind: core.RemoteProgramTerminal, ID: 1, Argv: []string{"/bin/bash", "-l"}, Label: &core.RemoteResourceLabel{Kind: "terminal", Name: "watch-shell"}, RunningMs: 125 * 60_000}, + {Kind: core.RemoteProgramProcess, ID: 7, Argv: []string{"npm", "run", "dev"}, RunningMs: 30_000}, +} + +// The values the log must never hold: the programs' commands and names, and the session tokens. +var remoteCloseSecrets = []string{"npm run dev", "/bin/bash", "watch-shell", "token-"} + +// keptOf is the session the host keeps for the saved connection's next connection, nil for none. +func keptOf(t *testing.T, h *harness) *core.RemoteResume { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + resume, err := remoteconn.NewestKept(ctx, h.app.remoteKeptSecrets, savedRemoteConnections(t, h)[0].ID) + if err != nil { + t.Fatalf("read the kept sessions: %v", err) + } + return resume +} + +// closeQuestion closes the project and waits for the question about the host's programs. +func (h *harness) closeQuestion(t *testing.T) *pluginPrompt { + t.Helper() + h.app.closeProject() + h.await("the question about the host's programs", func() bool { return len(h.app.prompts.queue) == 1 }) + h.settle() + return h.app.prompts.queue[0] +} + +// answer answers the prompt shown with the action numbered choice. +func (h *harness) answer(choice int) { + h.app.answerPrompt(&choice) + h.settle() +} + +// awaitClosed waits until the project is closed. +func (h *harness) awaitClosed(t *testing.T) { + t.Helper() + h.await("the project closed", func() bool { return h.app.project == nil && !h.app.closingProject }) + h.settle() +} + +// remoteChoices are what the host's sessions were closed with, in order. +func remoteChoices(k *remoteHostKernel) []core.RemoteClosePrograms { + k.mu.Lock() + defer k.mu.Unlock() + return slices.Clone(k.close.choices) +} + +// A remote workspace whose host runs nothing of it closes without a question and ends its session. +func TestRemoteCloseEndsWithoutAQuestionWhenTheHostRunsNothing(t *testing.T) { + h, k, _, _ := remoteWorkspaceHarness(t) + h.openRemoteTestProject(t) + h.app.closeProject() + h.awaitClosed(t) + if len(h.app.prompts.queue) != 0 { + t.Fatal("closing asked although the host runs nothing") + } + if got := remoteChoices(k); !slices.Equal(got, []core.RemoteClosePrograms{core.RemoteCloseEnd}) { + t.Fatalf("closed the session with %q, want end", got) + } +} + +// While the host runs programs of the workspace, closing asks with their kind, name, command and +// running time; Cancel keeps the workspace open and connected, and End and Close ends them. The +// commands are shown as they are and never logged. +func TestRemoteCloseAsksWhileTheHostRunsPrograms(t *testing.T) { + h, k, _, logger := remoteWorkspaceHarness(t) + lang := h.app.language() + p := h.openRemoteTestProject(t) + k.set(func(k *remoteHostKernel) { k.close.running = remoteTestPrograms }) + + prompt := h.closeQuestion(t) + if prompt.title != i18n.Shared(lang, "desktop.remote.close.title") { + t.Fatalf("title %q", prompt.title) + } + for _, want := range []string{ + i18n.SharedFormat(lang, "desktop.remote.close.running", map[string]string{"connection": remoteTestHost}), + "• Terminal “watch-shell”: /bin/bash -l (running for 2 h 5 min)", + "• Process: npm run dev (running for less than a minute)", + } { + if !strings.Contains(prompt.text, want) { + t.Fatalf("the question does not say %q:\n%s", want, prompt.text) + } + } + wantActions := []string{"Cancel", "Keep on Host and Close", "End and Close"} + if !slices.Equal(prompt.actions, wantActions) { + t.Fatalf("actions %q, want %q with End and Close the default", prompt.actions, wantActions) + } + if prompt.check != i18n.Shared(lang, "desktop.remote.close.remember") || prompt.checkHelp != i18n.Shared(lang, "desktop.remote.close.rememberHelp") { + t.Fatal("the question does not offer to remember the choice with its help") + } + if !h.shows(i18n.Shared(lang, "desktop.remote.close.remember")) { + t.Fatal("the checkbox is not shown") + } + + h.answer(0) + if h.app.project != p || p.remote.session != "session-1" || p.remote.leaving || len(remoteChoices(k)) != 0 { + t.Fatal("Cancel did not keep the workspace open and connected") + } + + h.closeQuestion(t) + h.answer(2) + h.awaitClosed(t) + if got := remoteChoices(k); !slices.Equal(got, []core.RemoteClosePrograms{core.RemoteCloseEnd}) { + t.Fatalf("closed the session with %q, want end", got) + } + if keptOf(t, h) != nil { + t.Fatal("ending the programs stored the session") + } + actions := remoteActions(logger) + if want := []string{"remote.close.cancel", "remote.close.end"}; !slices.Equal(actions[len(actions)-2:], want) { + t.Fatalf("performed %q, want %q last", actions, want) + } + if event := loggedAny(t, logger, remoteCloseSecrets...); event != "" { + t.Fatalf("logged a command, a name or a token: %s", event) + } +} + +// Keep on Host and Close stores the session's resume token, tells the host to keep the session and +// says how many programs stay. The next connection to the same host resumes the session, forgets +// the stored token and, once the folder opens, offers to end the kept programs: End Them ends +// those alone. +func TestRemoteCloseKeepsTheProgramsForTheNextConnection(t *testing.T) { + h, k, _, logger := remoteWorkspaceHarness(t) + lang := h.app.language() + h.openRemoteTestProject(t) + k.set(func(k *remoteHostKernel) { k.close.running = remoteTestPrograms }) + + h.closeQuestion(t) + h.answer(1) + h.awaitClosed(t) + if got := remoteChoices(k); !slices.Equal(got, []core.RemoteClosePrograms{core.RemoteCloseKeep}) { + t.Fatalf("closed the session with %q, want keep", got) + } + if got := keptOf(t, h); got == nil || *got != (core.RemoteResume{Key: "key-1", Token: "token-1"}) { + t.Fatal("the session's resume token was not stored") + } + kept := i18n.SharedFormat(lang, "desktop.remote.close.kept", map[string]string{"connection": remoteTestHost, "count": "2"}) + if got := lastNotice(h); got != kept { + t.Fatalf("notified %q, want %q", got, kept) + } + + k.set(func(k *remoteHostKernel) { k.close.running = nil }) + h.app.openRemote(surfaceMenu) + h.settle() + h.settle() + h.openRemoteTestProject(t) + k.mu.Lock() + resumes := slices.Clone(k.close.resumes) + k.mu.Unlock() + if len(resumes) != 2 || resumes[0] != nil || resumes[1] == nil || resumes[1].Key != "key-1" { + t.Fatal("the next connection did not present the kept session") + } + if keptOf(t, h) != nil { + t.Fatal("the resumed session's token is still stored") + } + h.await("the offer to end the kept programs", func() bool { return len(h.app.prompts.queue) == 1 }) + h.settle() + offer := h.app.prompts.queue[0] + if offer.title != i18n.Shared(lang, "desktop.remote.kept.title") || !strings.Contains(offer.text, "npm run dev") || + !slices.Equal(offer.actions, []string{"End Them", "Keep Running"}) { + t.Fatalf("offer %q %q %q", offer.title, offer.text, offer.actions) + } + h.answer(0) + h.await("the kept programs ended", func() bool { + k.mu.Lock() + defer k.mu.Unlock() + return len(k.close.ended) == 1 + }) + h.settle() + if got := k.close.ended[0]; !slices.EqualFunc(got, remoteTestPrograms, func(a, b core.RemoteProgram) bool { return a.Kind == b.Kind && a.ID == b.ID }) { + t.Fatalf("ended %+v, want the kept programs alone", got) + } + ended := i18n.SharedFormat(lang, "desktop.remote.kept.ended", map[string]string{"connection": remoteTestHost, "count": "2"}) + if got := lastNotice(h); got != ended { + t.Fatalf("notified %q, want %q", got, ended) + } + actions := remoteActions(logger) + if !slices.Contains(actions, "remote.close.keep") || actions[len(actions)-1] != "remote.kept.end" { + t.Fatalf("performed %q", actions) + } + if event := loggedAny(t, logger, remoteCloseSecrets...); event != "" { + t.Fatalf("logged a command, a name or a token: %s", event) + } +} + +// A connection that resumes a kept session and gives it back without opening a folder keeps it +// again, so its programs do not end without the user choosing it. +func TestRemoteCloseKeepsAResumedSessionNoWorkspaceTook(t *testing.T) { + h, k, _, _ := remoteWorkspaceHarness(t) + h.openRemoteTestProject(t) + k.set(func(k *remoteHostKernel) { k.close.running = remoteTestPrograms }) + h.closeQuestion(t) + h.answer(1) + h.awaitClosed(t) + + h.app.openRemote(surfaceMenu) + h.settle() + h.settle() + h.connectAndBrowse(t) + if keptOf(t, h) != nil { + t.Fatal("the resumed session's token is still stored") + } + h.app.closeRemote() + // A keep that succeeds posts nothing back, so settling (every background task returned) is + // what to wait for. + h.settle() + if got := remoteChoices(k); len(got) != 2 || got[1] != core.RemoteCloseKeep { + t.Fatalf("gave the resumed session back with %q, want keep", got) + } + if got := keptOf(t, h); got == nil || got.Key != "key-1" { + t.Fatal("the session given back was not stored again") + } +} + +// Remember my choice stores the answer: the next close does as it says without asking, End ending +// the programs and Keep on Host keeping them. +func TestRemoteCloseRemembersTheChoice(t *testing.T) { + h, k, _, _ := remoteWorkspaceHarness(t) + h.openRemoteTestProject(t) + k.set(func(k *remoteHostKernel) { k.close.running = remoteTestPrograms }) + prompt := h.closeQuestion(t) + prompt.checked = true + h.answer(2) + h.awaitClosed(t) + closing := func() core.RemoteClosing { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + read, err := remoteconn.ReadPreferences(ctx, core.NewClient(), h.store.Dir(), "") + if err != nil { + t.Fatalf("read the preferences: %v", err) + } + return read.State.Closing + } + h.await("the choice stored", func() bool { return closing().Programs == core.RemoteCloseEnd }) + + h.app.openRemote(surfaceMenu) + h.settle() + h.settle() + h.openRemoteTestProject(t) + h.app.closeProject() + h.awaitClosed(t) + if len(h.app.prompts.queue) != 0 { + t.Fatal("the remembered End asked again") + } + if got := remoteChoices(k); !slices.Equal(got, []core.RemoteClosePrograms{core.RemoteCloseEnd, core.RemoteCloseEnd}) { + t.Fatalf("closed the sessions with %q", got) + } + + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + read, err := remoteconn.ReadPreferences(ctx, core.NewClient(), h.store.Dir(), "") + if err != nil { + t.Fatal(err) + } + keep := core.RemoteCloseKeep + if _, _, err := read.Edit(ctx, core.NewClient(), core.RemotePreferenceEdit{ClosePrograms: &core.RemoteCloseProgramsEdit{Programs: &keep}}); err != nil { + t.Fatal(err) + } + h.app.openRemote(surfaceMenu) + h.settle() + h.settle() + h.openRemoteTestProject(t) + h.app.closeProject() + h.awaitClosed(t) + if len(h.app.prompts.queue) != 0 { + t.Fatal("the remembered Keep on Host asked") + } + if got := remoteChoices(k); got[len(got)-1] != core.RemoteCloseKeep || keptOf(t, h) == nil { + t.Fatalf("closed the sessions with %q, want the last kept", got) + } +} + +// A keep whose token cannot be stored ends the programs and says so, and so does a host that does +// not keep the session, whose token is then forgotten. +func TestRemoteCloseEndsWhenTheSessionCannotBeKept(t *testing.T) { + h, k, _, logger := remoteWorkspaceHarness(t) + lang := h.app.language() + values := map[string]string{"connection": remoteTestHost} + secrets := h.app.remoteKeptSecrets.(*memoryKeptSecrets) + secrets.failSet = errors.New("the secret store is locked") + h.openRemoteTestProject(t) + k.set(func(k *remoteHostKernel) { k.close.running = remoteTestPrograms }) + h.closeQuestion(t) + h.answer(1) + h.awaitClosed(t) + if got := remoteChoices(k); !slices.Equal(got, []core.RemoteClosePrograms{core.RemoteCloseEnd}) { + t.Fatalf("closed the session with %q, want end", got) + } + if got, want := lastNotice(h), i18n.SharedFormat(lang, "desktop.remote.close.keepFailed", values); got != want { + t.Fatalf("notified %q, want %q", got, want) + } + if countFailures(logger, "remote_keep_programs") != 1 { + t.Fatal("the failed keep was not logged") + } + + secrets.failSet = nil + k.set(func(k *remoteHostKernel) { k.close.refuseKeep = true }) + h.app.openRemote(surfaceMenu) + h.settle() + h.settle() + h.openRemoteTestProject(t) + h.closeQuestion(t) + h.answer(1) + h.awaitClosed(t) + if got, want := lastNotice(h), i18n.SharedFormat(lang, "desktop.remote.close.keepRefused", values); got != want { + t.Fatalf("notified %q, want %q", got, want) + } + if keptOf(t, h) != nil { + t.Fatal("the token of a session the host did not keep is still stored") + } + if event := loggedAny(t, logger, remoteCloseSecrets...); event != "" { + t.Fatalf("logged a command, a name or a token: %s", event) + } +} + +// A list of the host's programs that cannot be had does not trap the user in the window: the +// workspace closes and the failure is logged. +func TestRemoteCloseGoesOnWhenTheProgramsCannotBeListed(t *testing.T) { + h, k, _, logger := remoteWorkspaceHarness(t) + h.openRemoteTestProject(t) + k.set(func(k *remoteHostKernel) { + k.close.runningErr = &core.Error{Command: "remote.runningPrograms", Code: core.CodeConnectionClosed, Message: "closed"} + }) + h.app.closeProject() + h.awaitClosed(t) + if len(h.app.prompts.queue) != 0 || countFailures(logger, "remote_close_programs") != 1 { + t.Fatal("the failed list asked or was not logged") + } +} diff --git a/desktop/internal/workbench/remote_close_visual_test.go b/desktop/internal/workbench/remote_close_visual_test.go new file mode 100644 index 000000000..2e968a7b8 --- /dev/null +++ b/desktop/internal/workbench/remote_close_visual_test.go @@ -0,0 +1,105 @@ +//go:build vivahead && lithevisual + +package workbench + +import ( + "os" + "path/filepath" + "strings" + "testing" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/1lck/Lithe-IDEA/desktop/internal/remoteplaceholder" + "github.com/1lck/Lithe-IDEA/desktop/internal/remoteserver" + "github.com/1lck/Lithe-IDEA/desktop/internal/store" + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/headless" +) + +// TestVisualRemoteClose captures closing a remote workspace whose host still runs a terminal and a +// process of it: the question with the programs, Remember my choice and its help; the notice once +// they are kept on the host; and, on the next connection, the offer to end the kept programs. +func TestVisualRemoteClose(t *testing.T) { + out := os.Getenv("LITHE_VISUAL_OUTPUT_DIR") + if out == "" { + t.Skip("set LITHE_VISUAL_OUTPUT_DIR") + } + if err := os.MkdirAll(out, 0755); err != nil { + t.Fatal(err) + } + for _, look := range []struct{ theme, language, suffix string }{ + {"light", "en-US", "light-en-US"}, + {"dark", "zh-Hans", "dark-zh-CN"}, + } { + t.Run(look.suffix, func(t *testing.T) { + prefs := store.At(t.TempDir()) + if err := prefs.Save(settingsFile, settings{Theme: themeChoice(look.theme), Language: look.language, DisableAutoSave: true}); err != nil { + t.Fatal(err) + } + var session *headless.Session + kernel := &remoteHostKernel{testKernel: &testKernel{Client: core.NewClient()}} + // The folder was kept in safe mode before, so it opens without the trust question. + kernel.git.trust = map[string]string{remoteTestFolder: core.WorkspaceDistrusted} + h := newHarnessWithDriver(t, Options{Kernel: kernel, Store: prefs, Languages: []string{look.language}}, func(config app.Config) (*app.Driver, func(), error) { + config.Width, config.Height = 1200, 760 + var err error + session, err = headless.Open(config, nil, headless.Options{}) + if err != nil { + return nil, nil, err + } + return session.Driver(), session.Close, nil + }) + shot := func(scene string) { + t.Helper() + // The scenes set the window's state directly, which does not ask for a frame. + h.app.invalidator.Invalidate() + h.settleChain() + if err := session.Screenshot(filepath.Join(out, "remote-close-"+scene+"-"+look.suffix+".png")); err != nil { + t.Fatal(err) + } + } + timers := &remoteTimers{} + anchor := filepath.Join(t.TempDir(), remoteplaceholder.AnchorName) + h.app.remoteBundle = func() (remoteserver.Bundle, error) { + return remoteserver.Bundle{Version: "0.0.0-visual", Builds: []remoteserver.Build{{ + Target: "x86_64-unknown-linux-musl", Path: "/bundle/lithe-server", SHA256: strings.Repeat("0", 64), + }}}, nil + } + h.app.remoteAnchor = func() (string, error) { return anchor, nil } + h.app.remoteAfter = timers.start + h.app.openRemote(surfaceMenu) + h.settleChain() + r := &h.app.remote + r.selectNew() + r.form.name.SetText("Build box") + r.form.host.SetText(remoteTestHost) + r.form.user.SetText("dev") + h.app.saveRemote() + h.settleChain() + if r.err != "" || r.fieldErr.field != "" { + t.Fatalf("saving the connection: %q %+v", r.err, r.fieldErr) + } + h.openRemoteTestProject(t) + kernel.set(func(k *remoteHostKernel) { k.close.running = remoteTestPrograms }) + + h.closeQuestion(t) + // The pointer rests on the default action, as after a click on the window's close button. + shot("question") + h.answer(1) + h.awaitClosed(t) + shot("kept") + h.app.clearNotifications() + + kernel.set(func(k *remoteHostKernel) { k.close.running = nil }) + h.app.openRemote(surfaceMenu) + h.settleChain() + h.openRemoteTestProject(t) + h.await("the offer to end the kept programs", func() bool { return len(h.app.prompts.queue) == 1 }) + shot("offer") + if h.app.prompts.queue[0].title != i18n.Shared(h.app.language(), "desktop.remote.kept.title") { + t.Fatal("the offer to end the kept programs is not shown") + } + }) + } +} diff --git a/desktop/internal/workbench/remote_preferences.go b/desktop/internal/workbench/remote_preferences.go index 5b5467714..d50cc762f 100644 --- a/desktop/internal/workbench/remote_preferences.go +++ b/desktop/internal/workbench/remote_preferences.go @@ -20,24 +20,25 @@ func remotePreferencesDocument(ctx context.Context, kernel Kernel, root string) return remoteconn.PreferencesDocument(ctx, kernel, root) } +// remotePreferenceState is Core's reading of the remote workspace preferences under root, the +// automatic values when there is no preference directory. It runs off the window thread. +func remotePreferenceState(ctx context.Context, kernel Kernel, root string) (core.RemotePreferences, error) { + if root == "" { + return kernel.RemotePreferences(ctx, nil, "") + } + preferences, err := remoteconn.ReadPreferences(ctx, kernel, root, "") + return preferences.State, err +} + // remoteReconnectDelays is the pause before each automatic attempt to connect again, as Core // derives it from the reconnect limit of the preferences under root; none when the limit is 0. // It runs off the window thread. func remoteReconnectDelays(ctx context.Context, kernel Kernel, root string) ([]time.Duration, error) { - var reconnect core.RemoteReconnect - if root == "" { - state, err := kernel.RemotePreferences(ctx, nil, "") - if err != nil { - return nil, err - } - reconnect = state.Reconnect - } else { - preferences, err := remoteconn.ReadPreferences(ctx, kernel, root, "") - if err != nil { - return nil, err - } - reconnect = preferences.State.Reconnect + state, err := remotePreferenceState(ctx, kernel, root) + if err != nil { + return nil, err } + reconnect := state.Reconnect delays := make([]time.Duration, len(reconnect.DelaysMilliseconds)) for i, milliseconds := range reconnect.DelaysMilliseconds { delays[i] = time.Duration(milliseconds) * time.Millisecond diff --git a/desktop/internal/workbench/remote_workspace.go b/desktop/internal/workbench/remote_workspace.go index 32a3bc88f..f0fcbded4 100644 --- a/desktop/internal/workbench/remote_workspace.go +++ b/desktop/internal/workbench/remote_workspace.go @@ -24,8 +24,10 @@ import ( // lost, and the window then connects again on its own a few times, pausing longer each time. // OpenSSH's questions are cancelled during those attempts, which must not ask the user anything // they did not start; a host that needs a password then ends disconnected, and Reconnect in the -// status bar asks. Closing the project ends its session, and quitting ends every session Core -// keeps (App.Run). +// status bar asks. Connecting again presents the session's resume token, so the programs the +// host runs survive a lost connection. Closing the project asks, while the host still runs +// programs the workspace started, whether they end or keep running on the host +// (remote_close.go); quitting ends every session Core still has open (App.Run). // // In this stage the workspace lists its folder in the Project tool window, the editor opens, // saves and compares the host's files (remote_documents.go), Find in Files and Search Everywhere @@ -79,6 +81,12 @@ type remoteProject struct { host remoteHost // session is the session the binding is attached to, "" while there is none. session string + // resume is what connecting again presents to attach to the same host session, nil when the + // host issued no token. It is a secret: it stays in memory and is never logged. + resume *core.RemoteResume + // leaving is set while closing the project decides, or carries out, what happens to the + // programs the host runs (remote_close.go); nothing connects again meanwhile. + leaving bool // home is the host account's home directory, "" when the host did not report it. home string link remoteLink @@ -200,9 +208,10 @@ func (a *App) remotePlaceholderAnchor() (string, error) { } // connectRemoteHost opens a session to host with the server builds the client carries and, for -// an SSH host, the SSH program of the remote workspace preferences under root. It runs off the -// window thread. -func (a *App) connectRemoteHost(ctx context.Context, kernel Kernel, root string, host remoteHost) (core.RemoteConnectResult, error) { +// an SSH host, the SSH program of the remote workspace preferences under root. resume, when set, +// attaches to the host session an earlier connection kept or lost instead of starting one. It runs +// off the window thread. +func (a *App) connectRemoteHost(ctx context.Context, kernel Kernel, root string, host remoteHost, resume *core.RemoteResume) (core.RemoteConnectResult, error) { bundle, err := a.remoteServerBundle() if err != nil { return core.RemoteConnectResult{}, err @@ -212,6 +221,7 @@ func (a *App) connectRemoteHost(ctx context.Context, kernel Kernel, root string, servers[i] = core.RemoteServerBuild{Target: build.Target, Path: build.Path, SHA256: build.SHA256} } request := host.request(servers, bundle.Version) + request.Resume = resume if host.wsl == nil { // A WSL distribution starts through wsl.exe, which the SSH program does not replace. if request.Preferences, err = remotePreferencesDocument(ctx, kernel, root); err != nil { @@ -243,7 +253,7 @@ func (a *App) releaseRemoteSession(id string) { } kernel := a.kernel a.background(nil, remoteDisconnectTimeout, func(ctx context.Context) func(*App) { - _, err := kernel.RemoteDisconnect(ctx, id) + _, err := kernel.RemoteDisconnect(ctx, id, core.RemoteCloseEnd) if err == nil { return nil } @@ -289,11 +299,12 @@ func (r *remoteProject) stopRemoteTimer() { // attachRemote makes session the workspace's session and starts its heartbeat, the host watch of // its folder and, in a trusted workspace, the watch of its Git metadata, which reads the status // again. -func (a *App) attachRemote(p *project, session string) { +func (a *App) attachRemote(p *project, session core.RemoteSession) { r := p.remote a.stopRemoteWatch(p) - r.session, r.link, r.attempt, r.misses, r.failure = session, remoteConnected, 0, 0, nil - r.binding.Attach(session) + r.session, r.link, r.attempt, r.misses, r.failure = session.ID, remoteConnected, 0, 0, nil + r.resume = session.Resume() + r.binding.Attach(session.ID) a.beatRemote(p) r.watchWait = remoteWatchReady a.startRemoteWatch(p) @@ -400,7 +411,7 @@ func (a *App) startRemoteReconnection(p *project) { // is unreachable, tries again after each pause of the reconnection's delays. func (a *App) reconnectRemote(p *project, userStarted bool) { r := p.remote - if r == nil || r.closed || r.reconnecting != nil || r.session != "" { + if r == nil || r.closed || r.leaving || r.reconnecting != nil || r.session != "" { return } if userStarted { @@ -416,10 +427,10 @@ func (a *App) reconnectRemote(p *project, userStarted bool) { } attempt := &remoteProbe{cancel: cancel} r.reconnecting = attempt - kernel, root, host := a.kernel, a.globalToolchainRoot(), r.host + kernel, root, host, resume := a.kernel, a.globalToolchainRoot(), r.host, r.resume a.background(nil, 0, func(context.Context) func(*App) { defer cancel() - result, err := a.connectRemoteHost(ctx, kernel, root, host) + result, err := a.connectRemoteHost(ctx, kernel, root, host, resume) return func(a *App) { if a.project != p || r.closed || r.reconnecting != attempt { if result.Session != nil { @@ -430,7 +441,9 @@ func (a *App) reconnectRemote(p *project, userStarted bool) { } r.reconnecting = nil if err == nil && result.Status == core.RemoteProbeConnected && result.Session != nil { - a.attachRemote(p, result.Session.ID) + // The programs a resumed session still runs are the workspace's own, which closing + // it lists; nothing asks about them now. + a.attachRemote(p, *result.Session) a.refreshRemoteTree(p) a.recheckRemoteDocuments(p) return @@ -478,7 +491,7 @@ func (a *App) refreshRemoteTree(p *project) { // reconnectRemoteByUser is Reconnect in the status bar. func (a *App) reconnectRemoteByUser(surface actionSurface) { p := a.project - if p == nil || p.remote == nil || p.remote.session != "" || p.remote.reconnecting != nil { + if p == nil || p.remote == nil || p.remote.session != "" || p.remote.reconnecting != nil || p.remote.leaving { return } a.performed("remote.workspace.reconnect", surface) @@ -502,7 +515,7 @@ func (a *App) closeRemoteWorkspace(p *project) { } r.binding.Detach() a.releaseRemoteSession(r.session) - r.session, r.menuOpen = "", false + r.session, r.resume, r.menuOpen = "", nil, false } // refuseRemote reports whether p is a remote workspace. When it is, a feature that runs only on @@ -519,10 +532,10 @@ func (a *App) refuseRemote(p *project, operation string) bool { // openRemoteProject opens target as this workbench's project, which must have none: the window // opens the folder in a new tab otherwise (windowSessions.openRemoteTab). The workspace takes -// target's session; when it cannot open, the session is ended. +// target's session; when it cannot open, the session is given back (returnRemoteSession). func (a *App) openRemoteProject(target remoteTarget) { if a.project != nil || a.closingProject { - a.releaseRemoteSession(target.session.ID) + a.returnRemoteSession(target.connectionID, target.session) return } name := path.Base(target.remoteRoot) @@ -545,12 +558,13 @@ func (a *App) openRemoteProject(target remoteTarget) { a.logView.reset() a.worktreeView.reset() // Attaching the session starts the watch of the Git metadata (remote_git.go). - a.attachRemote(p, target.session.ID) + a.attachRemote(p, target.session) a.loadGit(p) a.loadLog(p) // Unsaved edits of the folder's files are drafts on this computer; they open over the host's // files as a local project's do. a.restoreCheckpoints(p) + a.offerKeptPrograms(p, target.session) } // remoteSessionLost is how a request of p reports, on its own goroutine, that it found the diff --git a/desktop/internal/workbench/remote_workspace_test.go b/desktop/internal/workbench/remote_workspace_test.go index 5a88ac934..fef597251 100644 --- a/desktop/internal/workbench/remote_workspace_test.go +++ b/desktop/internal/workbench/remote_workspace_test.go @@ -82,6 +82,63 @@ type remoteHostKernel struct { ports remoteHostPorts // wsl is this computer's WSL distributions (remote_wsl_test.go). wsl remoteHostWSL + // close is what the host sessions run and keep (remote_close_test.go). + close remoteHostClose +} + +// remoteHostClose is what the host's sessions run and keep. Each SSH session N has the key "key-N" +// and the token "token-N"; a connection that presents a kept session's key and token resumes it. +type remoteHostClose struct { + // running are the programs the attached session runs, whichever it is; runningErr fails + // listing them. + running []core.RemoteProgram + runningErr error + // choices are what each closed session was closed with, in closed's order. + choices []core.RemoteClosePrograms + // keys are the sessions' keys by session id. + keys map[string]string + // kept are the programs of the sessions the host keeps, by key; refuseKeep makes the host + // close a session it was asked to keep. + kept map[string][]core.RemoteProgram + refuseKeep bool + // resumes are what each SSH connection presented, nil for nothing. + resumes []*core.RemoteResume + // ended are the programs each request to end some named. + ended [][]core.RemoteProgram +} + +// session is the SSH session numbered n, resuming the kept session resume names when it presents +// its token. It runs under the kernel's lock. +func (c *remoteHostClose) session(n int, resume *core.RemoteResume) *core.RemoteSession { + c.resumes = append(c.resumes, resume) + if c.keys == nil { + c.keys = map[string]string{} + } + id := "session-" + strconv.Itoa(n) + session := &core.RemoteSession{ID: id, HostName: "devbox", UserName: "dev", HomeDirectory: remoteTestHome, SessionKey: "key-" + strconv.Itoa(n)} + if resume != nil && resume.Token == "token-"+strings.TrimPrefix(resume.Key, "key-") { + if kept, ok := c.kept[resume.Key]; ok { + delete(c.kept, resume.Key) + session.SessionKey, session.Resumed, session.KeptPrograms = resume.Key, true, kept + } + } + token := "token-" + strings.TrimPrefix(session.SessionKey, "key-") + session.SessionToken = &token + c.keys[id] = session.SessionKey + return session +} + +func (k *remoteHostKernel) RemoteRunningPrograms(context.Context, string) ([]core.RemoteProgram, error) { + k.mu.Lock() + defer k.mu.Unlock() + return slices.Clone(k.close.running), k.close.runningErr +} + +func (k *remoteHostKernel) RemoteEndPrograms(_ context.Context, _ string, programs []core.RemoteProgram) (int, error) { + k.mu.Lock() + defer k.mu.Unlock() + k.close.ended = append(k.close.ended, slices.Clone(programs)) + return len(programs), nil } // remoteTestTree is the workspace's tree the Project tool window lists by default. @@ -106,8 +163,7 @@ func (k *remoteHostKernel) RemoteConnect(_ context.Context, request core.RemoteC if k.refuse != "" { return core.RemoteConnectResult{Status: k.refuse}, nil } - session := &core.RemoteSession{ID: "session-" + strconv.Itoa(k.connects), HostName: "devbox", UserName: "dev", HomeDirectory: remoteTestHome} - return core.RemoteConnectResult{Status: core.RemoteProbeConnected, Session: session}, nil + return core.RemoteConnectResult{Status: core.RemoteProbeConnected, Session: k.close.session(k.connects, request.Resume)}, nil } func (k *remoteHostKernel) RemoteReadDir(_ context.Context, _ string, dir string) (core.RemoteDirectory, error) { @@ -129,11 +185,19 @@ func (k *remoteHostKernel) RemoteServerState(context.Context, string) error { return k.state } -func (k *remoteHostKernel) RemoteDisconnect(_ context.Context, id string) (bool, error) { +func (k *remoteHostKernel) RemoteDisconnect(_ context.Context, id string, programs core.RemoteClosePrograms) (core.RemoteDisconnectResult, error) { k.mu.Lock() defer k.mu.Unlock() k.closed = append(k.closed, id) - return true, nil + k.close.choices = append(k.close.choices, programs) + kept := programs == core.RemoteCloseKeep && !k.close.refuseKeep + if kept { + if k.close.kept == nil { + k.close.kept = map[string][]core.RemoteProgram{} + } + k.close.kept[k.close.keys[id]] = slices.Clone(k.close.running) + } + return core.RemoteDisconnectResult{Closed: true, Kept: kept}, nil } func (k *remoteHostKernel) ListDirectories(ctx context.Context, _ string, paths []string) ([]core.DirectoryListing, error) { diff --git a/desktop/internal/workbench/window_sessions.go b/desktop/internal/workbench/window_sessions.go index 45cab524a..90e05dfad 100644 --- a/desktop/internal/workbench/window_sessions.go +++ b/desktop/internal/workbench/window_sessions.go @@ -257,6 +257,7 @@ func (s *windowSessions) openTab(path string) { func (s *windowSessions) openRemoteTab(from *App, target remoteTarget) { a := New(s.options) a.remoteBundle, a.remoteAnchor, a.remoteAfter = from.remoteBundle, from.remoteAnchor, from.remoteAfter + a.remoteKeptSecrets = from.remoteKeptSecrets s.list = append(s.list, a) s.activate(a) a.reloadPluginLanguages() diff --git a/docs/assets/remote-close/README.md b/docs/assets/remote-close/README.md new file mode 100644 index 000000000..2ee9f3fdc --- /dev/null +++ b/docs/assets/remote-close/README.md @@ -0,0 +1,18 @@ +# 关闭远程工作区时确认远端进程(#2231)无头测试截图 + +来自生产 Viva 工作台的无头渲染,由 `desktop/internal/workbench/remote_close_visual_test.go` 的 `TestVisualRemoteClose` 生成。主机是测试里的假内核:连接名 “Build box”,主机上为这个工作区运行着一个命名终端(`/bin/bash -l`,已运行 2 小时 5 分钟)和一个未命名进程(`npm run dev`,不到 1 分钟)。截图用于确认: + +- 关闭窗口时,只要主机上还有 Lithe 启动的进程就先问:标题“关闭远程工作区?”,正文列出每个进程的类型、名称、命令(原样显示,不脱敏)和已运行时长;按钮依次是“取消”“保留在远端并关闭”“结束并关闭”(默认);“记住我的选择”旁的 ⓘ 说明之后不再询问、可在 设置 › 工具 › 远程工作区 中修改; +- 选“保留在远端并关闭”后,欢迎页通知“N 个进程保留在 <连接名> 上”; +- 下次连接同一主机并打开文件夹时,接上被保留的会话,列出上次保留的进程,可以“结束这些进程”(只结束它们,不动这次新开的)或“继续运行”。 + +截图不代表 macOS/Windows 原生窗口验收,也不代表真实 SSH 主机上的整机验收。 + +复验:在仓库根目录设置绝对路径 `LITHE_VISUAL_OUTPUT_DIR`,运行 +`scripts/desktop/desktop-go.sh test -tags vivahead,lithevisual -run 'TestVisualRemoteClose$' ./internal/workbench/`。 + +| 场景 | 浅色英文 | 深色中文 | +| --- | --- | --- | +| 关闭时询问 | [浅色英文](remote-close-question-light-en-US.png) | [深色中文](remote-close-question-dark-zh-CN.png) | +| 保留后的通知 | [浅色英文](remote-close-kept-light-en-US.png) | [深色中文](remote-close-kept-dark-zh-CN.png) | +| 下次连接列出保留的进程 | [浅色英文](remote-close-offer-light-en-US.png) | [深色中文](remote-close-offer-dark-zh-CN.png) | diff --git a/docs/assets/remote-close/remote-close-kept-dark-zh-CN.png b/docs/assets/remote-close/remote-close-kept-dark-zh-CN.png new file mode 100644 index 000000000..a0fd66a02 Binary files /dev/null and b/docs/assets/remote-close/remote-close-kept-dark-zh-CN.png differ diff --git a/docs/assets/remote-close/remote-close-kept-light-en-US.png b/docs/assets/remote-close/remote-close-kept-light-en-US.png new file mode 100644 index 000000000..3832dc7b6 Binary files /dev/null and b/docs/assets/remote-close/remote-close-kept-light-en-US.png differ diff --git a/docs/assets/remote-close/remote-close-offer-dark-zh-CN.png b/docs/assets/remote-close/remote-close-offer-dark-zh-CN.png new file mode 100644 index 000000000..3abd79a5e Binary files /dev/null and b/docs/assets/remote-close/remote-close-offer-dark-zh-CN.png differ diff --git a/docs/assets/remote-close/remote-close-offer-light-en-US.png b/docs/assets/remote-close/remote-close-offer-light-en-US.png new file mode 100644 index 000000000..667cdd14e Binary files /dev/null and b/docs/assets/remote-close/remote-close-offer-light-en-US.png differ diff --git a/docs/assets/remote-close/remote-close-question-dark-zh-CN.png b/docs/assets/remote-close/remote-close-question-dark-zh-CN.png new file mode 100644 index 000000000..39c04daf9 Binary files /dev/null and b/docs/assets/remote-close/remote-close-question-dark-zh-CN.png differ diff --git a/docs/assets/remote-close/remote-close-question-light-en-US.png b/docs/assets/remote-close/remote-close-question-light-en-US.png new file mode 100644 index 000000000..a49d10c10 Binary files /dev/null and b/docs/assets/remote-close/remote-close-question-light-en-US.png differ diff --git a/docs/assets/remote-settings/README.md b/docs/assets/remote-settings/README.md index 3ba654b97..7af551c9c 100644 --- a/docs/assets/remote-settings/README.md +++ b/docs/assets/remote-settings/README.md @@ -6,6 +6,7 @@ - “SSH 配置文件”只读显示 Core 读取的 `~/.ssh/config` 路径,文件不存在时在路径后注明“不存在”,注明不随宽度截断; - “自动重连时长”默认“自动(1 分钟)”,草稿状态选了 5 分钟; - “端口转发”一节的“反向转发”默认“自动(不允许)”,ⓘ 说明主机上的所有用户都能连接反向转发的端口、每条规则仍会确认; +- “关闭工作区”卡片:“关闭时的远端进程”默认“每次询问”,可选“结束”或“保留在远端”,关闭对话框里勾选“记住我的选择”后只能在这里改;“常驻会话的空闲超时”只读显示 Core 报告的远端服务超时(10 分钟),ⓘ 说明断线且没人保留的会话多久后结束; - “保存位置”显示偏好目录下的 `remote/preferences.json`,还没有文件时注明“修改后才创建”,路径过长时截断并在悬停提示里给出完整路径; - 修改只是草稿:侧栏页名后有圆点,底部显示未应用的数量和写入目标,点“应用”或“好”才写入。 @@ -15,3 +16,4 @@ | --- | --- | --- | | 自动值 | [浅色英文](remote-settings-automatic-light-en-US.png) | [深色中文](remote-settings-automatic-dark-zh-CN.png) | | 选择 SSH 程序和重连时长后的草稿 | [浅色英文](remote-settings-drafts-light-en-US.png) | [深色中文](remote-settings-drafts-dark-zh-CN.png) | +| 关闭时保留远端进程的草稿 | [浅色英文](remote-settings-closing-light-en-US.png) | [深色中文](remote-settings-closing-dark-zh-CN.png) | diff --git a/docs/assets/remote-settings/remote-settings-automatic-dark-zh-CN.png b/docs/assets/remote-settings/remote-settings-automatic-dark-zh-CN.png index 2fc81eaba..a7382f083 100644 Binary files a/docs/assets/remote-settings/remote-settings-automatic-dark-zh-CN.png and b/docs/assets/remote-settings/remote-settings-automatic-dark-zh-CN.png differ diff --git a/docs/assets/remote-settings/remote-settings-automatic-light-en-US.png b/docs/assets/remote-settings/remote-settings-automatic-light-en-US.png index 603443519..990002a23 100644 Binary files a/docs/assets/remote-settings/remote-settings-automatic-light-en-US.png and b/docs/assets/remote-settings/remote-settings-automatic-light-en-US.png differ diff --git a/docs/assets/remote-settings/remote-settings-closing-dark-zh-CN.png b/docs/assets/remote-settings/remote-settings-closing-dark-zh-CN.png new file mode 100644 index 000000000..3997d3bf5 Binary files /dev/null and b/docs/assets/remote-settings/remote-settings-closing-dark-zh-CN.png differ diff --git a/docs/assets/remote-settings/remote-settings-closing-light-en-US.png b/docs/assets/remote-settings/remote-settings-closing-light-en-US.png new file mode 100644 index 000000000..1794dd59f Binary files /dev/null and b/docs/assets/remote-settings/remote-settings-closing-light-en-US.png differ diff --git a/docs/assets/remote-settings/remote-settings-drafts-dark-zh-CN.png b/docs/assets/remote-settings/remote-settings-drafts-dark-zh-CN.png index 0d83e76f0..5c49395f6 100644 Binary files a/docs/assets/remote-settings/remote-settings-drafts-dark-zh-CN.png and b/docs/assets/remote-settings/remote-settings-drafts-dark-zh-CN.png differ diff --git a/docs/assets/remote-settings/remote-settings-drafts-light-en-US.png b/docs/assets/remote-settings/remote-settings-drafts-light-en-US.png index c6a7d7c8d..60ae42798 100644 Binary files a/docs/assets/remote-settings/remote-settings-drafts-light-en-US.png and b/docs/assets/remote-settings/remote-settings-drafts-light-en-US.png differ diff --git a/scripts/desktop/build-desktop-core.sh b/scripts/desktop/build-desktop-core.sh index 3bcbbf477..e3d0d0edf 100755 --- a/scripts/desktop/build-desktop-core.sh +++ b/scripts/desktop/build-desktop-core.sh @@ -326,7 +326,12 @@ PINNED_CORE_REPOSITORY="https://github.com/Lithe-IDEA/Lithe-core-rust.git" # wsl.exe (the wsl field) and remote.listWslDistributions lists the installed ones (#2231). # Lithe-core-rust main at 49fb750: #158 remote.preferences and remote.editPreferences (SSH program, # reconnect limit) feed the remote commands, with the reconnect pauses given by Core (#2231). -PINNED_CORE_REVISION="62d44ce9a0fc25897737844781c5d0e3f286c4c7" +# Lithe-core-rust main at 62d44ce: #159 host forward rules and reverse forwards (#2231). +# Lithe-core-rust main at ac80382: #160 remote.connect runs the persistent host session and resumes +# a kept one; remote.disconnect ends or keeps the host programs; remote.runningPrograms, +# remote.endPrograms (all or the listed ones), the closePrograms preference and +# closing.idleTimeoutSeconds; #161 plans the run configurations of a remote workspace (#2231). +PINNED_CORE_REVISION="ac80382df327579a92dba105abd9fddceef29a29" PROFILE="debug" CHECKOUT_ONLY="no" while [[ $# -gt 0 ]]; do diff --git a/shared/i18n/features/remote-connections.json b/shared/i18n/features/remote-connections.json index 73949b132..ff53092c4 100644 --- a/shared/i18n/features/remote-connections.json +++ b/shared/i18n/features/remote-connections.json @@ -993,6 +993,219 @@ "desktop" ] }, + { + "id": "desktop.remote.close.title", + "description": "Remote workspace close question: title", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.close.running", + "description": "Remote workspace close question: the line before the list of programs the host runs; {connection} is the connection's name", + "platforms": [ + "desktop" + ], + "parameters": { + "connection": "string" + } + }, + { + "id": "desktop.remote.close.end", + "description": "Remote workspace close question: default button that ends the host's programs and closes", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.close.keep", + "description": "Remote workspace close question: button that keeps the host's programs running and closes", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.close.remember", + "description": "Remote workspace close question: checkbox that stores the answer", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.close.rememberHelp", + "description": "Remote workspace close question: help behind the info glyph of the Remember checkbox", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.close.kept", + "description": "Notification after closing a remote workspace kept its programs on the host; {count} is how many, {connection} the connection's name", + "platforms": [ + "desktop" + ], + "parameters": { + "connection": "string", + "count": "string" + } + }, + { + "id": "desktop.remote.close.keepFailed", + "description": "Notification: keeping the host's programs failed because the session could not be stored, so they ended; {connection} is the connection's name", + "platforms": [ + "desktop" + ], + "parameters": { + "connection": "string" + } + }, + { + "id": "desktop.remote.close.keepRefused", + "description": "Notification: the host did not confirm it kept the session; {connection} is the connection's name", + "platforms": [ + "desktop" + ], + "parameters": { + "connection": "string" + } + }, + { + "id": "desktop.remote.close.keepLost", + "description": "Notification: the connection was lost before the host's programs could be kept; {connection} is the connection's name", + "platforms": [ + "desktop" + ], + "parameters": { + "connection": "string" + } + }, + { + "id": "desktop.remote.close.rememberFailed", + "description": "Notification: the close question's remembered answer could not be stored", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.close.item", + "description": "Remote workspace program list: one program with a name; {kind} is Terminal or Process, {command} the command as it runs, {duration} how long it has run, as \"running for 5 min\"", + "platforms": [ + "desktop" + ], + "parameters": { + "kind": "string", + "name": "string", + "command": "string", + "duration": "string" + } + }, + { + "id": "desktop.remote.close.itemUnnamed", + "description": "Remote workspace program list: one program without a name; {kind} is Terminal or Process, {command} the command as it runs, {duration} how long it has run, as \"running for 5 min\"", + "platforms": [ + "desktop" + ], + "parameters": { + "kind": "string", + "command": "string", + "duration": "string" + } + }, + { + "id": "desktop.remote.close.kindTerminal", + "description": "Remote workspace program list: the kind of a terminal", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.close.kindProcess", + "description": "Remote workspace program list: the kind of a process", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.close.ranUnderMinute", + "description": "Remote workspace program list: a program has run less than a minute", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.close.ranMinutes", + "description": "Remote workspace program list: a program has run {count} whole minutes", + "platforms": [ + "desktop" + ], + "parameters": { + "count": "string" + } + }, + { + "id": "desktop.remote.close.ranHours", + "description": "Remote workspace program list: a program has run {hours} hours and {minutes} minutes", + "platforms": [ + "desktop" + ], + "parameters": { + "hours": "string", + "minutes": "string" + } + }, + { + "id": "desktop.remote.kept.title", + "description": "Question after connecting to a host session an earlier window kept: title", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.kept.text", + "description": "Question after connecting to a kept host session: the line before the list; {connection} is the connection's name, {count} how many programs", + "platforms": [ + "desktop" + ], + "parameters": { + "connection": "string", + "count": "string" + } + }, + { + "id": "desktop.remote.kept.end", + "description": "Question after connecting to a kept host session: button that ends the listed programs", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.kept.keep", + "description": "Question after connecting to a kept host session: default button that leaves the programs running", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.kept.ended", + "description": "Notification: the kept programs were ended; {count} is how many were still running, {connection} the connection's name", + "platforms": [ + "desktop" + ], + "parameters": { + "connection": "string", + "count": "string" + } + }, + { + "id": "desktop.remote.kept.endFailed", + "description": "Notification: the kept programs could not be ended; {connection} is the connection's name", + "platforms": [ + "desktop" + ], + "parameters": { + "connection": "string" + } + }, { "id": "desktop.remote.document.disconnected", "description": "Reason a file of a remote workspace could not be opened or saved, after “Could not open/save {name}: ”: the workspace has no connection", @@ -2693,6 +2906,30 @@ "desktop.remote.workspace.safeBanner": "This remote workspace is in safe mode: you can browse, edit, save and search its files on the host. Trust the folder to use Git.", "desktop.remote.workspace.gitAbove": "This folder is inside a Git repository that starts in a folder above it on the host. Open the repository's top folder to use Git in a remote workspace.", "desktop.remote.workspace.localOnly": "This feature does not work in a remote workspace yet. You can browse, edit, save and search the host's files, run terminals and use Git on the host.", + "desktop.remote.close.title": "Close the remote workspace?", + "desktop.remote.close.running": "These programs are still running on {connection}:", + "desktop.remote.close.end": "End and Close", + "desktop.remote.close.keep": "Keep on Host and Close", + "desktop.remote.close.remember": "Remember my choice", + "desktop.remote.close.rememberHelp": "Don't ask again. You can change this in Settings › Tools › Remote Workspace.", + "desktop.remote.close.kept": "Programs left running on {connection}: {count}", + "desktop.remote.close.keepFailed": "Could not store the session of {connection}, so its programs ended with the workspace.", + "desktop.remote.close.keepRefused": "{connection} did not confirm it kept the session. If it did not, the host ends its programs.", + "desktop.remote.close.keepLost": "The connection to {connection} was lost, so its programs could not be kept. The host ends them after its idle timeout.", + "desktop.remote.close.rememberFailed": "Could not remember this choice. Closing a remote workspace will ask again.", + "desktop.remote.close.item": "• {kind} “{name}”: {command} ({duration})", + "desktop.remote.close.itemUnnamed": "• {kind}: {command} ({duration})", + "desktop.remote.close.kindTerminal": "Terminal", + "desktop.remote.close.kindProcess": "Process", + "desktop.remote.close.ranUnderMinute": "running for less than a minute", + "desktop.remote.close.ranMinutes": "running for {count} min", + "desktop.remote.close.ranHours": "running for {hours} h {minutes} min", + "desktop.remote.kept.title": "Programs Kept on the Host", + "desktop.remote.kept.text": "A closed window kept these programs running on {connection} ({count}):", + "desktop.remote.kept.end": "End Them", + "desktop.remote.kept.keep": "Keep Running", + "desktop.remote.kept.ended": "Ended programs on {connection}: {count}", + "desktop.remote.kept.endFailed": "Could not end the programs kept on {connection}.", "desktop.remote.document.disconnected": "the remote workspace is not connected; try again once it reconnects", "desktop.remote.document.timedOut": "the host did not answer in time", "desktop.remote.document.notFound": "the file no longer exists on the host", @@ -3011,6 +3248,30 @@ "desktop.remote.workspace.safeBanner": "此远程工作区处于安全模式:可以浏览、编辑、保存和搜索主机上的文件。信任此文件夹后即可使用 Git。", "desktop.remote.workspace.gitAbove": "此文件夹位于主机上更上层文件夹开始的 Git 仓库中。请打开仓库的顶层文件夹,以便在远程工作区中使用 Git。", "desktop.remote.workspace.localOnly": "远程工作区暂不支持此功能,可以浏览、编辑、保存和搜索主机上的文件,也可以在主机上运行终端和使用 Git。", + "desktop.remote.close.title": "关闭远程工作区?", + "desktop.remote.close.running": "以下进程仍在 {connection} 上运行:", + "desktop.remote.close.end": "结束并关闭", + "desktop.remote.close.keep": "保留在远端并关闭", + "desktop.remote.close.remember": "记住我的选择", + "desktop.remote.close.rememberHelp": "之后不再询问,可在 设置 › 工具 › 远程工作区 中修改", + "desktop.remote.close.kept": "{count} 个进程保留在 {connection} 上", + "desktop.remote.close.keepFailed": "无法保存 {connection} 的会话,进程已随工作区结束。", + "desktop.remote.close.keepRefused": "{connection} 没有确认保留会话;如果没有保留,主机会结束这些进程。", + "desktop.remote.close.keepLost": "与 {connection} 的连接已断开,进程没能保留;主机会在空闲超时后结束它们。", + "desktop.remote.close.rememberFailed": "没能记住这个选择,下次关闭远程工作区时仍会询问。", + "desktop.remote.close.item": "• {kind}“{name}”:{command}({duration})", + "desktop.remote.close.itemUnnamed": "• {kind}:{command}({duration})", + "desktop.remote.close.kindTerminal": "终端", + "desktop.remote.close.kindProcess": "进程", + "desktop.remote.close.ranUnderMinute": "已运行不到 1 分钟", + "desktop.remote.close.ranMinutes": "已运行 {count} 分钟", + "desktop.remote.close.ranHours": "已运行 {hours} 小时 {minutes} 分钟", + "desktop.remote.kept.title": "上次保留的进程", + "desktop.remote.kept.text": "上次关闭时保留在 {connection} 上的 {count} 个进程仍在运行:", + "desktop.remote.kept.end": "结束这些进程", + "desktop.remote.kept.keep": "继续运行", + "desktop.remote.kept.ended": "已结束 {connection} 上的 {count} 个进程", + "desktop.remote.kept.endFailed": "无法结束 {connection} 上保留的进程。", "desktop.remote.document.disconnected": "远程工作区未连接,请在重新连接后再试", "desktop.remote.document.timedOut": "主机没有及时响应", "desktop.remote.document.notFound": "主机上已没有这个文件", diff --git a/shared/i18n/features/remote-settings.json b/shared/i18n/features/remote-settings.json index f543de1ed..66830c3c9 100644 --- a/shared/i18n/features/remote-settings.json +++ b/shared/i18n/features/remote-settings.json @@ -194,6 +194,69 @@ "desktop" ] }, + { + "id": "desktop.remoteSettings.closing", + "description": "Remote Workspace page: title of the card about closing a remote workspace", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remoteSettings.closePrograms", + "description": "Remote Workspace page: label of the row choosing what closing a workspace does to the programs on the host", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remoteSettings.closeProgramsHelp", + "description": "Remote Workspace page: help behind the info glyph of the host programs row", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remoteSettings.closeAsk", + "description": "Remote Workspace page: the automatic choice of the host programs row, which asks every time", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remoteSettings.closeAskSaved", + "description": "Remote Workspace page: the stored choice that asks every time", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remoteSettings.closeEnd", + "description": "Remote Workspace page: choice that ends the host programs on close", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remoteSettings.closeKeep", + "description": "Remote Workspace page: choice that keeps the host programs running on close", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remoteSettings.idleTimeout", + "description": "Remote Workspace page: label of the read-only row with the host session's idle timeout", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remoteSettings.idleTimeoutHelp", + "description": "Remote Workspace page: help behind the info glyph of the idle timeout row", + "platforms": [ + "desktop" + ] + }, { "id": "desktop.remoteSettings.damaged", "description": "Remote Workspace page: the preference file cannot be decoded; the path is shown", @@ -343,6 +406,15 @@ "desktop.remoteSettings.storage": "Stored in", "desktop.remoteSettings.storageHelp": "Only the values you change are kept, in this machine's preference folder. Nothing is written to a host.", "desktop.remoteSettings.storageNone": "Created when you change a value", + "desktop.remoteSettings.closing": "Closing", + "desktop.remoteSettings.closePrograms": "Host programs on close", + "desktop.remoteSettings.closeProgramsHelp": "What happens to the terminals and processes still running on the host when you close a remote workspace or its window, or quit Lithe. Kept programs are listed the next time you connect to the same host, where you can end them. Remember my choice in the close question changes this too.", + "desktop.remoteSettings.closeAsk": "Automatic (ask every time)", + "desktop.remoteSettings.closeAskSaved": "Ask every time", + "desktop.remoteSettings.closeEnd": "End them", + "desktop.remoteSettings.closeKeep": "Keep on host", + "desktop.remoteSettings.idleTimeout": "Idle timeout of host sessions", + "desktop.remoteSettings.idleTimeoutHelp": "After a connection is lost, the host keeps its session and programs this long, so reconnecting picks them up; then it ends them. A session whose programs you kept on the host does not time out. The remote server sets this, so it cannot be changed.", "desktop.remoteSettings.damaged": "{path} cannot be read. Fix or delete the file; until then no host is connected with it.", "desktop.remoteSettings.conflict": "The preference file changed meanwhile and was read again. Apply your change again.", "desktop.remoteSettings.unavailable": "There is no preference folder to keep these settings in.", @@ -386,6 +458,15 @@ "desktop.remoteSettings.storage": "保存位置", "desktop.remoteSettings.storageHelp": "只保存你改过的值,放在本机的偏好设置目录中,不会写到主机上。", "desktop.remoteSettings.storageNone": "修改后才创建", + "desktop.remoteSettings.closing": "关闭工作区", + "desktop.remoteSettings.closePrograms": "关闭时的远端进程", + "desktop.remoteSettings.closeProgramsHelp": "关闭远程工作区、它的窗口或退出 Lithe 时,主机上仍在运行的终端和进程怎么处理。保留在远端的进程,下次连接同一主机时会列出来,可以再结束。关闭时勾选“记住我的选择”也会改这里。", + "desktop.remoteSettings.closeAsk": "自动(每次询问)", + "desktop.remoteSettings.closeAskSaved": "每次询问", + "desktop.remoteSettings.closeEnd": "结束", + "desktop.remoteSettings.closeKeep": "保留在远端", + "desktop.remoteSettings.idleTimeout": "常驻会话的空闲超时", + "desktop.remoteSettings.idleTimeoutHelp": "连接断开后,主机在这段时间内保留会话和其中的进程,期间重连会接回它们,超时后结束。选择保留在远端的会话不会超时。这个时长由远端服务决定,不能修改。", "desktop.remoteSettings.damaged": "无法读取 {path}。请修正或删除这个文件;修好之前不会用它连接主机。", "desktop.remoteSettings.conflict": "设置文件在此期间被改过,已重新读取。请再次应用你的修改。", "desktop.remoteSettings.unavailable": "没有可以保存这些设置的偏好设置目录。", diff --git a/shared/platform-feature-matrix/features/remote-workspace.json b/shared/platform-feature-matrix/features/remote-workspace.json index b192a66ea..7031d3545 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 发行版)、远程路径工作区、主机文件编辑与监听、主机终端、主机搜索与替换、远程信任与主机 Git、端口转发(含主机侧转发规则与反向转发)、远程工作区设置(SSH 程序与断线重连)", + "capability": "远程连接(SSH 主机与本机 WSL 发行版)、远程路径工作区、主机文件编辑与监听、主机终端、主机搜索与替换、远程信任与主机 Git、端口转发(含主机侧转发规则与反向转发)、远程工作区设置(SSH 程序、断线重连与关闭时的远端进程)、关闭确认与保留远端进程", "macos": { "implementationStatus": "partial", "verificationStatus": "pending", @@ -44,9 +44,6 @@ "desktop/internal/core/remote_helpers_test.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", - "desktop/internal/workbench/remote_port_rules_test.go", "desktop/internal/workbench/remote_ports_test.go", "desktop/internal/workbench/remote_ports_visual_test.go", "desktop/internal/workbench/remote_wsl.go", @@ -58,7 +55,15 @@ "desktop/internal/settingswindow/remote_workspace_view.go", "desktop/internal/remoteconn/preferences_test.go", "desktop/internal/settingswindow/remote_workspace_view_test.go", - "desktop/internal/settingswindow/remote_workspace_visual_test.go" + "desktop/internal/settingswindow/remote_workspace_visual_test.go", + "desktop/internal/workbench/remote_close.go", + "desktop/internal/workbench/remote_close_test.go", + "desktop/internal/workbench/remote_close_visual_test.go", + "desktop/internal/remoteconn/kept.go", + "desktop/internal/remoteconn/kept_test.go", + "desktop/internal/workbench/remote_port_rules.go", + "desktop/internal/workbench/remote_port_rules_view.go", + "desktop/internal/workbench/remote_port_rules_test.go" ] }, "windows": { @@ -91,18 +96,20 @@ "desktop/internal/core/remote_forward.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", "desktop/internal/workbench/remote_wsl.go", "desktop/internal/core/remote_preferences.go", "desktop/internal/remoteconn/preferences.go", "desktop/internal/workbench/remote_preferences.go", "desktop/internal/settingswindow/remote_preferences_state.go", - "desktop/internal/settingswindow/remote_workspace_view.go" + "desktop/internal/settingswindow/remote_workspace_view.go", + "desktop/internal/workbench/remote_close.go", + "desktop/internal/remoteconn/kept.go", + "desktop/internal/workbench/remote_port_rules.go", + "desktop/internal/workbench/remote_port_rules_view.go" ] }, "owner": "Remote", - "verification": "在“远程开发”窗口选中已保存的 Linux SSH 连接点“连接”:SSH 询问出现在窗口中,连接后窗口改为主机的文件夹选择,从主目录开始列出子文件夹(跳过名称不是 UTF-8 的条目并说明数量),可输入 ~ 或 / 开头的路径跳转,不存在的路径说明原因且不能打开;“返回”断开这次会话回到连接表单。选中文件夹点“打开”:新标签页打开远程工作区,窗口标题为“文件夹 [SSH: 连接名]”,项目树经 Core 列出主机目录(本机占位目录始终为空),右键只有复制主机路径和刷新;以安全模式打开的文件夹,编辑器上方说明可以浏览、编辑、保存和搜索主机文件,信任文件夹后才能用 Git;受信任的文件夹说明文件、终端和 Git 都在主机上,运行、调试和语言服务器暂不可用;空白编辑区提示 Search Everywhere 和 Find in Files。在项目树双击文件:编辑器经会话读取主机文件(不超过 16 MiB),保存时带上打开时的大小和修改时间写回主机,新建的文件只在主机上不存在时创建;主机上的文件期间被别人改过时保存被拒绝并显示外部修改冲突,“加载磁盘版本”载入主机内容,本机占位目录始终为空。超过 8 MiB 的保存说明主机单次保存上限,编辑内容保留;主机上缺失、无权限、不是普通文件、超时和连接断开分别说明原因,连接断开后自动重连并把打开的文档和主机重新比对。图片、PDF 等查看器、文件夹外的文件、本地历史和插件终端都被拒绝并提示,不回退到本机。打开“终端”工具窗口:经会话的 remote.runTerminal 在主机文件夹运行主机账户的登录 shell(不带参数,不读本机 Shell 设置,没有本机 Shell 菜单),标签名为连接名,之后的标签为“连接名 (2)”等;输入按顺序、每块不超过 32 KiB 写入,主机说忙时稍后重试,窗口尺寸随输入发送;输出超过 8 MiB 未显示时丢弃最旧的部分并记一次失败。程序退出显示退出码,被信号结束显示 128+信号,关闭标签不算失败。连接断开时终端显示会话已结束,工作区按退避重连;未连接时按回车说明工作区未连接,重连后按回车在新会话上运行。终端起不来时显示 Core 给出的原因(可能含主机路径),日志只记命令名和错误码。拖到终端的文件粘贴为主机路径并按 POSIX shell 加引号,本机工作区外的文件不粘贴并提示原因;粘贴图片不可用(图片会存到本机)。每个会话连接后,经 remote.runWatch 在主机上递归监听整个文件夹,跳过已启用插件隐藏的文件夹名(按原样比较大小写),插件改变隐藏名称时重新开始监听;在主机上新建、修改、删除文件后,项目树重新列出受影响的目录(Core 的 workspace.filterChanges 按可见性规则过滤,不需要会话),打开的文档与主机比对:没有编辑的重新载入,有编辑的显示外部修改冲突;文件夹外和被隐藏文件夹里的变化不触发列表。监听开始时、主机丢失变化(overflow)时、一次超过 4096 个变化时,重新列出树中展开的目录并比对所有文档,日志每次监听各记一次;主机监听数用尽时其余部分继续监听,提示一次“项目文件可能无法自动更新”。监听中文件夹被删除或移走时立即重新监听;主机找不到文件夹时项目树显示根目录不可用,监听等树重新列出文件夹后再开始,主机与树结论不一致时也只等待、不反复重试。其他监听失败只记命令名和错误码、提示一次,等下一个会话再开始;监听发现连接断开时与心跳一样结束会话并重连。Find in Files 的搜索、计数和替换预览带远程绑定发送,Core 从主机文件夹建立索引并读取主机上的当前内容,结果路径相对主机文件夹;点结果在远程编辑器打开主机文件并定位到匹配处,本机占位目录始终为空。主机监听报告的变化路径在下一次查询前增量更新索引,不重建;监听开始和主机丢失变化时重建一次。包含生成文件的查询每次都重建索引(主机监听跳过插件隐藏的文件夹);主机监听数用尽后、会话断开到下一个会话的监听开始之间,每次查询都重建,只由监听提示一次“项目文件可能无法自动更新”,搜索不再另外提示。查询显示期间主机上的变化让结果重新查询。Search Everywhere 所有页签都可用,文件名和文本来自主机,打开弹窗时重新读取生成文件的名称;远程工作区不启动语言服务器,符号只有 Core 在主机文件中找到的。Replace All 在编辑器中替换打开的文档;未打开的文件经会话读取主机内容,由 Core 替换后,只在主机文件仍是读取时的内容时写回,期间被改过的报告冲突,已被删除的说明主机上找不到文件,其余文件照常替换,都不写本机占位目录。在文件夹选择中打开从未决定过的文件夹:先询问是否信任(显示连接名和主机文件夹,Core 给出上级文件夹时可勾选信任其下的所有文件夹),“信任并打开”把决定按连接名记入 Core 的远程信任记录后以受信任方式打开,“以安全模式打开”只读打开,“返回”回到文件夹选择;之前决定过的文件夹直接按记录打开。安全模式下 Git、提交和日志窗口与本机项目一样说明需要信任,编辑器上方的提示里可以信任文件夹,信任后不重开窗口就在主机上启动 Git。受信任的工作区经会话在主机上运行 Git:状态、暂存、提交、差异(含编辑器行号旁的变更标记)、日志与分支、逐行追溯(读取主机上的文件内容)、搁置与储藏都读写主机仓库,本机占位目录始终没有 .git;“排除到本地”写入主机仓库的 info/exclude(缺少 info 文件夹时在主机上创建,读写期间文件被别人改过时这次排除失败、不覆盖)。同一会话经 remote.runWatch 递归监听主机仓库的 git 目录(公共目录在别处时一并监听),主机上 git checkout、commit 等改动元数据后按路径分类并重新读取状态;监听开始、丢失变化或主机监听数用尽时重新读取一次完整状态,新会话重新开始监听。主机文件夹位于上级目录开始的仓库内时,Git 和提交窗口说明要打开仓库顶层文件夹,不显示变更也不记为失败。工作树列表、锁定、解锁、删除在主机上执行,复制路径复制主机路径;打开、在新窗口打开、在文件浏览器中显示和新建工作树被拒绝并提示。受信任的远程工作区里运行、调试、当前文件运行、测试、构建任务和插件语言服务器都不在本机启动,都记为拒绝并提示,运行、测试和构建工具窗口说明暂不可用。状态栏前端显示连接名和心跳往返时间;连续两次心跳无响应显示“无响应”,第三次结束会话并按 Core 由“自动重连时长”给出的间隔重连(默认 1、2、4、8、16、29 秒,共 60 秒),每次失败后等下一个间隔,用完后显示“已断开”和原因,菜单里可“重新连接”;连接被关闭时同样按这些间隔重连;时长设为“不自动重连”时直接显示“已断开”。菜单里“断开并关闭”关闭工作区并结束会话,退出 Lithe 时关闭所有远程会话。最近项目不记录远程工作区。日志只有 remote.connect、remote.workspace.open/reconnect/disconnect 等动作和失败的操作名,不含主机、用户名、主机路径或主目录。运行 remote_workspace_test.go 的 5 个测试、remote_git_test.go 的 6 个测试、remoteplaceholder 的 TestHostAndLocalPathsMapBothWays、remote_documents_test.go 的 2 个测试、remote_terminal_test.go 的 9 个测试、remote_watch_test.go 的 5 个测试、remote_search_test.go 的 4 个测试、internal/core 的 TestRemoteTerminal*、TestRemoteWatch* 与 TestRemoteWorkspaceFiltersChangesWithoutTheHost、termview 的 TestOpenStartsTheProgramElsewhere,以及 TestVisualRemoteWorkspace 无头截图;在 Windows 运行 TestCoreRefusesUnadaptedCommandsAndAClosedSessionDetachesTheBinding,验证 Linux 主机路径能通过绑定校验。真实 SSH 主机上的整机验收(包括终端里 vim、top 等全屏程序与窗口缩放,主机上 git checkout 等大批量修改后的监听,以及大仓库上的搜索)仍待完成。远程工作区左侧多出“端口”工具窗口(本机工作区没有,关闭工作区后消失):窗口打开时每 3 秒经 ports.listening 读取主机上正在监听的端口和会话的转发,窗口关闭或未显示时停止读取;同一端口在 0.0.0.0 与 :: 上监听只显示一行;远端端口带上主机监听的 IP 地址,多个地址时显示第一个和其余数量,悬停提示列出全部,地址或网址过长被截断时悬停提示给出全文;列出远端端口、本机地址、进程(名称与 PID,读不到时为“未知”)、来源(监听发现、手动添加)和状态。默认不自动转发任何端口,打开窗口和发现新端口都不转发;行尾“转发”把端口转发到主机上对应族的回环地址,本机在 127.0.0.1 的同号端口监听,该端口被本机其他程序占用时改用空闲端口,本机地址用警告色显示并在提示里说明原端口。右键“转发到指定本机端口…”和已转发行的“更改本机端口…”打开对话框输入 1–65535 的本机端口,非法输入就地说明且不转发;改到另一个端口时先停止原转发再在新端口转发,选择在工作区打开期间保留,停止后再转发仍用该端口。顶部输入端口、主机:端口或网址(http、https、ws、wss,省略端口时按协议默认端口)可手动添加并转发,由 Core 的 remote.parseForwardAddress 解析;格式不对就地说明,网址里带用户名或密码时拒绝并说明,输入框保留原文、日志不记输入内容;同一目标再次添加不重复。网址行按输入的样子显示,转发到主机上提供该端口的回环地址;在浏览器打开和复制本机地址把主机部分换成本机地址并保留路径和查询,ws/wss 网址不提供在浏览器打开;浏览器打不开时提示网址,日志只记失败、不记网址。主机回环地址以外的目标先询问(S28),确认后才带 AllowNonLoopback 转发,取消记为拒绝。已转发行可在浏览器打开、复制本机地址、停止;手动添加且已停止、主机上也没有在监听的行可移除;窗口标题栏可全部停止,标题栏的 ⓘ 说明转发对本机其他程序可见(S30);会话转发数达到 Core 上限时说明上限;状态栏显示已转发数量,点击打开端口窗口;会话结束时转发随之结束,重连后不自动恢复。日志只记 remote.ports.forward/localPort/move/stop/status 等动作和失败操作名,不含主机、地址或进程名。运行 remote_ports_test.go 的 12 个测试、internal/core 的 TestRemoteSessionCommandsOfAnUnknownSession 与 TestRemoteParseForwardAddressReadsPortsAndURLs,以及 TestVisualRemotePorts 无头截图。手动添加的端口和本机端口选择只在工作区打开期间保留,关闭后不保存(需 Core 存储,后续阶段)。端口窗口标题栏的“+”打开“添加转发规则”:方向默认“主机端口 → 另一台服务器”,由主机自己连接目标,数据不经过本机;主机端口可留空由主机选择,目标接受端口、主机:端口或网址(由 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 小时,保存过的其他值也列出。“反向转发”默认“自动(不允许)”,可选允许或不允许,ⓘ 说明主机上的所有用户都能连接反向转发的端口、每条规则仍会确认。“保存位置”显示偏好目录下的 remote/preferences.json,还没有文件时注明修改后才创建。修改只是草稿:侧栏和底部显示未应用数量,“应用”或“好”经 Core 的 remote.editPreferences 写入(程序先于时长),写入后重新读取显示;Core 拒绝相对路径、不存在、不可执行的程序或超出 0–3600 秒的时长时在页面说明原因并保留草稿,不写文件;文件期间被改过时重新读取并请用户再次应用;文件损坏时说明路径、不提供编辑,此时连接、测试连接、读取有效设置和导入 SSH 主机都失败并说明原因,不用未经用户选择的程序启动 OpenSSH。选中的 SSH 程序用于连接、测试连接、有效设置和 SSH 配置导入(WSL 经 wsl.exe 启动,不使用它)。日志只记 remote_preferences_settings_load/save 等操作名和 Core 错误码,不记路径。运行 settingswindow 的 TestRemoteWorkspace* 5 个测试、remoteconn 的 preferences_test.go、internal/core 的 TestRemotePreferences*,以及 TestVisualRemoteWorkspace 无头截图(中英文、深浅色,自动值与草稿两种状态)。", + "verification": "在“远程开发”窗口选中已保存的 Linux SSH 连接点“连接”:SSH 询问出现在窗口中,连接后窗口改为主机的文件夹选择,从主目录开始列出子文件夹(跳过名称不是 UTF-8 的条目并说明数量),可输入 ~ 或 / 开头的路径跳转,不存在的路径说明原因且不能打开;“返回”断开这次会话回到连接表单。选中文件夹点“打开”:新标签页打开远程工作区,窗口标题为“文件夹 [SSH: 连接名]”,项目树经 Core 列出主机目录(本机占位目录始终为空),右键只有复制主机路径和刷新;以安全模式打开的文件夹,编辑器上方说明可以浏览、编辑、保存和搜索主机文件,信任文件夹后才能用 Git;受信任的文件夹说明文件、终端和 Git 都在主机上,运行、调试和语言服务器暂不可用;空白编辑区提示 Search Everywhere 和 Find in Files。在项目树双击文件:编辑器经会话读取主机文件(不超过 16 MiB),保存时带上打开时的大小和修改时间写回主机,新建的文件只在主机上不存在时创建;主机上的文件期间被别人改过时保存被拒绝并显示外部修改冲突,“加载磁盘版本”载入主机内容,本机占位目录始终为空。超过 8 MiB 的保存说明主机单次保存上限,编辑内容保留;主机上缺失、无权限、不是普通文件、超时和连接断开分别说明原因,连接断开后自动重连并把打开的文档和主机重新比对。图片、PDF 等查看器、文件夹外的文件、本地历史和插件终端都被拒绝并提示,不回退到本机。打开“终端”工具窗口:经会话的 remote.runTerminal 在主机文件夹运行主机账户的登录 shell(不带参数,不读本机 Shell 设置,没有本机 Shell 菜单),标签名为连接名,之后的标签为“连接名 (2)”等;输入按顺序、每块不超过 32 KiB 写入,主机说忙时稍后重试,窗口尺寸随输入发送;输出超过 8 MiB 未显示时丢弃最旧的部分并记一次失败。程序退出显示退出码,被信号结束显示 128+信号,关闭标签不算失败。连接断开时终端显示会话已结束,工作区按退避重连;未连接时按回车说明工作区未连接,重连后按回车在新会话上运行。终端起不来时显示 Core 给出的原因(可能含主机路径),日志只记命令名和错误码。拖到终端的文件粘贴为主机路径并按 POSIX shell 加引号,本机工作区外的文件不粘贴并提示原因;粘贴图片不可用(图片会存到本机)。每个会话连接后,经 remote.runWatch 在主机上递归监听整个文件夹,跳过已启用插件隐藏的文件夹名(按原样比较大小写),插件改变隐藏名称时重新开始监听;在主机上新建、修改、删除文件后,项目树重新列出受影响的目录(Core 的 workspace.filterChanges 按可见性规则过滤,不需要会话),打开的文档与主机比对:没有编辑的重新载入,有编辑的显示外部修改冲突;文件夹外和被隐藏文件夹里的变化不触发列表。监听开始时、主机丢失变化(overflow)时、一次超过 4096 个变化时,重新列出树中展开的目录并比对所有文档,日志每次监听各记一次;主机监听数用尽时其余部分继续监听,提示一次“项目文件可能无法自动更新”。监听中文件夹被删除或移走时立即重新监听;主机找不到文件夹时项目树显示根目录不可用,监听等树重新列出文件夹后再开始,主机与树结论不一致时也只等待、不反复重试。其他监听失败只记命令名和错误码、提示一次,等下一个会话再开始;监听发现连接断开时与心跳一样结束会话并重连。Find in Files 的搜索、计数和替换预览带远程绑定发送,Core 从主机文件夹建立索引并读取主机上的当前内容,结果路径相对主机文件夹;点结果在远程编辑器打开主机文件并定位到匹配处,本机占位目录始终为空。主机监听报告的变化路径在下一次查询前增量更新索引,不重建;监听开始和主机丢失变化时重建一次。包含生成文件的查询每次都重建索引(主机监听跳过插件隐藏的文件夹);主机监听数用尽后、会话断开到下一个会话的监听开始之间,每次查询都重建,只由监听提示一次“项目文件可能无法自动更新”,搜索不再另外提示。查询显示期间主机上的变化让结果重新查询。Search Everywhere 所有页签都可用,文件名和文本来自主机,打开弹窗时重新读取生成文件的名称;远程工作区不启动语言服务器,符号只有 Core 在主机文件中找到的。Replace All 在编辑器中替换打开的文档;未打开的文件经会话读取主机内容,由 Core 替换后,只在主机文件仍是读取时的内容时写回,期间被改过的报告冲突,已被删除的说明主机上找不到文件,其余文件照常替换,都不写本机占位目录。在文件夹选择中打开从未决定过的文件夹:先询问是否信任(显示连接名和主机文件夹,Core 给出上级文件夹时可勾选信任其下的所有文件夹),“信任并打开”把决定按连接名记入 Core 的远程信任记录后以受信任方式打开,“以安全模式打开”只读打开,“返回”回到文件夹选择;之前决定过的文件夹直接按记录打开。安全模式下 Git、提交和日志窗口与本机项目一样说明需要信任,编辑器上方的提示里可以信任文件夹,信任后不重开窗口就在主机上启动 Git。受信任的工作区经会话在主机上运行 Git:状态、暂存、提交、差异(含编辑器行号旁的变更标记)、日志与分支、逐行追溯(读取主机上的文件内容)、搁置与储藏都读写主机仓库,本机占位目录始终没有 .git;“排除到本地”写入主机仓库的 info/exclude(缺少 info 文件夹时在主机上创建,读写期间文件被别人改过时这次排除失败、不覆盖)。同一会话经 remote.runWatch 递归监听主机仓库的 git 目录(公共目录在别处时一并监听),主机上 git checkout、commit 等改动元数据后按路径分类并重新读取状态;监听开始、丢失变化或主机监听数用尽时重新读取一次完整状态,新会话重新开始监听。主机文件夹位于上级目录开始的仓库内时,Git 和提交窗口说明要打开仓库顶层文件夹,不显示变更也不记为失败。工作树列表、锁定、解锁、删除在主机上执行,复制路径复制主机路径;打开、在新窗口打开、在文件浏览器中显示和新建工作树被拒绝并提示。受信任的远程工作区里运行、调试、当前文件运行、测试、构建任务和插件语言服务器都不在本机启动,都记为拒绝并提示,运行、测试和构建工具窗口说明暂不可用。状态栏前端显示连接名和心跳往返时间;连续两次心跳无响应显示“无响应”,第三次结束会话并按 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、remote_documents_test.go 的 2 个测试、remote_terminal_test.go 的 9 个测试、remote_watch_test.go 的 5 个测试、remote_search_test.go 的 4 个测试、internal/core 的 TestRemoteTerminal*、TestRemoteWatch* 与 TestRemoteWorkspaceFiltersChangesWithoutTheHost、termview 的 TestOpenStartsTheProgramElsewhere,以及 TestVisualRemoteWorkspace 无头截图;在 Windows 运行 TestCoreRefusesUnadaptedCommandsAndAClosedSessionDetachesTheBinding,验证 Linux 主机路径能通过绑定校验。真实 SSH 主机上的整机验收(包括终端里 vim、top 等全屏程序与窗口缩放,主机上 git checkout 等大批量修改后的监听,以及大仓库上的搜索)仍待完成。远程工作区左侧多出“端口”工具窗口(本机工作区没有,关闭工作区后消失):窗口打开时每 3 秒经 ports.listening 读取主机上正在监听的端口和会话的转发,窗口关闭或未显示时停止读取;同一端口在 0.0.0.0 与 :: 上监听只显示一行;远端端口带上主机监听的 IP 地址,多个地址时显示第一个和其余数量,悬停提示列出全部,地址或网址过长被截断时悬停提示给出全文;列出远端端口、本机地址、进程(名称与 PID,读不到时为“未知”)、来源(监听发现、手动添加)和状态。默认不自动转发任何端口,打开窗口和发现新端口都不转发;行尾“转发”把端口转发到主机上对应族的回环地址,本机在 127.0.0.1 的同号端口监听,该端口被本机其他程序占用时改用空闲端口,本机地址用警告色显示并在提示里说明原端口。右键“转发到指定本机端口…”和已转发行的“更改本机端口…”打开对话框输入 1–65535 的本机端口,非法输入就地说明且不转发;改到另一个端口时先停止原转发再在新端口转发,选择在工作区打开期间保留,停止后再转发仍用该端口。顶部输入端口、主机:端口或网址(http、https、ws、wss,省略端口时按协议默认端口)可手动添加并转发,由 Core 的 remote.parseForwardAddress 解析;格式不对就地说明,网址里带用户名或密码时拒绝并说明,输入框保留原文、日志不记输入内容;同一目标再次添加不重复。网址行按输入的样子显示,转发到主机上提供该端口的回环地址;在浏览器打开和复制本机地址把主机部分换成本机地址并保留路径和查询,ws/wss 网址不提供在浏览器打开;浏览器打不开时提示网址,日志只记失败、不记网址。主机回环地址以外的目标先询问(S28),确认后才带 AllowNonLoopback 转发,取消记为拒绝。已转发行可在浏览器打开、复制本机地址、停止;手动添加且已停止、主机上也没有在监听的行可移除;窗口标题栏可全部停止,标题栏的 ⓘ 说明转发对本机其他程序可见(S30);会话转发数达到 Core 上限时说明上限;状态栏显示已转发数量,点击打开端口窗口;会话结束时转发随之结束,重连后不自动恢复。日志只记 remote.ports.forward/localPort/move/stop/status 等动作和失败操作名,不含主机、地址或进程名。运行 remote_ports_test.go 的 12 个测试、internal/core 的 TestRemoteSessionCommandsOfAnUnknownSession 与 TestRemoteParseForwardAddressReadsPortsAndURLs,以及 TestVisualRemotePorts 无头截图。手动添加的端口和本机端口选择只在工作区打开期间保留,关闭后不保存(需 Core 存储,后续阶段)。端口窗口标题栏的“+”打开“添加转发规则”:方向默认“主机端口 → 另一台服务器”,由主机自己连接目标,数据不经过本机;主机端口可留空由主机选择,目标接受端口、主机:端口或网址(由 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 主机上关闭后保留、重连接回和结束保留进程的整机验收,以及保留进程的输出重新接回终端和运行窗口(后续阶段),仍待完成。", "legacy": { "revision": "5a54c41aa37a4e6e6b68918a4b05765b9dd07a36", "macos": { @@ -139,5 +146,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 的默认值,所以保存了其他值时也能显示自动值。" + "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 写入同一份偏好文档。进程名称和命令只在对话框里显示,不写日志。" }