Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -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`,才会出现在关闭确认里。不要在桌面端另记一份进程列表。
27 changes: 24 additions & 3 deletions desktop/internal/core/remote_preferences.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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 {
Expand All @@ -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"`
}
Expand All @@ -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,
Expand All @@ -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"`
Expand Down
138 changes: 131 additions & 7 deletions desktop/internal/core/remote_session.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
}

Expand Down Expand Up @@ -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
Expand Down
Loading
Loading