diff --git a/desktop/internal/core/remote.go b/desktop/internal/core/remote.go index adaddd59a..a9eda7f8f 100644 --- a/desktop/internal/core/remote.go +++ b/desktop/internal/core/remote.go @@ -279,11 +279,14 @@ type RemoteProbeResult struct { // challenge with Remote set, answered with RemoteAuthRespond; without a prompt each question is // cancelled at once. Core bounds a probe, answers included, to five minutes. The probe changes // nothing, so an observation failure is reported only when the request itself succeeded. -func (c *Client) RemoteProbe(ctx context.Context, connection SSHConnection) (RemoteProbeResult, error) { +// preferences is the remote workspace preference document, or nil; it names the SSH program, and +// a damaged one fails with CodeParseFailed before OpenSSH starts. +func (c *Client) RemoteProbe(ctx context.Context, connection SSHConnection, preferences *string) (RemoteProbeResult, error) { var result RemoteProbeResult observationErr, err := c.executeRemoteWithPrompts(ctx, "remote.probe", struct { - Connection SSHConnection `json:"connection"` - }{connection}, &result) + Connection SSHConnection `json:"connection"` + Preferences *string `json:"preferences,omitempty"` + }{connection, preferences}, &result) if err != nil { return RemoteProbeResult{}, err } diff --git a/desktop/internal/core/remote_helpers.go b/desktop/internal/core/remote_helpers.go index b0c6eb5b9..d97ece04d 100644 --- a/desktop/internal/core/remote_helpers.go +++ b/desktop/internal/core/remote_helpers.go @@ -76,12 +76,14 @@ type RemoteEffectiveSettings struct { // RemoteEffectiveSettings asks OpenSSH what it would use for connection, without connecting. // Core bounds the run to 10 seconds: CodeRuntimeMissing without ssh, CodeProcessFailed with the -// redacted standard error in Details, CodeTimedOut and CodeParseFailed. -func (c *Client) RemoteEffectiveSettings(ctx context.Context, connection SSHConnection) (RemoteEffectiveSettings, error) { +// redacted standard error in Details, CodeTimedOut and CodeParseFailed. preferences is the +// remote workspace preference document, or nil, naming the SSH program. +func (c *Client) RemoteEffectiveSettings(ctx context.Context, connection SSHConnection, preferences *string) (RemoteEffectiveSettings, error) { var settings RemoteEffectiveSettings err := c.Execute(ctx, "remote.effectiveSettings", struct { - Connection SSHConnection `json:"connection"` - }{connection}, &settings) + Connection SSHConnection `json:"connection"` + Preferences *string `json:"preferences,omitempty"` + }{connection, preferences}, &settings) return settings, err } @@ -135,13 +137,15 @@ type RemoteSSHConfigHosts struct { // RemoteSSHConfigHosts reads ~/.ssh/config below homeDirectory, an absolute path, and checks each // host against document, the saved connections or nil. Core runs `ssh -G` for each alias within -// 30 seconds for the whole list; CodeRuntimeMissing without ssh. -func (c *Client) RemoteSSHConfigHosts(ctx context.Context, homeDirectory string, document *string) (RemoteSSHConfigHosts, error) { +// 30 seconds for the whole list; CodeRuntimeMissing without ssh. preferences is the remote +// workspace preference document, or nil, naming the SSH program. +func (c *Client) RemoteSSHConfigHosts(ctx context.Context, homeDirectory string, document, preferences *string) (RemoteSSHConfigHosts, error) { var hosts RemoteSSHConfigHosts err := c.Execute(ctx, "remote.sshConfigHosts", struct { HomeDirectory string `json:"homeDirectory"` Document *string `json:"document"` - }{homeDirectory, document}, &hosts) + Preferences *string `json:"preferences,omitempty"` + }{homeDirectory, document, preferences}, &hosts) hosts.Files = nonNil(hosts.Files) hosts.Hosts = nonNil(hosts.Hosts) return hosts, err diff --git a/desktop/internal/core/remote_helpers_test.go b/desktop/internal/core/remote_helpers_test.go index e131c0369..5890c36b2 100644 --- a/desktop/internal/core/remote_helpers_test.go +++ b/desktop/internal/core/remote_helpers_test.go @@ -131,7 +131,7 @@ func TestRemoteEffectiveSettingsNameTheirSources(t *testing.T) { "hostname 192.0.2.10\nuser dev\nport 2222\nidentityfile ~/.ssh/build_key\nconnecttimeout 15\nserveraliveinterval 0\nproxyjump jump-box", "hostname build-box\nuser localdev\nport 22\nidentityfile ~/.ssh/id_ed25519\nconnecttimeout 15\nserveraliveinterval 0\nproxyjump none", ) - settings, err := NewClient().RemoteEffectiveSettings(testContext(t), SSHConnection{Host: "build-box", User: "dev"}) + settings, err := NewClient().RemoteEffectiveSettings(testContext(t), SSHConnection{Host: "build-box", User: "dev"}, nil) if err != nil { t.Fatalf("effective settings: %v", err) } @@ -159,7 +159,7 @@ func TestRemoteSSHConfigHostsListTheAliases(t *testing.T) { if err := os.WriteFile(filepath.Join(home, ".ssh", "config"), []byte("Host build-box\n HostName 192.0.2.10\n\nHost *.lab\n User dev\n"), 0o600); err != nil { t.Fatal(err) } - hosts, err := NewClient().RemoteSSHConfigHosts(testContext(t), home, nil) + hosts, err := NewClient().RemoteSSHConfigHosts(testContext(t), home, nil, nil) if err != nil || len(hosts.Files) != 1 || len(hosts.Hosts) != 2 { t.Fatalf("hosts = %+v, err = %v", hosts, err) } diff --git a/desktop/internal/core/remote_preferences.go b/desktop/internal/core/remote_preferences.go new file mode 100644 index 000000000..c750998e8 --- /dev/null +++ b/desktop/internal/core/remote_preferences.go @@ -0,0 +1,121 @@ +package core + +import "context" + +// Remote workspace preferences: the values of the settings page Tools › Remote Workspace. The +// document is machine-local; the desktop reads and publishes it like the saved connections, and +// Core validates it, applies one edit at a time and tells what each automatic value resolves to. + +// RemotePreferenceSource says whether a value is the user's setting or the automatic one. +type RemotePreferenceSource string + +const ( + // RemotePreferenceFromSetting is a value the user chose. + RemotePreferenceFromSetting RemotePreferenceSource = "setting" + // RemotePreferenceAutomatic is the value Core picks when the user chose none. + RemotePreferenceAutomatic RemotePreferenceSource = "automatic" +) + +// RemoteProgramStatus is what is at the SSH program path when the page reads it. +type RemoteProgramStatus string + +const ( + // RemoteProgramFound is an executable file. + RemoteProgramFound RemoteProgramStatus = "found" + // RemoteProgramMissing is nothing at the saved path; for the automatic value, no ssh on + // PATH, so Core starts the bare name ssh for the system to look up. + RemoteProgramMissing RemoteProgramStatus = "missing" + // RemoteProgramNotExecutable is a directory or a file that cannot be run. + RemoteProgramNotExecutable RemoteProgramStatus = "notExecutable" +) + +// RemotePreferenceValues are the stored values; nil is automatic. +type RemotePreferenceValues struct { + SSHProgram *string `json:"sshProgram"` + ReconnectLimitSeconds *uint32 `json:"reconnectLimitSeconds"` +} + +// RemoteSSHProgram is the OpenSSH client Core starts. Path is nil only when the automatic +// value finds no ssh on PATH. +type RemoteSSHProgram struct { + Source RemotePreferenceSource `json:"source"` + Path *string `json:"path"` + Status RemoteProgramStatus `json:"status"` +} + +// RemoteReconnect is how a dropped session is reconnected: one attempt after each pause in +// DelaysMilliseconds, which add up to LimitSeconds. No pauses means no automatic reconnect. +type RemoteReconnect struct { + Source RemotePreferenceSource `json:"source"` + LimitSeconds uint32 `json:"limitSeconds"` + DelaysMilliseconds []uint64 `json:"delaysMilliseconds"` +} + +// RemotePreferenceStorage is where the document lives below the application's preference root. +type RemotePreferenceStorage struct { + RelativePath string `json:"relativePath"` + MaximumBytes int64 `json:"maximumBytes"` +} + +// RemoteSSHConfigFile is the user's ~/.ssh/config. +type RemoteSSHConfigFile struct { + Path string `json:"path"` + Exists bool `json:"exists"` +} + +// RemotePreferences is what remote.preferences reports. SSHConfig is set only when a home +// directory was given. +type RemotePreferences struct { + Preferences RemotePreferenceValues `json:"preferences"` + SSH RemoteSSHProgram `json:"ssh"` + Reconnect RemoteReconnect `json:"reconnect"` + Storage RemotePreferenceStorage `json:"storage"` + SSHConfig *RemoteSSHConfigFile `json:"sshConfig"` +} + +// RemotePreferences reads document, the preference document's text or nil when there is none. +// homeDirectory, an absolute path or empty, adds the SSH configuration file. A document that +// cannot be decoded fails with CodeParseFailed; a relative home directory with +// CodeInvalidRequest naming homeDirectory in RemoteConnectionFieldError. +func (c *Client) RemotePreferences(ctx context.Context, document *string, homeDirectory string) (RemotePreferences, error) { + var result RemotePreferences + err := c.Execute(ctx, "remote.preferences", struct { + Document *string `json:"document"` + HomeDirectory string `json:"homeDirectory,omitempty"` + }{document, homeDirectory}, &result) + result.Reconnect.DelaysMilliseconds = nonNil(result.Reconnect.DelaysMilliseconds) + return result, err +} + +// RemotePreferenceEdit changes one value: set exactly one field. A nil Path or Seconds makes the +// value automatic again. +type RemotePreferenceEdit struct { + SSHProgram *RemoteSSHProgramEdit `json:"sshProgram,omitempty"` + ReconnectLimit *RemoteReconnectLimitEdit `json:"reconnectLimit,omitempty"` +} + +// RemoteSSHProgramEdit sets the SSH program to an absolute path of an executable file. +type RemoteSSHProgramEdit struct { + Path *string `json:"path"` +} + +// RemoteReconnectLimitEdit sets how long a dropped session is reconnected, 0 to 3600 seconds. +type RemoteReconnectLimitEdit struct { + Seconds *uint32 `json:"seconds"` +} + +// EditRemotePreferences applies edit to document. changed is false, and the document nil, when +// nothing changes. A refused value fails with CodeInvalidRequest and names sshProgram or +// reconnectLimitSeconds with the reason (invalid, tooLong, relative, missing, notExecutable, +// outOfRange) in RemoteConnectionFieldError; a damaged document fails with CodeParseFailed. +func (c *Client) EditRemotePreferences(ctx context.Context, document *string, edit RemotePreferenceEdit) (changed bool, updated *string, err error) { + var result struct { + Changed bool `json:"changed"` + Document *string `json:"document"` + } + err = c.Execute(ctx, "remote.editPreferences", struct { + Document *string `json:"document"` + RemotePreferenceEdit + }{document, edit}, &result) + return result.Changed, result.Document, err +} diff --git a/desktop/internal/core/remote_session.go b/desktop/internal/core/remote_session.go index 363ab7477..7fcc2440d 100644 --- a/desktop/internal/core/remote_session.go +++ b/desktop/internal/core/remote_session.go @@ -38,6 +38,9 @@ type RemoteConnectRequest struct { ServerVersion string `json:"serverVersion"` // InstallRoot is where the host keeps installed servers; empty is $HOME/.lithe-server. InstallRoot string `json:"installRoot,omitempty"` + // Preferences is the remote workspace preference document, or nil. It names the SSH program; + // a WSL connection ignores it. + Preferences *string `json:"preferences,omitempty"` } // WSLConnection is a distribution of the Windows Subsystem for Linux on this machine, as diff --git a/desktop/internal/core/remote_session_test.go b/desktop/internal/core/remote_session_test.go index 3db7f075b..92ce629e5 100644 --- a/desktop/internal/core/remote_session_test.go +++ b/desktop/internal/core/remote_session_test.go @@ -199,7 +199,7 @@ func TestRemoteConnectAsksThroughTheHostAndSendsNoUnreadableBuild(t *testing.T) var probe RemoteProbeResult var probeErr error finishesWithin(t, "probe", testDeadline, func() { - probe, probeErr = client.RemoteProbe(WithGitAuthentication(testContext(t), prompt), connection) + probe, probeErr = client.RemoteProbe(WithGitAuthentication(testContext(t), prompt), connection, nil) }) if probeErr != nil || probe.Host == nil { t.Fatalf("probe = %+v, %v", probe, probeErr) diff --git a/desktop/internal/core/remote_test.go b/desktop/internal/core/remote_test.go index 5cd78ace2..3b960ed49 100644 --- a/desktop/internal/core/remote_test.go +++ b/desktop/internal/core/remote_test.go @@ -58,7 +58,7 @@ func TestRemoteProbeAsksThroughTheHostAndReportsThePlatform(t *testing.T) { var result RemoteProbeResult var err error finishesWithin(t, "probe", testDeadline, func() { - result, err = client.RemoteProbe(WithGitAuthentication(testContext(t), prompt), SSHConnection{Host: "devbox", User: "dev"}) + result, err = client.RemoteProbe(WithGitAuthentication(testContext(t), prompt), SSHConnection{Host: "devbox", User: "dev"}, nil) }) finishesWithin(t, "answers", testDeadline, replies.Wait) if err != nil { @@ -98,7 +98,7 @@ func TestRemoteProbeWithoutAPromptCancelsEachQuestion(t *testing.T) { var result RemoteProbeResult var err error finishesWithin(t, "probe", testDeadline, func() { - result, err = NewClient().RemoteProbe(testContext(t), SSHConnection{Host: "devbox", User: "dev"}) + result, err = NewClient().RemoteProbe(testContext(t), SSHConnection{Host: "devbox", User: "dev"}, nil) }) if err != nil { t.Fatalf("probe: %v", err) diff --git a/desktop/internal/i18n/messages.go b/desktop/internal/i18n/messages.go index 25602d4e5..500f1080f 100644 --- a/desktop/internal/i18n/messages.go +++ b/desktop/internal/i18n/messages.go @@ -582,6 +582,7 @@ type SettingsMessages struct { Debuggers string Console string TrustedLocations string + RemoteWorkspace string Languages string Tools string SearchPage string diff --git a/desktop/internal/i18n/settings_messages.go b/desktop/internal/i18n/settings_messages.go index 7a4e6d86c..8c96fdc14 100644 --- a/desktop/internal/i18n/settings_messages.go +++ b/desktop/internal/i18n/settings_messages.go @@ -22,6 +22,7 @@ func settingsMessages(language Language) SettingsMessages { Debuggers: Shared(language, "desktop.buildSettings.debuggers"), Console: Shared(language, "desktop.consoleSettings.title"), TrustedLocations: Shared(language, "desktop.trustedLocations.title"), + RemoteWorkspace: Shared(language, "desktop.remoteSettings.title"), Languages: Shared(language, "settings.groups.languages"), Tools: Shared(language, "settings.groups.tools"), SearchPage: Shared(language, "desktop.search.settings.title"), diff --git a/desktop/internal/i18n/shared.generated.go b/desktop/internal/i18n/shared.generated.go index d5d790003..22747101c 100644 --- a/desktop/internal/i18n/shared.generated.go +++ b/desktop/internal/i18n/shared.generated.go @@ -1811,6 +1811,7 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.remote.ports.stop": "Stop Forwarding", "desktop.remote.ports.stopAll": "Stop All Forwards", "desktop.remote.ports.title": "Ports", + "desktop.remote.preferences.damaged": "The remote workspace settings file is damaged, so the host was not connected. Open Settings › Tools › Remote Workspace to see it.", "desktop.remote.probe.authenticationFailed": "Authentication failed: the server did not accept the keys or password offered.", "desktop.remote.probe.connected": "Connected: {system} {machine}", "desktop.remote.probe.cpu": "CPUs", @@ -1935,6 +1936,40 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.remoteAuth.refused": "SSH did not take the answer: it may be at most 8192 bytes and may not contain a line break. The question was cancelled.", "desktop.remoteAuth.secretHint": "The answer goes only to this SSH connection. Lithe does not keep it.", "desktop.remoteAuth.title": "SSH Authentication", + "desktop.remoteSettings.chooseProgram": "Choose…", + "desktop.remoteSettings.chooseProgramTitle": "Choose SSH Program", + "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.keywords": "remote ssh openssh host server reconnect reconnection connection wsl", + "desktop.remoteSettings.minutes": "{count} min", + "desktop.remoteSettings.programAutomatic": "Automatic ({path})", + "desktop.remoteSettings.programAutomaticMissing": "Automatic (no ssh found)", + "desktop.remoteSettings.programMissing": "{path} does not exist. Connecting fails until it is back or the program is set to Automatic.", + "desktop.remoteSettings.programNotExecutable": "{path} is not an executable file. Connecting fails until it is or the program is set to Automatic.", + "desktop.remoteSettings.reconnectAutomatic": "Automatic ({duration})", + "desktop.remoteSettings.reconnectLimit": "Retry for", + "desktop.remoteSettings.reconnectLimitHelp": "After a connection is lost, Lithe tries again within this time, waiting 1, 2, 4… seconds and at most 29 seconds between attempts. With Don't Reconnect the workspace stays disconnected until you reconnect it.", + "desktop.remoteSettings.reconnectNever": "Don't Reconnect", + "desktop.remoteSettings.reconnection": "Reconnection", + "desktop.remoteSettings.refusedLimit": "The reconnect time must be between 0 and 3600 seconds.", + "desktop.remoteSettings.refusedProgram": "The SSH program path cannot be used.", + "desktop.remoteSettings.refusedProgramMissing": "The chosen SSH program does not exist.", + "desktop.remoteSettings.refusedProgramNotExecutable": "The chosen SSH program is not an executable file.", + "desktop.remoteSettings.refusedProgramRelative": "The SSH program must be an absolute path.", + "desktop.remoteSettings.seconds": "{count} s", + "desktop.remoteSettings.sshConfig": "SSH configuration", + "desktop.remoteSettings.sshConfigHelp": "Host aliases, ports, keys and jump hosts come from this file. Lithe reads it and never writes it.", + "desktop.remoteSettings.sshConfigMissing": "Does not exist", + "desktop.remoteSettings.sshProgram": "SSH program", + "desktop.remoteSettings.sshProgramHelp": "The OpenSSH client started to reach a host. Automatic uses the ssh found on PATH. WSL distributions are reached without SSH and do not use it.", + "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.target": "remote workspace settings", + "desktop.remoteSettings.title": "Remote Workspace", + "desktop.remoteSettings.unavailable": "There is no preference folder to keep these settings in.", "desktop.run.closeSession": "Close", "desktop.run.durationHours": "{hours} h {minutes} min", "desktop.run.durationMilliseconds": "{milliseconds} ms", @@ -5521,6 +5556,7 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.remote.ports.stop": "停止转发", "desktop.remote.ports.stopAll": "停止全部转发", "desktop.remote.ports.title": "端口", + "desktop.remote.preferences.damaged": "远程工作区设置文件已损坏,因此没有连接主机。请在 设置 › 工具 › 远程工作区 中查看。", "desktop.remote.probe.authenticationFailed": "身份验证失败:服务器没有接受提供的密钥或密码。", "desktop.remote.probe.connected": "已连接:{system} {machine}", "desktop.remote.probe.cpu": "CPU 数", @@ -5645,6 +5681,40 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.remoteAuth.refused": "SSH 没有接受这个回答:回答最多 8192 字节,且不能包含换行。这个问题已取消。", "desktop.remoteAuth.secretHint": "回答只交给这次 SSH 连接,Lithe 不会保存。", "desktop.remoteAuth.title": "SSH 身份验证", + "desktop.remoteSettings.chooseProgram": "选择…", + "desktop.remoteSettings.chooseProgramTitle": "选择 SSH 程序", + "desktop.remoteSettings.conflict": "设置文件在此期间被改过,已重新读取。请再次应用你的修改。", + "desktop.remoteSettings.connection": "连接", + "desktop.remoteSettings.damaged": "无法读取 {path}。请修正或删除这个文件;修好之前不会用它连接主机。", + "desktop.remoteSettings.failed": "无法读取或保存远程工作区设置:{reason}", + "desktop.remoteSettings.keywords": "远程 主机 服务器 重连 断线 连接 remote ssh openssh wsl", + "desktop.remoteSettings.minutes": "{count} 分钟", + "desktop.remoteSettings.programAutomatic": "自动({path})", + "desktop.remoteSettings.programAutomaticMissing": "自动(未找到 ssh)", + "desktop.remoteSettings.programMissing": "找不到 {path}。在它恢复或改回自动之前,连接会失败。", + "desktop.remoteSettings.programNotExecutable": "{path} 不是可执行文件。在修好或改回自动之前,连接会失败。", + "desktop.remoteSettings.reconnectAutomatic": "自动({duration})", + "desktop.remoteSettings.reconnectLimit": "自动重连时长", + "desktop.remoteSettings.reconnectLimitHelp": "连接断开后,在这段时间内自动重试,间隔依次为 1、2、4…秒,最长 29 秒。选“不自动重连”时,工作区保持断开,直到你手动重连。", + "desktop.remoteSettings.reconnectNever": "不自动重连", + "desktop.remoteSettings.reconnection": "断线重连", + "desktop.remoteSettings.refusedLimit": "自动重连时长必须在 0 到 3600 秒之间。", + "desktop.remoteSettings.refusedProgram": "这个 SSH 程序路径不能使用。", + "desktop.remoteSettings.refusedProgramMissing": "找不到选择的 SSH 程序。", + "desktop.remoteSettings.refusedProgramNotExecutable": "选择的 SSH 程序不是可执行文件。", + "desktop.remoteSettings.refusedProgramRelative": "SSH 程序必须是绝对路径。", + "desktop.remoteSettings.seconds": "{count} 秒", + "desktop.remoteSettings.sshConfig": "SSH 配置文件", + "desktop.remoteSettings.sshConfigHelp": "主机别名、端口、密钥和跳板机都从这个文件读取。Lithe 只读取,不会写入。", + "desktop.remoteSettings.sshConfigMissing": "不存在", + "desktop.remoteSettings.sshProgram": "SSH 程序", + "desktop.remoteSettings.sshProgramHelp": "连接主机时启动的 OpenSSH 客户端。自动时使用 PATH 中找到的 ssh。WSL 发行版不经过 SSH,不受影响。", + "desktop.remoteSettings.storage": "保存位置", + "desktop.remoteSettings.storageHelp": "只保存你改过的值,放在本机的偏好设置目录中,不会写到主机上。", + "desktop.remoteSettings.storageNone": "修改后才创建", + "desktop.remoteSettings.target": "远程工作区设置", + "desktop.remoteSettings.title": "远程工作区", + "desktop.remoteSettings.unavailable": "没有可以保存这些设置的偏好设置目录。", "desktop.run.closeSession": "关闭", "desktop.run.durationHours": "{hours}小时{minutes}分", "desktop.run.durationMilliseconds": "{milliseconds}毫秒", diff --git a/desktop/internal/remoteconn/preferences.go b/desktop/internal/remoteconn/preferences.go new file mode 100644 index 000000000..7dede9f71 --- /dev/null +++ b/desktop/internal/remoteconn/preferences.go @@ -0,0 +1,123 @@ +package remoteconn + +import ( + "context" + "errors" + + "github.com/1lck/Lithe-IDEA/desktop/internal/configfile" + "github.com/1lck/Lithe-IDEA/desktop/internal/core" +) + +// The remote workspace preferences (settings › Tools › Remote Workspace) live in +// /remote/preferences.json, the path and the size limit Core names +// (remote.preferences), next to the saved connections in the platform user preference directory. +// They are machine-local and owned by this machine's user: created on the first change, holding +// 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. + +// PreferencesKernel is the part of the Core client the remote workspace preferences use. +type PreferencesKernel interface { + RemotePreferences(ctx context.Context, document *string, homeDirectory string) (core.RemotePreferences, error) + EditRemotePreferences(ctx context.Context, document *string, edit core.RemotePreferenceEdit) (changed bool, updated *string, err error) +} + +// Preferences is the preference document with the bytes it was read from. +type Preferences struct { + // State is Core's reading: the stored values and what each automatic one resolves to. + State core.RemotePreferences + root string + home string + file configfile.Snapshot +} + +// Path is the file the preferences are kept in, for display. +func (p Preferences) Path() string { return p.file.Path() } + +// Exists says the file was there when the preferences were read; it is created on the first change. +func (p Preferences) Exists() bool { return p.file.Exists() } + +// ReadPreferences reads the preferences kept under root, the platform preference directory. +// home, the user's home directory or empty, adds the SSH configuration file to State. Reading +// creates nothing. A document Core cannot decode fails with ErrDamaged joined to Core's error; +// the returned Preferences still names its Path. +func ReadPreferences(ctx context.Context, kernel PreferencesKernel, root, home string) (Preferences, error) { + if root == "" { + return Preferences{}, ErrUnavailable + } + plan, err := kernel.RemotePreferences(ctx, nil, "") + if err != nil { + return Preferences{}, err + } + file, err := configfile.Capture(ctx, root, plan.Storage.RelativePath, plan.Storage.MaximumBytes) + preferences := Preferences{root: root, home: home, file: file} + if errors.Is(err, configfile.ErrTooLarge) || errors.Is(err, configfile.ErrEncoding) { + return preferences, errors.Join(ErrDamaged, err) + } + if err != nil { + return Preferences{}, err + } + text, err := file.Text() + if err != nil { + return preferences, errors.Join(ErrDamaged, err) + } + state, err := kernel.RemotePreferences(ctx, text, home) + if err != nil { + var coreErr *core.Error + if errors.As(err, &coreErr) && coreErr.Code == core.CodeParseFailed { + return preferences, errors.Join(ErrDamaged, err) + } + return Preferences{}, err + } + preferences.State = state + return preferences, nil +} + +// PreferencesDocument is the text of the preferences kept under root, nil when there are none, +// for the Core requests that start OpenSSH. A damaged document fails with ErrDamaged, so no +// OpenSSH starts with a program the user did not choose. +func PreferencesDocument(ctx context.Context, kernel PreferencesKernel, root string) (*string, error) { + preferences, err := ReadPreferences(ctx, kernel, root, "") + if err != nil { + return nil, err + } + return preferences.file.Text() +} + +// Edit applies edit to the bytes p was read from, publishes the result and reads the preferences +// again. A refused value fails with Core's error (core.RemoteConnectionFieldError names the +// field); a file changed since p was read fails with ErrConflict and writes nothing. committed +// reports that the new document reached the disk even when a later step failed. +func (p Preferences) Edit(ctx context.Context, kernel PreferencesKernel, edit core.RemotePreferenceEdit) (after Preferences, committed bool, err error) { + if p.root == "" { + return p, false, ErrUnavailable + } + text, err := p.file.Text() + if err != nil { + return p, false, errors.Join(ErrDamaged, err) + } + changed, document, err := kernel.EditRemotePreferences(ctx, text, edit) + if err != nil { + var coreErr *core.Error + if errors.As(err, &coreErr) && coreErr.Code == core.CodeParseFailed { + err = errors.Join(ErrDamaged, err) + } + return p, false, err + } + if changed { + if document == nil { + return p, false, errors.New("remoteconn: Core changed the preferences without a document") + } + committed, err = p.file.Replace(ctx, []byte(*document), func() error { return p.file.Verify(ctx) }) + if errors.Is(err, configfile.ErrConflict) { + err = errors.Join(ErrConflict, err) + } + if err != nil { + return p, committed, err + } + } + after, err = ReadPreferences(ctx, kernel, p.root, p.home) + return after, committed, err +} diff --git a/desktop/internal/remoteconn/preferences_test.go b/desktop/internal/remoteconn/preferences_test.go new file mode 100644 index 000000000..7149ec686 --- /dev/null +++ b/desktop/internal/remoteconn/preferences_test.go @@ -0,0 +1,151 @@ +package remoteconn + +import ( + "errors" + "os" + "path/filepath" + "runtime" + "testing" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" +) + +func seconds(value uint32) core.RemotePreferenceEdit { + return core.RemotePreferenceEdit{ReconnectLimit: &core.RemoteReconnectLimitEdit{Seconds: &value}} +} + +// Reading absent preferences creates nothing and reports the automatic values; a change writes +// only the preference document, and restoring the automatic value keeps the file without it. +func TestPreferencesWriteOnlyTheirDocument(t *testing.T) { + ctx := testContext(t) + kernel := core.NewClient() + root := filepath.Join(t.TempDir(), "preferences") + home := t.TempDir() + read, err := ReadPreferences(ctx, kernel, root, home) + if err != nil { + t.Fatal(err) + } + if _, err := os.Stat(root); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("reading created the preference root: %v", err) + } + state := read.State + if state.Reconnect.Source != core.RemotePreferenceAutomatic || state.Reconnect.LimitSeconds != 60 || len(state.Reconnect.DelaysMilliseconds) != 6 { + t.Fatalf("reconnect = %+v", state.Reconnect) + } + if state.Preferences.SSHProgram != nil || state.Preferences.ReconnectLimitSeconds != nil || state.SSH.Source != core.RemotePreferenceAutomatic { + t.Fatalf("preferences = %+v, ssh source = %q", state.Preferences, state.SSH.Source) + } + if state.SSHConfig == nil || state.SSHConfig.Path != filepath.Join(home, ".ssh", "config") || state.SSHConfig.Exists { + t.Fatalf("ssh config = %+v", state.SSHConfig) + } + changed, committed, err := read.Edit(ctx, kernel, seconds(3)) + if err != nil || !committed { + t.Fatalf("edit: committed = %v, err = %v", committed, err) + } + if want := filepath.Join(root, "remote", "preferences.json"); changed.Path() != want { + t.Fatalf("path = %q, want %q", changed.Path(), want) + } + reconnect := changed.State.Reconnect + if reconnect.Source != core.RemotePreferenceFromSetting || reconnect.LimitSeconds != 3 || len(reconnect.DelaysMilliseconds) != 2 { + t.Fatalf("after edit reconnect = %+v", reconnect) + } + if changed.State.SSHConfig == nil { + t.Fatal("the edit dropped the home directory") + } + document, err := PreferencesDocument(ctx, kernel, root) + if err != nil || document == nil { + t.Fatalf("document = %v, err = %v", document != nil, err) + } + restored, committed, err := changed.Edit(ctx, kernel, core.RemotePreferenceEdit{ReconnectLimit: &core.RemoteReconnectLimitEdit{}}) + if err != nil || !committed || restored.State.Reconnect.Source != core.RemotePreferenceAutomatic { + t.Fatalf("restore: committed = %v, source = %q, err = %v", committed, restored.State.Reconnect.Source, err) + } + same, committed, err := restored.Edit(ctx, kernel, core.RemotePreferenceEdit{ReconnectLimit: &core.RemoteReconnectLimitEdit{}}) + if err != nil || committed || same.State.Reconnect.LimitSeconds != 60 { + t.Fatalf("unchanged edit: committed = %v, err = %v", committed, err) + } +} + +// A refused value names its field and writes nothing. +func TestRefusedPreferenceNamesTheField(t *testing.T) { + ctx := testContext(t) + kernel := core.NewClient() + root := t.TempDir() + read, err := ReadPreferences(ctx, kernel, root, "") + if err != nil { + t.Fatal(err) + } + relative := "bin/ssh" + _, committed, err := read.Edit(ctx, kernel, core.RemotePreferenceEdit{SSHProgram: &core.RemoteSSHProgramEdit{Path: &relative}}) + field, reason, ok := core.RemoteConnectionFieldError(err) + if committed || !ok || field != "sshProgram" || reason != "relative" { + t.Fatalf("relative program: committed = %v, field = %q, reason = %q", committed, field, reason) + } + _, committed, err = read.Edit(ctx, kernel, seconds(3601)) + field, reason, ok = core.RemoteConnectionFieldError(err) + if committed || !ok || field != "reconnectLimitSeconds" || reason != "outOfRange" { + t.Fatalf("limit: committed = %v, field = %q, reason = %q", committed, field, reason) + } + if _, err := os.Stat(filepath.Join(root, "remote")); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("a refused edit wrote the document: %v", 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) { + if runtime.GOOS == "windows" { + t.Skip("the executable bit is Unix-only; Windows checks the file exists") + } + ctx := testContext(t) + kernel := core.NewClient() + root := t.TempDir() + program := filepath.Join(t.TempDir(), "ssh") + if err := os.WriteFile(program, []byte("#!/bin/sh\n"), 0o755); err != nil { + t.Fatal(err) + } + read, err := ReadPreferences(ctx, kernel, root, "") + if err != nil { + t.Fatal(err) + } + saved, committed, err := read.Edit(ctx, kernel, core.RemotePreferenceEdit{SSHProgram: &core.RemoteSSHProgramEdit{Path: &program}}) + if err != nil || !committed { + t.Fatalf("save: committed = %v, err = %v", committed, err) + } + ssh := saved.State.SSH + if ssh.Source != core.RemotePreferenceFromSetting || ssh.Status != core.RemoteProgramFound || ssh.Path == nil || *ssh.Path != program { + t.Fatalf("ssh = %+v", ssh) + } + if err := os.Remove(program); err != nil { + t.Fatal(err) + } + reread, err := ReadPreferences(ctx, kernel, root, "") + if err != nil || reread.State.SSH.Status != core.RemoteProgramMissing { + t.Fatalf("status = %q, err = %v", reread.State.SSH.Status, err) + } +} + +// A document Core cannot decode is ErrDamaged: it still names its path, and PreferencesDocument +// refuses it, so nothing starts OpenSSH with it. +func TestDamagedPreferencesAreReported(t *testing.T) { + ctx := testContext(t) + kernel := core.NewClient() + root := t.TempDir() + path := filepath.Join(root, "remote", "preferences.json") + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte(`{"version":1,"unknown":true}`), 0o600); err != nil { + t.Fatal(err) + } + read, err := ReadPreferences(ctx, kernel, root, "") + if !errors.Is(err, ErrDamaged) || read.Path() != path { + t.Fatalf("read: path matches = %v, err = %v", read.Path() == path, err) + } + if _, err := PreferencesDocument(ctx, kernel, root); !errors.Is(err, ErrDamaged) { + t.Fatalf("document: err = %v", err) + } + if _, err := ReadPreferences(ctx, kernel, "", ""); !errors.Is(err, ErrUnavailable) { + t.Fatalf("no root: err = %v", err) + } +} diff --git a/desktop/internal/settingswindow/build_apply.go b/desktop/internal/settingswindow/build_apply.go index e9d097c3b..3172407cf 100644 --- a/desktop/internal/settingswindow/build_apply.go +++ b/desktop/internal/settingswindow/build_apply.go @@ -8,7 +8,8 @@ import ( // The Build pages keep their edits as drafts until the footer's Apply or OK writes them, as // in docs/design/build-execution-settings.html: the machine's toolchain defaults, then the -// project's, then the trusted locations, then each debugger's stepping policy. One request is +// project's, then the trusted locations, the remote trust records and the remote workspace +// preferences, then each debugger's stepping policy. One request is // out at a time, because the toolchain scopes and the trusted locations share one writer and // every write is read back before the next. A failed write stops the rest and keeps the window // open with its drafts; Cancel writes nothing. @@ -17,6 +18,7 @@ const ( applyToolchain = "toolchain:" applyLocations = "locations:" applyRemoteTrust = "remote-trust:" + applyRemotePrefs = "remote-preferences:" applyStepping = "stepping:" ) @@ -56,6 +58,10 @@ func (w *window) buildDrafts(language i18n.Language) (count int, targets []strin count += n targets = append(targets, i18n.Shared(language, "desktop.trustedLocations.remoteTarget")) } + if n := t.prefs.drafts(); n > 0 { + count += n + targets = append(targets, i18n.Shared(language, "desktop.remoteSettings.target")) + } } if pending := w.steppingPending(); len(pending) > 0 { count += len(pending) @@ -89,6 +95,10 @@ func (w *window) startApply(close bool) { t.remote.readFailed = nil a.steps = append(a.steps, applyRemoteTrust) } + if t.prefs.drafts() > 0 { + t.prefs.readFailed = nil + a.steps = append(a.steps, applyRemotePrefs) + } } for _, id := range w.steppingPending() { a.steps = append(a.steps, applyStepping+id) @@ -142,6 +152,14 @@ func (w *window) advanceApply(toolchainFailed error, stepping steppingResult) { if w.toolchains.remote.saving { return } + case a.running == applyRemotePrefs: + if toolchainFailed != nil { + w.stopApply(toolchainFailed) + return + } + if w.toolchains.prefs.saving { + return + } case strings.HasPrefix(a.running, applyStepping): if !stepping.done { return @@ -209,6 +227,28 @@ func (w *window) advanceApply(toolchainFailed error, stepping steppingResult) { } continue } + if step == applyRemotePrefs { + prefs := w.toolchains.prefs + if prefs.busy() { + return + } + if !prefs.loaded || prefs.stale { + // A write failed and left the preferences stale: read them again and write the + // drafts they do not hold. + if prefs.readFailed != nil { + w.stopApply(prefs.readFailed) + return + } + prefs.beginLoad() + return + } + a.steps = a.steps[1:] + if prefs.beginSave() { + a.running = step + return + } + continue + } a.steps = a.steps[1:] if w.beginSteppingApply(strings.TrimPrefix(step, applyStepping)) { a.running = step diff --git a/desktop/internal/settingswindow/model.go b/desktop/internal/settingswindow/model.go index 8e9b4f56e..2014663cb 100644 --- a/desktop/internal/settingswindow/model.go +++ b/desktop/internal/settingswindow/model.go @@ -45,12 +45,13 @@ const ( // under it: the pages plugins contribute to it make it a group, and its own page is the // directory of them. pageLanguages - // pageTools is the group "Tools"; the four pages after it belong to it. + // pageTools is the group "Tools"; the five pages after it belong to it. pageTools pageTerminal pageSearch pageConsole pageTrustedLocations + pageRemoteWorkspace // pageAI is the group "AI"; the two pages after it belong to it. pageAI pageAIGeneration @@ -86,6 +87,7 @@ var parents = [pageCount]pageID{ pageSearch: pageTools, pageConsole: pageTools, pageTrustedLocations: pageTools, + pageRemoteWorkspace: pageTools, pageAI: noPage, pageAIGeneration: pageAI, pageIDEAPI: pageAI, @@ -155,6 +157,8 @@ func titleOf(messages *i18n.SettingsMessages, id pageID) string { return messages.Console case pageTrustedLocations: return messages.TrustedLocations + case pageRemoteWorkspace: + return messages.RemoteWorkspace case pageLanguages: return messages.Languages case pageTools: @@ -351,6 +355,8 @@ func pageKeywords(language i18n.Language, id pageID) string { return i18n.Shared(language, "desktop.consoleSettings.keywords") case pageTrustedLocations: return i18n.Shared(language, "desktop.trustedLocations.keywords") + case pageRemoteWorkspace: + return i18n.Shared(language, "desktop.remoteSettings.keywords") } return "" } diff --git a/desktop/internal/settingswindow/remote_preferences_state.go b/desktop/internal/settingswindow/remote_preferences_state.go new file mode 100644 index 000000000..b24c83b76 --- /dev/null +++ b/desktop/internal/settingswindow/remote_preferences_state.go @@ -0,0 +1,268 @@ +package settingswindow + +import ( + "context" + "errors" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/1lck/Lithe-IDEA/desktop/internal/remoteconn" + "github.com/vivaui/viva/ui" +) + +// RemotePreferences is what the Remote Workspace page shows: the preference document as Core read +// it, and what every value resolves to when it is automatic, so a choice of Automatic can name the +// program and the time it stands for even while a saved value overrides it. +type RemotePreferences struct { + Saved remoteconn.Preferences + Automatic core.RemotePreferences +} + +// RemotePreferencesLoader reads the remote workspace preferences of this machine and applies the +// page's edits. Save applies each edit, in order, against the bytes the preferences were read from +// and reads them again. All calls run off the window thread, and neither needs a connection. +type RemotePreferencesLoader interface { + LoadRemotePreferences(context.Context) (RemotePreferences, error) + SaveRemotePreferences(context.Context, RemotePreferences, []core.RemotePreferenceEdit) (RemotePreferences, error) +} + +// remotePreferencesState is the Remote Workspace page: the preferences Core read from +// remote/preferences.json in the preference directory, the changes not applied yet and the +// requests that read and write them. Only the window thread touches the fields; each request is +// an Effect whose key changes when it is made, taken at the start of a paint. +// +// The file is its own, so a write is checked against the bytes it was read from and refused with +// remoteconn.ErrConflict when another window wrote in between; the page reads it again and keeps +// the drafts. +type remotePreferencesState struct { + loader RemotePreferencesLoader + + loadEffect *ui.EffectState[RemotePreferences, int] + loadKey int + loading bool + loaded bool + stale bool + readFailed error + // damagedPath is the file a failed read could not decode, shown with the failure. + damagedPath string + source RemotePreferences + + // program and limit are the drafts; set says the user changed the value, and a nil value + // drafts Automatic. + program *string + programSet bool + limit *uint32 + limitSet bool + + saveEffect *ui.EffectState[RemotePreferences, int] + saveKey int + saveSource RemotePreferences + saveEdits []core.RemotePreferenceEdit + saving bool + failed error +} + +func newRemotePreferencesState(loader ToolchainLoader) *remotePreferencesState { + r := &remotePreferencesState{} + prefs, ok := loader.(RemotePreferencesLoader) + if !ok { + return r + } + r.loader = prefs + r.loadEffect = ui.NewEffect[RemotePreferences, int](func(ctx context.Context) (RemotePreferences, error) { + return prefs.LoadRemotePreferences(ctx) + }) + r.saveEffect = ui.NewEffect[RemotePreferences, int](func(ctx context.Context) (RemotePreferences, error) { + return prefs.SaveRemotePreferences(ctx, r.saveSource, r.saveEdits) + }) + return r +} + +func (r *remotePreferencesState) available() bool { return r != nil && r.loader != nil } + +func (r *remotePreferencesState) busy() bool { return r.available() && (r.loading || r.saving) } + +// ensureLoaded reads the preferences when the page shows and there are none, or they went stale. +func (r *remotePreferencesState) ensureLoaded() { + if !r.available() || r.busy() || r.readFailed != nil { + return + } + if !r.loaded || r.stale { + r.beginLoad() + } +} + +func (r *remotePreferencesState) beginLoad() { + r.loadKey++ + r.loading, r.readFailed = true, nil +} + +// reload reads the preferences again; the drafts stay. +func (r *remotePreferencesState) reload() { + if !r.available() || r.busy() { + return + } + r.failed = nil + r.beginLoad() +} + +// shownProgram is the SSH program the page shows: the draft, or the saved one; nil is Automatic. +func (r *remotePreferencesState) shownProgram() *string { + if r.programSet { + return r.program + } + return r.source.Saved.State.Preferences.SSHProgram +} + +// shownLimit is the reconnect limit the page shows; nil is Automatic. +func (r *remotePreferencesState) shownLimit() *uint32 { + if r.limitSet { + return r.limit + } + return r.source.Saved.State.Preferences.ReconnectLimitSeconds +} + +// setProgram drafts the SSH program, nil for Automatic; choosing the saved value drops the draft. +func (r *remotePreferencesState) setProgram(path *string) { + if !r.available() || !r.loaded || r.busy() { + return + } + r.failed = nil + r.program, r.programSet = path, !sameString(path, r.source.Saved.State.Preferences.SSHProgram) +} + +// setLimit drafts the reconnect limit, nil for Automatic; choosing the saved value drops the draft. +func (r *remotePreferencesState) setLimit(seconds *uint32) { + if !r.available() || !r.loaded || r.busy() { + return + } + r.failed = nil + 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) } + +func sameUint32(a, b *uint32) bool { return (a == nil) == (b == nil) && (a == nil || *a == *b) } + +func (r *remotePreferencesState) drafts() int { + if !r.available() { + return 0 + } + n := 0 + if r.programSet { + n++ + } + if r.limitSet { + n++ + } + return n +} + +// edits are the drafts as Core edits, the program first. +func (r *remotePreferencesState) edits() []core.RemotePreferenceEdit { + var edits []core.RemotePreferenceEdit + if r.programSet { + edits = append(edits, core.RemotePreferenceEdit{SSHProgram: &core.RemoteSSHProgramEdit{Path: r.program}}) + } + if r.limitSet { + edits = append(edits, core.RemotePreferenceEdit{ReconnectLimit: &core.RemoteReconnectLimitEdit{Seconds: r.limit}}) + } + return edits +} + +// beginSave writes the drafts against the preferences they were made on. Stale preferences are +// read again first; the caller tries again once that read is taken. +func (r *remotePreferencesState) beginSave() bool { + if !r.available() || !r.loaded || r.stale || r.busy() || r.drafts() == 0 { + return false + } + r.saveSource, r.saveEdits = r.source, r.edits() + r.saveKey++ + r.saving, r.failed = true, nil + return true +} + +// keepChanged drops the drafts the preferences just read already hold. +func (r *remotePreferencesState) keepChanged() { + stored := r.source.Saved.State.Preferences + if r.programSet && sameString(r.program, stored.SSHProgram) { + r.program, r.programSet = nil, false + } + if r.limitSet && sameUint32(r.limit, stored.ReconnectLimitSeconds) { + r.limit, r.limitSet = nil, false + } +} + +// take applies the page's finished requests and reports a write that failed, so the footer's +// apply stops. +func (r *remotePreferencesState) take() (saveFailed error) { + if !r.available() { + return nil + } + if source, err, ok := r.loadEffect.Take(); ok { + r.loading = false + if err != nil { + r.readFailed, r.damagedPath = err, source.Saved.Path() + } else { + r.source, r.loaded, r.stale, r.damagedPath = source, true, false, "" + r.keepChanged() + } + } + if source, err, ok := r.saveEffect.Take(); ok { + r.saving = false + switch { + case err != nil: + // Another window may have written the file meanwhile (remoteconn.ErrConflict), Core + // refused a value, or the first edit reached the disk before the second failed: read + // the preferences again and keep the drafts they do not hold. + r.failed, r.stale, saveFailed = err, true, err + default: + r.source, r.loaded, r.stale = source, true, false + r.program, r.programSet, r.limit, r.limitSet = nil, false, nil, false + } + } + return saveFailed +} + +// remotePreferencesFailureMessage says why the preferences could not be read or written. A refused +// value names its field and reason; Core's other messages may name local paths and are shown, and +// the loader logs only their code. +func remotePreferencesFailureMessage(language i18n.Language, err error, path string) string { + if field, reason, ok := core.RemoteConnectionFieldError(err); ok { + switch { + case field == "sshProgram" && reason == "relative": + return i18n.Shared(language, "desktop.remoteSettings.refusedProgramRelative") + case field == "sshProgram" && reason == "missing": + return i18n.Shared(language, "desktop.remoteSettings.refusedProgramMissing") + case field == "sshProgram" && reason == "notExecutable": + return i18n.Shared(language, "desktop.remoteSettings.refusedProgramNotExecutable") + case field == "sshProgram": + return i18n.Shared(language, "desktop.remoteSettings.refusedProgram") + case field == "reconnectLimitSeconds": + return i18n.Shared(language, "desktop.remoteSettings.refusedLimit") + } + } + switch { + case errors.Is(err, remoteconn.ErrConflict): + return i18n.Shared(language, "desktop.remoteSettings.conflict") + case errors.Is(err, remoteconn.ErrDamaged): + return i18n.SharedFormat(language, "desktop.remoteSettings.damaged", map[string]string{"path": path}) + case errors.Is(err, remoteconn.ErrUnavailable): + return i18n.Shared(language, "desktop.remoteSettings.unavailable") + } + return i18n.SharedFormat(language, "desktop.remoteSettings.failed", map[string]string{"reason": err.Error()}) +} + +// declare keeps the requests that are out alive in every paint, so leaving the page does not +// cancel a write. +func (r *remotePreferencesState) declare(c ui.C) { + if !r.available() { + return + } + if r.loadKey != 0 { + ui.Effect(c.Part("remote-preferences-load"), r.loadEffect, r.loadKey) + } + if r.saveKey != 0 { + ui.Effect(c.Part("remote-preferences-save"), r.saveEffect, r.saveKey) + } +} diff --git a/desktop/internal/settingswindow/remote_workspace_view.go b/desktop/internal/settingswindow/remote_workspace_view.go new file mode 100644 index 000000000..c804066e3 --- /dev/null +++ b/desktop/internal/settingswindow/remote_workspace_view.go @@ -0,0 +1,236 @@ +package settingswindow + +import ( + "errors" + "slices" + "strconv" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/1lck/Lithe-IDEA/desktop/internal/icons" + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +// reconnectAutomatic is the reconnect choice that removes the saved limit; the others are seconds. +const reconnectAutomatic = -1 + +// reconnectChoices are the reconnect limits offered besides a saved one, in seconds; Core accepts +// 0 to 3600. +var reconnectChoices = []int{reconnectAutomatic, 0, 15, 30, 60, 120, 300, 600, 1800, 3600} + +// remoteWorkspacePage shows the remote workspace preferences as Core read them from the preference +// directory and what each automatic value resolves to. Opening it only reads; a change is a draft +// the footer's Apply writes. +func (w *window) remoteWorkspacePage(c ui.C) { + r := w.toolchains.prefs + language := w.marketLanguage() + r.ensureLoaded() + w.pageScroll(c, pageRemoteWorkspace, func() { + if !r.loaded { + if r.readFailed == nil { + ui.Row(c.Part("loading")).FillWidth().Height(28).Items(ui.Center).Children(func() { + ui.Text(c, i18n.Shared(language, "desktop.toolchains.loading")).FontSize(12).Color(w.pal.muted) + }) + } + w.remotePreferencesNotices(c.Part("notices"), language, r) + return + } + w.card(c.Part("connection"), i18n.Shared(language, "desktop.remoteSettings.connection"), "", func() { + w.remoteProgramRow(c.Part("program"), language, r) + w.remoteSSHConfigRow(c.Part("ssh-config"), language, r) + }) + w.card(c.Part("reconnection"), i18n.Shared(language, "desktop.remoteSettings.reconnection"), "", func() { + w.remoteReconnectRow(c.Part("reconnect"), language, r) + }) + w.card(c.Part("storage"), i18n.Shared(language, "desktop.remoteSettings.storage"), "", func() { + title := i18n.Shared(language, "desktop.remoteSettings.storage") + note := "" + if !r.source.Saved.Exists() { + note = i18n.Shared(language, "desktop.remoteSettings.storageNone") + } + w.settingsRow(c.Part("storage-row"), title, i18n.Shared(language, "desktop.remoteSettings.storageHelp"), func() { + w.remotePathText(c.Part("storage-path"), r.source.Saved.Path(), note) + }) + }) + w.remotePreferencesNotices(c.Part("notices"), language, r) + }) +} + +// remoteProgramRow chooses the OpenSSH client: Automatic, naming the ssh found on PATH, or a file +// the user picked. A saved program that went missing or lost its executable bit is reported under +// the row. +func (w *window) remoteProgramRow(c ui.C, language i18n.Language, r *remotePreferencesState) { + title := i18n.Shared(language, "desktop.remoteSettings.sshProgram") + shown := r.shownProgram() + saved := r.source.Saved.State.Preferences.SSHProgram + choices := []string{""} + for _, path := range []*string{saved, shown} { + if path != nil && *path != "" && !slices.Contains(choices, *path) { + choices = append(choices, *path) + } + } + value := "" + if shown != nil { + value = *shown + } + label := func(path string) string { + if path != "" { + return path + } + automatic := r.source.Automatic.SSH + if automatic.Status != core.RemoteProgramFound || automatic.Path == nil { + return i18n.Shared(language, "desktop.remoteSettings.programAutomaticMissing") + } + return i18n.SharedFormat(language, "desktop.remoteSettings.programAutomatic", map[string]string{"path": *automatic.Path}) + } + busy := r.busy() + w.settingsRow(c, title, i18n.Shared(language, "desktop.remoteSettings.sshProgramHelp"), func() { + ui.Row(c).Grow(1).Shrink(1).MinWidth(0).Gap(8).Items(ui.Center).Children(func() { + if ui.Select(c.Part("program"), &value, choices, label).Grow(1).Shrink(1).MinWidth(0).Label(title).Disabled(busy).Changed() { + if value == "" { + r.setProgram(nil) + } else { + path := value + r.setProgram(&path) + } + } + if w.button(c.Part("choose"), buttonSmall, i18n.Shared(language, "desktop.remoteSettings.chooseProgram"), busy) { + w.pickRemoteProgram(language, r) + } + }) + }) + ssh := r.source.Saved.State.SSH + if r.programSet || ssh.Source != core.RemotePreferenceFromSetting || ssh.Path == nil { + return + } + switch ssh.Status { + case core.RemoteProgramMissing: + ui.Wrap(c.Part("program-missing"), i18n.SharedFormat(language, "desktop.remoteSettings.programMissing", map[string]string{"path": *ssh.Path})).FontSize(12).Color(w.pal.danger) + case core.RemoteProgramNotExecutable: + ui.Wrap(c.Part("program-not-executable"), i18n.SharedFormat(language, "desktop.remoteSettings.programNotExecutable", map[string]string{"path": *ssh.Path})).FontSize(12).Color(w.pal.danger) + } +} + +// remoteSSHConfigRow names the user's OpenSSH configuration file; Lithe only reads it. +func (w *window) remoteSSHConfigRow(c ui.C, language i18n.Language, r *remotePreferencesState) { + config := r.source.Saved.State.SSHConfig + if config == nil { + return + } + note := "" + if !config.Exists { + note = i18n.Shared(language, "desktop.remoteSettings.sshConfigMissing") + } + w.settingsRow(c, i18n.Shared(language, "desktop.remoteSettings.sshConfig"), i18n.Shared(language, "desktop.remoteSettings.sshConfigHelp"), func() { + w.remotePathText(c.Part("path"), config.Path, note) + }) +} + +// remoteReconnectRow chooses how long a lost connection is retried: Automatic, naming Core's +// default, never, or a time; a saved time that is not among the choices is listed too. +func (w *window) remoteReconnectRow(c ui.C, language i18n.Language, r *remotePreferencesState) { + title := i18n.Shared(language, "desktop.remoteSettings.reconnectLimit") + value := reconnectAutomatic + if shown := r.shownLimit(); shown != nil { + value = int(*shown) + } + choices := reconnectChoices + for _, limit := range []*uint32{r.source.Saved.State.Preferences.ReconnectLimitSeconds, r.shownLimit()} { + if limit != nil && !slices.Contains(choices, int(*limit)) { + choices = append(append([]int{}, choices...), int(*limit)) + } + } + label := func(seconds int) string { + switch seconds { + case reconnectAutomatic: + return i18n.SharedFormat(language, "desktop.remoteSettings.reconnectAutomatic", map[string]string{ + "duration": remoteDuration(language, int(r.source.Automatic.Reconnect.LimitSeconds)), + }) + case 0: + return i18n.Shared(language, "desktop.remoteSettings.reconnectNever") + } + return remoteDuration(language, seconds) + } + w.settingsRow(c, title, i18n.Shared(language, "desktop.remoteSettings.reconnectLimitHelp"), func() { + if ui.Select(c.Part("limit"), &value, choices, label).FillWidth().Label(title).Disabled(r.busy()).Changed() { + if value == reconnectAutomatic { + r.setLimit(nil) + } else { + seconds := uint32(value) + r.setLimit(&seconds) + } + } + }) +} + +// remoteDuration is a reconnect 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)}) + } + return i18n.SharedFormat(language, "desktop.remoteSettings.seconds", map[string]string{"count": strconv.Itoa(seconds)}) +} + +// remotePathText is a local path the row's width may cut, with the whole path as its tooltip, and +// a note such as "does not exist" after it that the width never cuts. +func (w *window) remotePathText(c ui.C, path, note string) { + ui.Row(c).Grow(1).Shrink(1).MinWidth(0).Gap(8).Items(ui.Center). + HitWith(ui.ID(c), path, gfx.HitOptions{Role: gfx.RoleGroup}).Tooltip(path).Children(func() { + ui.Text(c, path).FontSize(12).Mono().Color(w.pal.text).Shrink(1).MinWidth(0).Ellipsis() + if note != "" { + ui.Text(c.Part("note"), note).FontSize(12).Color(w.pal.muted).Shrink(0) + } + }) +} + +// remotePreferencesNotices are the read's and the write's failures, and the write that is out. +func (w *window) remotePreferencesNotices(c ui.C, language i18n.Language, r *remotePreferencesState) { + if r.readFailed == nil && r.failed == nil && !r.saving { + return + } + ui.Column(c).FillWidth().Shrink(0).Gap(8).Children(func() { + if r.readFailed != nil { + message := remotePreferencesFailureMessage(language, r.readFailed, r.damagedPath) + w.box(c.Part("load-failed"), boxErr, func(words gfx.Color) { + boxIcon(c, icons.CircleX, words) + boxText(c, message, words) + if w.button(c.Part("load-retry"), buttonSmall, i18n.Shared(language, "desktop.toolchains.reload"), r.busy()) { + r.reload() + } + }) + } + if r.failed != nil { + message := remotePreferencesFailureMessage(language, r.failed, r.source.Saved.Path()) + w.box(c.Part("failed"), boxErr, func(words gfx.Color) { + boxIcon(c, icons.CircleX, words) + boxText(c, message, words) + }) + } + if r.saving { + w.box(c.Part("busy"), boxInfo, func(words gfx.Color) { + boxIcon(c, icons.Clock, words) + boxText(c, i18n.Shared(language, "desktop.toolchains.saving"), words) + }) + } + }) +} + +// pickRemoteProgram asks for the SSH program and drafts it; Core checks it when Apply writes it. +func (w *window) pickRemoteProgram(language i18n.Language, r *remotePreferencesState) { + paths, err := app.OpenFiles(app.OpenFileOptions{Title: i18n.Shared(language, "desktop.remoteSettings.chooseProgramTitle")}) + // log-exempt: 用户取消:关闭文件选择器不修改 SSH 程序草稿。 + if errors.Is(err, app.ErrCanceled) || (err == nil && len(paths) == 0) { + return + } + if err != nil { + r.failed = err + if w.ctrl.opts.MarketplaceError != nil { + w.ctrl.opts.MarketplaceError(err) + } + return + } + path := paths[0] + r.setProgram(&path) +} diff --git a/desktop/internal/settingswindow/remote_workspace_view_test.go b/desktop/internal/settingswindow/remote_workspace_view_test.go new file mode 100644 index 000000000..b0d4d55ac --- /dev/null +++ b/desktop/internal/settingswindow/remote_workspace_view_test.go @@ -0,0 +1,182 @@ +package settingswindow + +import ( + "context" + "os" + "path/filepath" + "strings" + "sync/atomic" + "testing" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/1lck/Lithe-IDEA/desktop/internal/remoteconn" +) + +// corePreferencesLoader keeps the remote workspace preferences in a test directory through the +// real Core client, the way the workbench's adapter does. +type corePreferencesLoader struct { + fakeToolchainLoader + kernel *core.Client + root, home string + saves atomic.Int32 +} + +func newCorePreferencesLoader(t *testing.T) *corePreferencesLoader { + t.Helper() + return &corePreferencesLoader{kernel: core.NewClient(), root: filepath.Join(t.TempDir(), "preferences"), home: t.TempDir()} +} + +func (l *corePreferencesLoader) LoadRemotePreferences(ctx context.Context) (RemotePreferences, error) { + return l.read(ctx) +} + +func (l *corePreferencesLoader) SaveRemotePreferences(ctx context.Context, prefs RemotePreferences, edits []core.RemotePreferenceEdit) (RemotePreferences, error) { + l.saves.Add(1) + saved := prefs.Saved + for _, edit := range edits { + var err error + if saved, _, err = saved.Edit(ctx, l.kernel, edit); err != nil { + return prefs, err + } + } + return l.read(ctx) +} + +func (l *corePreferencesLoader) read(ctx context.Context) (RemotePreferences, error) { + automatic, err := l.kernel.RemotePreferences(ctx, nil, "") + if err != nil { + return RemotePreferences{}, err + } + saved, err := remoteconn.ReadPreferences(ctx, l.kernel, l.root, l.home) + return RemotePreferences{Saved: saved, Automatic: automatic}, err +} + +func (l *corePreferencesLoader) file() string { + return filepath.Join(l.root, "remote", "preferences.json") +} + +// remoteWorkspaceWindow opens a settings window on the Remote Workspace page and waits for the +// preferences to be read. +func remoteWorkspaceWindow(t *testing.T, loader *corePreferencesLoader) (*window, *windowDriver, *remotePreferencesState) { + t.Helper() + w := newWindow(NewController(Options{Toolchains: loader}), Values{}) + w.sess.show(pageRemoteWorkspace) + d := openWindow(t, w) + r := w.toolchains.prefs + d.until("the remote workspace preferences to load", func() bool { return (r.loaded || r.readFailed != nil) && !r.busy() }) + d.pump() + return w, d, r +} + +// Opening the page reads and creates nothing; it shows the automatic reconnect time Core resolves +// and the SSH configuration file it found missing. +func TestRemoteWorkspacePageOnlyReads(t *testing.T) { + loader := newCorePreferencesLoader(t) + _, d, r := remoteWorkspaceWindow(t, loader) + if r.readFailed != nil { + t.Fatalf("read failed: %v", r.readFailed) + } + automatic := i18n.SharedFormat(i18n.English, "desktop.remoteSettings.reconnectAutomatic", map[string]string{ + "duration": remoteDuration(i18n.English, 60), + }) + if !d.text(automatic) { + t.Fatal("the reconnect row does not show the automatic time Core resolves") + } + if !d.has(filepath.Join(loader.home, ".ssh", "config")) || !d.text(en("desktop.remoteSettings.sshConfigMissing")) { + t.Fatal("the SSH configuration row does not say the file is missing") + } + if _, err := os.Stat(loader.root); !os.IsNotExist(err) { + t.Fatalf("opening the page created the preference directory: %v", err) + } + if r.drafts() != 0 || loader.saves.Load() != 0 { + t.Fatalf("drafts = %d, saves = %d: opening the page changed something", r.drafts(), loader.saves.Load()) + } +} + +// A changed reconnect time is a draft the footer's Apply writes; choosing Automatic again writes +// the file without it. +func TestRemoteWorkspaceReconnectLimitIsAppliedAndRestored(t *testing.T) { + loader := newCorePreferencesLoader(t) + w, d, r := remoteWorkspaceWindow(t, loader) + seconds := uint32(120) + r.setLimit(&seconds) + d.w.inv.Invalidate() + d.pump() + if r.drafts() != 1 { + t.Fatalf("drafts = %d, want the reconnect time", r.drafts()) + } + if _, err := os.Stat(loader.file()); !os.IsNotExist(err) { + t.Fatalf("a draft wrote the file before Apply: %v", err) + } + d.click(en("desktop.buildSettings.apply")) + d.until("the apply to end", func() bool { return !w.apply.active() && !r.busy() }) + d.pump() + if r.failed != nil || r.drafts() != 0 { + t.Fatalf("failed = %v, drafts = %d", r.failed, r.drafts()) + } + reconnect := r.source.Saved.State.Reconnect + if reconnect.Source != core.RemotePreferenceFromSetting || reconnect.LimitSeconds != 120 { + t.Fatalf("reconnect = %+v, want 120 seconds from the setting", reconnect) + } + text, err := os.ReadFile(loader.file()) + if err != nil || !strings.Contains(string(text), "120") { + t.Fatalf("the file does not hold the time: err = %v", err) + } + if !d.text(remoteDuration(i18n.English, 120)) { + t.Fatal("the row does not show the saved time") + } + + r.setLimit(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 got := r.source.Saved.State.Reconnect.Source; got != core.RemotePreferenceAutomatic || r.source.Saved.State.Preferences.ReconnectLimitSeconds != nil { + t.Fatalf("source = %q: Automatic was not restored", got) + } +} + +// Core's refusal of a relative program names the field under the page and keeps the draft, and +// nothing is written. +func TestRemoteWorkspaceRefusedProgramKeepsTheDraft(t *testing.T) { + loader := newCorePreferencesLoader(t) + w, d, r := remoteWorkspaceWindow(t, loader) + relative := "bin/ssh" + r.setProgram(&relative) + d.w.inv.Invalidate() + d.pump() + d.click(en("desktop.buildSettings.apply")) + d.until("the apply to stop", func() bool { return !w.apply.active() && !r.saving }) + d.until("the preferences to be read again", func() bool { return !r.busy() }) + d.pump() + if r.failed == nil || r.drafts() != 1 { + t.Fatalf("failed = %v, drafts = %d: the refusal did not keep the draft", r.failed, r.drafts()) + } + if !d.wrapped(en("desktop.remoteSettings.refusedProgramRelative")) { + t.Fatal("the page does not say the program must be an absolute path") + } + if _, err := os.Stat(loader.file()); !os.IsNotExist(err) { + t.Fatalf("a refused edit wrote the file: %v", err) + } +} + +// A file Core cannot decode is reported with its path and nothing is offered to edit. +func TestRemoteWorkspaceDamagedFileIsReported(t *testing.T) { + loader := newCorePreferencesLoader(t) + if err := os.MkdirAll(filepath.Dir(loader.file()), 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(loader.file(), []byte(`{"version":1,"unknown":true}`), 0o600); err != nil { + t.Fatal(err) + } + _, d, r := remoteWorkspaceWindow(t, loader) + message := i18n.SharedFormat(i18n.English, "desktop.remoteSettings.damaged", map[string]string{"path": loader.file()}) + if r.loaded || r.readFailed == nil || !d.wrapped(message) { + t.Fatalf("loaded = %v, read failed = %v: the damaged file is not reported with its path", r.loaded, r.readFailed != nil) + } + if d.has(en("desktop.remoteSettings.sshProgram")) { + t.Fatal("the page offers to edit a file it could not read") + } +} diff --git a/desktop/internal/settingswindow/remote_workspace_visual_test.go b/desktop/internal/settingswindow/remote_workspace_visual_test.go new file mode 100644 index 000000000..b8b0369be --- /dev/null +++ b/desktop/internal/settingswindow/remote_workspace_visual_test.go @@ -0,0 +1,65 @@ +//go:build vivahead && lithevisual + +package settingswindow + +import ( + "os" + "path/filepath" + "testing" + + "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. +// 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") + if out == "" { + t.Skip("set LITHE_VISUAL_OUTPUT_DIR to capture the remote workspace page") + } + if err := os.MkdirAll(out, 0o755); err != nil { + t.Fatal(err) + } + for _, language := range []i18n.Language{i18n.English, i18n.Chinese} { + for _, theme := range []string{"dark", "light"} { + t.Run(language.Code()+"/"+theme, func(t *testing.T) { + loader := newCorePreferencesLoader(t) + // Opening the page and drafting create nothing, so the fictional folders are never written. + loader.home = "/Users/example" + loader.root = "/Users/example/Library/Application Support/Lithe Desktop" + w := newWindow(NewController(Options{ + Text: func() *i18n.Messages { return i18n.For(language) }, Language: func() i18n.Language { return language }, + SystemLanguage: language, SystemDark: func() bool { return theme == "dark" }, + Toolchains: loader, + }), Values{Theme: theme, Language: language.Code()}) + w.sess.show(pageRemoteWorkspace) + session, err := headless.Open(w.config(), nil, headless.Options{}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(session.Close) + d := &windowDriver{t: t, w: w, driver: session.Driver()} + r := w.toolchains.prefs + d.until("the preferences to load", func() bool { return r.loaded && !r.busy() }) + d.pump() + shot := func(state string) { + t.Helper() + if err := session.Screenshot(filepath.Join(out, "remote-workspace-"+state+"-"+theme+"-"+language.Code()+".png")); err != nil { + t.Fatal(err) + } + } + title := i18n.Shared(language, "desktop.remoteSettings.sshProgram") + d.until("the page to be painted", func() bool { return d.text(title) }) + shot("automatic") + program := "/opt/homebrew/bin/ssh" + seconds := uint32(300) + r.setProgram(&program) + r.setLimit(&seconds) + d.until("the drafts to be painted", func() bool { return d.text(program) }) + shot("drafts") + }) + } + } +} diff --git a/desktop/internal/settingswindow/settingswindow_test.go b/desktop/internal/settingswindow/settingswindow_test.go index 3e1b03393..75c5860ed 100644 --- a/desktop/internal/settingswindow/settingswindow_test.go +++ b/desktop/internal/settingswindow/settingswindow_test.go @@ -60,8 +60,8 @@ func TestOnlyAppearanceVersionControlBuildToolsAndAIAreGroups(t *testing.T) { } } -func TestToolsGroupHoldsTerminalSearchConsoleAndTrustedLocations(t *testing.T) { - want := []pageID{pageTerminal, pageSearch, pageConsole, pageTrustedLocations} +func TestToolsGroupHoldsTerminalSearchConsoleTrustedLocationsAndRemoteWorkspace(t *testing.T) { + want := []pageID{pageTerminal, pageSearch, pageConsole, pageTrustedLocations, pageRemoteWorkspace} var got []pageID for id := pageID(0); id < pageCount; id++ { if parents[id] == pageTools { @@ -69,7 +69,7 @@ func TestToolsGroupHoldsTerminalSearchConsoleAndTrustedLocations(t *testing.T) { } } if !slices.Equal(got, want) { - t.Fatalf("pages in Tools = %v, want Terminal, Search, Console and Trusted Locations %v", got, want) + t.Fatalf("pages in Tools = %v, want Terminal, Search, Console, Trusted Locations and Remote Workspace %v", got, want) } if pageTerminal != pageTools+1 { t.Fatal("the Terminal page does not directly follow its group, which appendVisible relies on") @@ -166,8 +166,8 @@ func TestExpandedToolsGroupListsTerminal(t *testing.T) { open := initialOpen() open[pageTools] = true rows := appendVisible(nil, english(), &open, "") - if len(rows) != 18 { - t.Fatalf("rows = %v, want the 14 of the default sidebar and the four pages of Tools", rows) + if len(rows) != 19 { + t.Fatalf("rows = %v, want the 14 of the default sidebar and the five pages of Tools", rows) } for i, r := range rows { if r.page != pageTools { @@ -206,7 +206,7 @@ func TestSearchFindsTerminalInsideItsGroup(t *testing.T) { func TestSearchOnTheToolsGroupKeepsTerminal(t *testing.T) { open := initialOpen() rows := appendVisible(nil, english(), &open, foldQuery("tools")) - want := []pageID{pageTools, pageTerminal, pageSearch, pageConsole, pageTrustedLocations} + want := []pageID{pageTools, pageTerminal, pageSearch, pageConsole, pageTrustedLocations, pageRemoteWorkspace} if got := pagesOf(rows); !slices.Equal(got, want) { t.Fatalf("pages = %v, want %v", got, want) } diff --git a/desktop/internal/settingswindow/toolchains_state.go b/desktop/internal/settingswindow/toolchains_state.go index 74e0668a4..340190063 100644 --- a/desktop/internal/settingswindow/toolchains_state.go +++ b/desktop/internal/settingswindow/toolchains_state.go @@ -393,6 +393,8 @@ type toolchainState struct { // remote is the Remote Workspaces card of the same page. Its document is a file of its own, // so busy() does not include its requests. remote *remoteTrustState + // prefs is the Remote Workspace page; its document is a file of its own too. + prefs *remotePreferencesState // The list's query and the page's selection. query string @@ -413,6 +415,7 @@ func newToolchainState(loader ToolchainLoader) *toolchainState { t.view, t.search = newToolchainProjection(viewer), newToolchainProjection(viewer) t.locations = newTrustedLocationsState(t, loader) t.remote = newRemoteTrustState(loader) + t.prefs = newRemotePreferencesState(loader) if loader == nil { return t } @@ -687,6 +690,9 @@ func (t *toolchainState) take() (saveFailed error) { if err := t.remote.take(); err != nil && saveFailed == nil { saveFailed = err } + if err := t.prefs.take(); err != nil && saveFailed == nil { + saveFailed = err + } t.view.take() t.search.take() return saveFailed @@ -751,6 +757,7 @@ func (t *toolchainState) declare(c ui.C) { } t.locations.declare(c) t.remote.declare(c) + t.prefs.declare(c) t.view.declare(c.Part("toolchain-view")) t.search.declare(c.Part("toolchain-search")) } diff --git a/desktop/internal/settingswindow/window_view.go b/desktop/internal/settingswindow/window_view.go index f6d602219..b11fdb177 100644 --- a/desktop/internal/settingswindow/window_view.go +++ b/desktop/internal/settingswindow/window_view.go @@ -308,8 +308,8 @@ func (w *window) navContent(c ui.C, i int) { } // navTrailing ends a row as the prototype does: Build folded and the Toolchains page count the -// tools with a problem, the Debuggers and Trusted Locations pages mark drafts and a kind counts -// its pages. +// tools with a problem, the Debuggers, Trusted Locations and Remote Workspace pages mark drafts and +// a kind counts its pages. func (w *window) navTrailing(c ui.C, r row) { if r.dynamic != "" { return @@ -329,6 +329,10 @@ func (w *window) navTrailing(c ui.C, r row) { if w.toolchains.locations.drafts() > 0 || w.toolchains.remote.drafts() > 0 { dot(c, 7, w.bp.accent) } + case r.page == pageRemoteWorkspace: + if w.toolchains.prefs.drafts() > 0 { + dot(c, 7, w.bp.accent) + } } } @@ -383,6 +387,8 @@ func (w *window) content(c ui.C) { w.consolePage(c) case w.sess.page == pageTrustedLocations && (w.toolchains.locations.available() || w.toolchains.remote.available()): w.trustedLocationsPage(c) + case w.sess.page == pageRemoteWorkspace && w.toolchains.prefs.available(): + w.remoteWorkspacePage(c) case w.sess.page == pageTerminal && w.ctrl.opts.TerminalShells != nil: w.terminalPage(c) case w.sess.page == pageSearch: diff --git a/desktop/internal/workbench/app.go b/desktop/internal/workbench/app.go index 667165c66..232292ddc 100644 --- a/desktop/internal/workbench/app.go +++ b/desktop/internal/workbench/app.go @@ -211,7 +211,7 @@ type Kernel interface { GitAuthRespond(ctx context.Context, requestID string, answer *string) (bool, error) RemoteConnections(ctx context.Context, document *string) (core.RemoteConnectionsState, error) EditRemoteConnections(ctx context.Context, document *string, edit core.RemoteConnectionEdit) (core.RemoteConnectionsPublication, error) - RemoteProbe(ctx context.Context, connection core.SSHConnection) (core.RemoteProbeResult, error) + RemoteProbe(ctx context.Context, connection core.SSHConnection, preferences *string) (core.RemoteProbeResult, error) 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) @@ -225,9 +225,11 @@ type Kernel interface { RemoteServerState(ctx context.Context, sessionID string) error SearchRemoteConnections(ctx context.Context, document *string, query string) (core.RemoteConnectionsState, error) RemoteParseAddress(ctx context.Context, text string) (core.RemoteAddress, error) - RemoteEffectiveSettings(ctx context.Context, connection core.SSHConnection) (core.RemoteEffectiveSettings, error) - RemoteSSHConfigHosts(ctx context.Context, homeDirectory string, document *string) (core.RemoteSSHConfigHosts, error) + RemoteEffectiveSettings(ctx context.Context, connection core.SSHConnection, preferences *string) (core.RemoteEffectiveSettings, error) + RemoteSSHConfigHosts(ctx context.Context, homeDirectory string, document, preferences *string) (core.RemoteSSHConfigHosts, error) RemoteMottyHosts(ctx context.Context, configDirectory string, document *string) (core.RemoteMottyHosts, error) + RemotePreferences(ctx context.Context, document *string, homeDirectory string) (core.RemotePreferences, error) + EditRemotePreferences(ctx context.Context, document *string, edit core.RemotePreferenceEdit) (bool, *string, error) RemoteWorkspaceTrust(ctx context.Context, document *string, sessionID, workspace string) (core.RemoteWorkspaceTrustState, error) EditRemoteWorkspaceTrust(ctx context.Context, document *string, decision core.RemoteWorkspaceTrustDecision) (core.RemoteWorkspaceTrustPublication, error) RevokeRemoteWorkspaceTrust(ctx context.Context, document *string, revoke core.RemoteWorkspaceTrustRevoke) (core.RemoteWorkspaceTrustPublication, error) diff --git a/desktop/internal/workbench/remote.go b/desktop/internal/workbench/remote.go index 8b5306a88..54596ac1c 100644 --- a/desktop/internal/workbench/remote.go +++ b/desktop/internal/workbench/remote.go @@ -714,10 +714,14 @@ func (a *App) testRemote() { ctx, cancel := context.WithTimeout(a.operationContext(context.Background()), remoteProbeTimeout) probe := &remoteProbe{cancel: cancel} r.probe = probe - generation, kernel := r.generation, a.kernel + generation, kernel, root := r.generation, a.kernel, a.globalToolchainRoot() a.background(nil, 0, func(context.Context) func(*App) { defer cancel() - result, err := kernel.RemoteProbe(a.gitAuthentication(ctx), connection) + var result core.RemoteProbeResult + preferences, err := remotePreferencesDocument(ctx, kernel, root) + if err == nil { + result, err = kernel.RemoteProbe(a.gitAuthentication(ctx), connection, preferences) + } return func(a *App) { r := &a.remote if !r.open || r.generation != generation || r.probe != probe { diff --git a/desktop/internal/workbench/remote_browse.go b/desktop/internal/workbench/remote_browse.go index e59688a16..567d37eff 100644 --- a/desktop/internal/workbench/remote_browse.go +++ b/desktop/internal/workbench/remote_browse.go @@ -108,10 +108,10 @@ func (a *App) connectRemote(folder string) { } }) }) - generation, kernel := r.generation, a.kernel + generation, kernel, root := r.generation, a.kernel, a.globalToolchainRoot() a.background(nil, 0, func(context.Context) func(*App) { defer cancel() - result, err := a.connectRemoteHost(a.gitAuthentication(ctx), kernel, host) + result, err := a.connectRemoteHost(a.gitAuthentication(ctx), kernel, root, host) return func(a *App) { r := &a.remote if !r.open || r.generation != generation || r.connect != attempt { @@ -170,6 +170,8 @@ func remoteConnectFailureText(language i18n.Language, err error) string { switch { case errors.Is(err, remoteserver.ErrNotBundled): return i18n.Shared(language, "desktop.remote.connect.notBundled") + case errors.Is(err, remoteconn.ErrDamaged): + return i18n.Shared(language, "desktop.remote.preferences.damaged") case errors.Is(err, remoteserver.ErrMismatch), errors.As(err, &coreErr) && coreErr.Code == core.CodeRemoteServerInvalid: return i18n.Shared(language, "desktop.remote.connect.serverInvalid") diff --git a/desktop/internal/workbench/remote_documents_test.go b/desktop/internal/workbench/remote_documents_test.go index 62b345545..bcb771670 100644 --- a/desktop/internal/workbench/remote_documents_test.go +++ b/desktop/internal/workbench/remote_documents_test.go @@ -192,7 +192,7 @@ func TestRemoteWorkspaceEditsTheHostsFiles(t *testing.T) { // connection connects again on its own and then compares the documents with the host, so a change // made on the host meanwhile shows as a conflict. The log keeps only the command and the code. func TestRemoteDocumentFailuresSayWhy(t *testing.T) { - h, k, _, logger := remoteWorkspaceHarness(t) + h, k, timers, logger := remoteWorkspaceHarness(t) lang := h.app.language() k.put(remoteTestReadme, "# Project\n") k.set(func(k *remoteHostKernel) { @@ -236,6 +236,7 @@ func TestRemoteDocumentFailuresSayWhy(t *testing.T) { k.fileErr = &core.Error{Command: "remote.stat", Code: core.CodeConnectionClosed, Message: "closed"} }) h.app.saveDocument(p, d.id) + h.fireReconnect(t, timers, r) h.await("the new session and the check after it", func() bool { return r.session == "session-2" && !r.beating && !d.saving && !d.checking && !d.checkPending }) diff --git a/desktop/internal/workbench/remote_git_test.go b/desktop/internal/workbench/remote_git_test.go index 0d0899256..0dbaf9b71 100644 --- a/desktop/internal/workbench/remote_git_test.go +++ b/desktop/internal/workbench/remote_git_test.go @@ -360,6 +360,7 @@ func TestRemoteWorkspaceTrustStartsGitOnTheHost(t *testing.T) { }) h.fire(t, timers) host.awaitEnd(t) + h.fireReconnect(t, timers, r) h.await("the second session", func() bool { return r.session == "session-2" && !r.beating }) if w := h.awaitRemoteGit(p); w.session != "session-2" || k.watchAt(t, remoteTestFolder+"/.git").session != "session-2" { t.Fatal("the new session does not watch the git directory") diff --git a/desktop/internal/workbench/remote_import.go b/desktop/internal/workbench/remote_import.go index db53eea2c..d2f6ed936 100644 --- a/desktop/internal/workbench/remote_import.go +++ b/desktop/internal/workbench/remote_import.go @@ -72,7 +72,7 @@ func (a *App) openRemoteImport(source remoteImportSource) { m.err = i18n.SharedFormat(a.language(), "desktop.remote.import.failed", map[string]string{"reason": documentLogError(err).Error()}) return } - generation, kernel := r.generation, a.kernel + generation, kernel, root := r.generation, a.kernel, a.globalToolchainRoot() a.background(nil, remoteReadTimeout, func(ctx context.Context) func(*App) { var motty core.RemoteMottyHosts var ssh core.RemoteSSHConfigHosts @@ -82,10 +82,12 @@ func (a *App) openRemoteImport(source remoteImportSource) { } else { mottyErr = err } - if home, err := os.UserHomeDir(); err == nil { - ssh, sshErr = kernel.RemoteSSHConfigHosts(ctx, home, document) - } else { + if home, err := os.UserHomeDir(); err != nil { + sshErr = err + } else if preferences, err := remotePreferencesDocument(ctx, kernel, root); err != nil { sshErr = err + } else { + ssh, sshErr = kernel.RemoteSSHConfigHosts(ctx, home, document, preferences) } return func(a *App) { r := &a.remote diff --git a/desktop/internal/workbench/remote_list.go b/desktop/internal/workbench/remote_list.go index 424efe63b..fac423e2e 100644 --- a/desktop/internal/workbench/remote_list.go +++ b/desktop/internal/workbench/remote_list.go @@ -257,9 +257,13 @@ func (a *App) loadRemoteEffective(connection core.SSHConnection) { r.effective = map[core.SSHConnection]*remoteEffective{} } r.effective[key] = nil - generation, kernel := r.generation, a.kernel + generation, kernel, root := r.generation, a.kernel, a.globalToolchainRoot() a.background(nil, remoteReadTimeout, func(ctx context.Context) func(*App) { - settings, err := kernel.RemoteEffectiveSettings(ctx, key) + var settings core.RemoteEffectiveSettings + preferences, err := remotePreferencesDocument(ctx, kernel, root) + if err == nil { + settings, err = kernel.RemoteEffectiveSettings(ctx, key, preferences) + } return func(a *App) { r := &a.remote if !r.open || r.generation != generation { @@ -313,7 +317,7 @@ func (a *App) remoteAutoPlaceholder(language i18n.Language, value, fallback stri // the empty page's cards and the import menu. Core compares them with the saved list, so a host // already saved is not counted. func (a *App) loadRemoteImportCounts() { - generation, kernel := a.remote.generation, a.kernel + generation, kernel, root := a.remote.generation, a.kernel, a.globalToolchainRoot() document, failure := a.remote.source.Document() a.background(nil, remoteReadTimeout, func(ctx context.Context) func(*App) { counts := remoteImportCounts{loaded: true} @@ -329,7 +333,11 @@ func (a *App) loadRemoteImportCounts() { } } if home, err := os.UserHomeDir(); err == nil { - hosts, err := kernel.RemoteSSHConfigHosts(ctx, home, document) + preferences, err := remotePreferencesDocument(ctx, kernel, root) + var hosts core.RemoteSSHConfigHosts + if err == nil { + hosts, err = kernel.RemoteSSHConfigHosts(ctx, home, document, preferences) + } if err != nil { failure = err } diff --git a/desktop/internal/workbench/remote_ports_test.go b/desktop/internal/workbench/remote_ports_test.go index 2d56b3993..3756761ec 100644 --- a/desktop/internal/workbench/remote_ports_test.go +++ b/desktop/internal/workbench/remote_ports_test.go @@ -631,6 +631,7 @@ func TestRemotePortsForgetTheForwardsOfALostSession(t *testing.T) { k.once = &core.Error{Command: "remote.serverState", Code: core.CodeConnectionClosed, Message: "closed"} }) h.fireAfter(t, timers, remoteHeartbeatInterval) + h.fireReconnect(t, timers, r) h.await("the new session's reading", func() bool { return r.session == "session-2" && !r.beating && r.ports.listed && !p.tree.reading }) diff --git a/desktop/internal/workbench/remote_preferences.go b/desktop/internal/workbench/remote_preferences.go new file mode 100644 index 000000000..5b5467714 --- /dev/null +++ b/desktop/internal/workbench/remote_preferences.go @@ -0,0 +1,46 @@ +package workbench + +import ( + "context" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/remoteconn" +) + +// remotePreferencesDocument is the remote workspace preference document kept under root, for a +// Core request that starts OpenSSH: nil when there is no preference directory or no document, so +// every value is automatic. A damaged document fails with remoteconn.ErrDamaged, so OpenSSH does +// not start with a program the user did not choose. It runs off the window thread; root is +// a.globalToolchainRoot() read on it. +func remotePreferencesDocument(ctx context.Context, kernel Kernel, root string) (*string, error) { + if root == "" { + return nil, nil + } + return remoteconn.PreferencesDocument(ctx, kernel, root) +} + +// 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 + } + delays := make([]time.Duration, len(reconnect.DelaysMilliseconds)) + for i, milliseconds := range reconnect.DelaysMilliseconds { + delays[i] = time.Duration(milliseconds) * time.Millisecond + } + return delays, nil +} diff --git a/desktop/internal/workbench/remote_terminal_test.go b/desktop/internal/workbench/remote_terminal_test.go index 936ec6a5a..6aeb670ca 100644 --- a/desktop/internal/workbench/remote_terminal_test.go +++ b/desktop/internal/workbench/remote_terminal_test.go @@ -329,7 +329,7 @@ func TestRemoteWorkspaceTerminalEndsWithTheConnection(t *testing.T) { } k.set(func(k *remoteHostKernel) { k.refuse = "" }) - h.fire(t, timers) + h.fireReconnect(t, timers, p.remote) if p.remote.session == "" || p.remote.session == run.session { t.Fatal("the workspace did not connect again") } diff --git a/desktop/internal/workbench/remote_test.go b/desktop/internal/workbench/remote_test.go index 75822d6c0..62375d2e5 100644 --- a/desktop/internal/workbench/remote_test.go +++ b/desktop/internal/workbench/remote_test.go @@ -50,7 +50,7 @@ type remoteProbeKernel struct { result core.RemoteProbeResult } -func (k *remoteProbeKernel) RemoteProbe(context.Context, core.SSHConnection) (core.RemoteProbeResult, error) { +func (k *remoteProbeKernel) RemoteProbe(context.Context, core.SSHConnection, *string) (core.RemoteProbeResult, error) { return k.result, nil } @@ -584,7 +584,7 @@ type importCountKernel struct { documents []*string } -func (k *importCountKernel) RemoteSSHConfigHosts(_ context.Context, _ string, document *string) (core.RemoteSSHConfigHosts, error) { +func (k *importCountKernel) RemoteSSHConfigHosts(_ context.Context, _ string, document, _ *string) (core.RemoteSSHConfigHosts, error) { k.documents = append(k.documents, document) var hosts core.RemoteSSHConfigHosts for _, alias := range []string{"alpha", "beta"} { diff --git a/desktop/internal/workbench/remote_watch_test.go b/desktop/internal/workbench/remote_watch_test.go index 196fa1dbb..807517bed 100644 --- a/desktop/internal/workbench/remote_watch_test.go +++ b/desktop/internal/workbench/remote_watch_test.go @@ -324,6 +324,7 @@ func TestRemoteWatchFollowsTheSession(t *testing.T) { k.once = &core.Error{Command: "remote.serverState", Code: core.CodeConnectionClosed, Message: "closed"} }) h.fire(t, timers) + h.fireReconnect(t, timers, r) h.await("the second session", func() bool { return r.session == "session-2" && !r.beating }) h.awaitWatching(p) if w := k.lastWatch(t); w.session != "session-2" || k.watchRuns() != 2 { @@ -331,6 +332,7 @@ func TestRemoteWatchFollowsTheSession(t *testing.T) { } k.lastWatch(t).finish(t, &core.Error{Command: "remote.runWatch", Code: core.CodeConnectionClosed, Message: "closed"}) + h.fireReconnect(t, timers, r) h.await("the third session", func() bool { return r.session == "session-3" && !r.beating }) h.awaitWatching(p) if w := k.lastWatch(t); w.session != "session-3" || !slices.Contains(k.closed, "session-2") { diff --git a/desktop/internal/workbench/remote_workspace.go b/desktop/internal/workbench/remote_workspace.go index 524ad9eb3..32a3bc88f 100644 --- a/desktop/internal/workbench/remote_workspace.go +++ b/desktop/internal/workbench/remote_workspace.go @@ -44,12 +44,6 @@ const ( // unresponsive; remoteHeartbeatMisses in a row end the session and connect again. remoteHeartbeatTimeout = 10 * time.Second remoteHeartbeatMisses = 3 - // remoteReconnectAttempts bounds the attempts to connect again after the connection was lost. - // The pause before the next attempt doubles from remoteReconnectFirstPause up to - // remoteReconnectMaxPause. - remoteReconnectAttempts = 6 - remoteReconnectFirstPause = time.Second - remoteReconnectMaxPause = 30 * time.Second // remoteDisconnectTimeout bounds ending one session; remoteCloseAllTimeout bounds ending every // session while the application quits. remoteDisconnectTimeout = 10 * time.Second @@ -97,8 +91,13 @@ type remoteProject struct { timer uint64 beating bool // attempt counts the attempts of the current reconnection; reconnecting is the running one. + // delays are the pauses before its automatic attempts, read from the remote workspace + // preferences when the connection was lost; lost tells a reading apart from one a later loss + // or Reconnect replaced. attempt int reconnecting *remoteProbe + delays []time.Duration + lost uint64 // failure is why connecting again failed, nil while it has not. failure *remoteProbeOutcome // menuOpen is the status bar's menu of the connection. @@ -200,9 +199,10 @@ func (a *App) remotePlaceholderAnchor() (string, error) { return remoteplaceholder.DefaultAnchor() } -// connectRemoteHost opens a session to host with the server builds the client carries. It runs -// off the window thread. -func (a *App) connectRemoteHost(ctx context.Context, kernel Kernel, host remoteHost) (core.RemoteConnectResult, 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) { bundle, err := a.remoteServerBundle() if err != nil { return core.RemoteConnectResult{}, err @@ -211,7 +211,14 @@ func (a *App) connectRemoteHost(ctx context.Context, kernel Kernel, host remoteH for i, build := range bundle.Builds { servers[i] = core.RemoteServerBuild{Target: build.Target, Path: build.Path, SHA256: build.SHA256} } - return kernel.RemoteConnect(ctx, host.request(servers, bundle.Version)) + request := host.request(servers, bundle.Version) + 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 { + return core.RemoteConnectResult{}, err + } + } + return kernel.RemoteConnect(ctx, request) } // remoteConnectOutcome is the result of a connection to host as the window shows a test's. @@ -352,21 +359,53 @@ func (a *App) loseRemote(p *project, session string, err error) { r.binding.Detach() r.stopRemoteTimer() a.releaseRemoteSession(session) - r.attempt = 0 - a.reconnectRemote(p, false) + a.startRemoteReconnection(p) +} + +// startRemoteReconnection reads how long to connect again from the remote workspace preferences +// and waits for the first pause. With no pauses, a reconnect limit of 0, the workspace stays +// disconnected until the user reconnects; preferences that cannot be read leave it disconnected +// with the reason in the status bar's menu. +func (a *App) startRemoteReconnection(p *project) { + r := p.remote + r.attempt, r.delays, r.link, r.failure = 0, nil, remoteReconnecting, nil + r.lost++ + lost, kernel, root, host := r.lost, a.kernel, a.globalToolchainRoot(), r.host + a.background(p, remoteReadTimeout, func(ctx context.Context) func(*App) { + delays, err := remoteReconnectDelays(ctx, kernel, root) + return func(a *App) { + if a.project != p || r.closed || r.lost != lost || r.session != "" || r.reconnecting != nil { + // log-exempt: 用户取消:工作区已关闭,或用户已手动重连,这次读取不再适用。 + return + } + if err != nil { + a.backgroundFailed("remote_reconnect_preferences", documentLogError(err)) + r.link, r.failure = remoteDisconnected, remoteConnectOutcome(host, core.RemoteConnectResult{}, err) + return + } + r.delays = delays + if len(delays) == 0 { + r.link = remoteDisconnected + // log-exempt: 用户设置:自动重连上限为 0,连接丢失已记录(remote_session_lost)。 + return + } + a.scheduleRemote(p, delays[0], func(a *App, p *project) { a.reconnectRemote(p, false) }) + } + }) } // reconnectRemote opens a new session over the workspace's connection. userStarted is Reconnect // in the status bar: it starts the attempts afresh, asks OpenSSH's questions in the window and // does not try again on its own. An automatic attempt cancels every question and, while the host -// is unreachable, tries again after a pause up to remoteReconnectAttempts times. +// 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 != "" { return } if userStarted { - r.attempt = 0 + r.attempt, r.delays = 0, nil + r.lost++ } r.attempt++ r.stopRemoteTimer() @@ -377,10 +416,10 @@ func (a *App) reconnectRemote(p *project, userStarted bool) { } attempt := &remoteProbe{cancel: cancel} r.reconnecting = attempt - kernel, host := a.kernel, r.host + kernel, root, host := a.kernel, a.globalToolchainRoot(), r.host a.background(nil, 0, func(context.Context) func(*App) { defer cancel() - result, err := a.connectRemoteHost(ctx, kernel, host) + result, err := a.connectRemoteHost(ctx, kernel, root, host) return func(a *App) { if a.project != p || r.closed || r.reconnecting != attempt { if result.Session != nil { @@ -400,9 +439,9 @@ func (a *App) reconnectRemote(p *project, userStarted bool) { a.releaseRemoteSession(result.Session.ID) } r.failure = remoteConnectOutcome(host, result, err) - if !userStarted && r.attempt < remoteReconnectAttempts && remoteRetryable(result.Status, err) { + if !userStarted && r.attempt < len(r.delays) && remoteRetryable(result.Status, err) { r.link = remoteReconnecting - a.scheduleRemote(p, remoteReconnectPause(r.attempt), func(a *App, p *project) { a.reconnectRemote(p, false) }) + a.scheduleRemote(p, r.delays[r.attempt], func(a *App, p *project) { a.reconnectRemote(p, false) }) // log-exempt: 同一次失败已经记录过:导致重连的连接丢失已记录(remote_session_lost),最后一次尝试的结果另记 remote_reconnect。 return } @@ -426,15 +465,6 @@ func remoteRetryable(status core.RemoteProbeStatus, err error) bool { return status == core.RemoteProbeUnreachable } -// remoteReconnectPause is the pause after the failed attempt-th attempt. -func remoteReconnectPause(attempt int) time.Duration { - pause := remoteReconnectFirstPause - for i := 1; i < attempt && pause < remoteReconnectMaxPause; i++ { - pause *= 2 - } - return min(pause, remoteReconnectMaxPause) -} - // refreshRemoteTree reads the Project tool window's listings again over the new session: the root // when it could not be listed, otherwise the folders shown open. func (a *App) refreshRemoteTree(p *project) { diff --git a/desktop/internal/workbench/remote_workspace_test.go b/desktop/internal/workbench/remote_workspace_test.go index 254f50abb..5a88ac934 100644 --- a/desktop/internal/workbench/remote_workspace_test.go +++ b/desktop/internal/workbench/remote_workspace_test.go @@ -221,6 +221,31 @@ func (s *remoteTimers) take(t *testing.T) *remoteTimer { return live[0] } +// live counts the timers still pending. +func (s *remoteTimers) live() (n int) { + s.mu.Lock() + defer s.mu.Unlock() + for _, timer := range s.pending { + if !timer.stopped { + n++ + } + } + return n +} + +// fireReconnect waits for the pause before the first attempt to connect again, which the +// workspace schedules once it has read the reconnect delays off the window thread, checks it is +// Core's first pause and runs it. +func (h *harness) fireReconnect(t *testing.T, timers *remoteTimers, r *remoteProject) { + t.Helper() + h.await("the pause before connecting again", func() bool { + return r.session == "" && len(r.delays) > 0 && r.attempt == 0 && timers.live() == 1 + }) + if d := h.fire(t, timers); d != time.Second { + t.Fatalf("paused %v before connecting again, want Core's first pause of 1s", d) + } +} + // fire runs the pending timer, applies the heartbeat or the attempt it starts, and says how long // the workspace had asked to wait. func (h *harness) fire(t *testing.T, timers *remoteTimers) time.Duration { @@ -470,13 +495,20 @@ func TestRemoteWorkspaceReconnectsAfterMissedHeartbeats(t *testing.T) { } var pauses []time.Duration for r.link == remoteReconnecting { + // The first pause waits for the reconnect delays, which are read off the window thread. + h.await("the next pause", func() bool { return timers.live() == 1 || r.link != remoteReconnecting }) + if r.link != remoteReconnecting { + break + } pauses = append(pauses, h.fire(t, timers)) } - if want := []time.Duration{time.Second, 2 * time.Second, 4 * time.Second, 8 * time.Second, 16 * time.Second}; !slices.Equal(pauses, want) { + // Core's automatic reconnect limit of 60 seconds: one attempt after each pause. + want := []time.Duration{time.Second, 2 * time.Second, 4 * time.Second, 8 * time.Second, 16 * time.Second, 29 * time.Second} + if !slices.Equal(pauses, want) { t.Fatalf("paused %v before connecting again, want %v", pauses, want) } - if got := k.count(func(k *remoteHostKernel) int { return k.connects }); got != 1+remoteReconnectAttempts { - t.Fatalf("connected %d times, want the first and %d attempts", got, remoteReconnectAttempts) + if got := k.count(func(k *remoteHostKernel) int { return k.connects }); got != 1+len(want) { + t.Fatalf("connected %d times, want the first and %d attempts", got, len(want)) } if r.link != remoteDisconnected || !h.shows(remoteStatusText(lang, r)) { t.Fatalf("link %v after the last attempt, want disconnected", r.link) @@ -512,9 +544,9 @@ func TestRemoteWorkspaceReconnectsAfterMissedHeartbeats(t *testing.T) { t.Fatalf("%s logged %d times, want once", operation, got) } } - want := []string{"remote.workspace.reconnect", "remote.workspace.disconnect"} - if got := remoteActions(logger); !slices.Equal(got[len(got)-2:], want) { - t.Fatalf("performed %q, want it to end with %q", got, want) + actions := []string{"remote.workspace.reconnect", "remote.workspace.disconnect"} + if got := remoteActions(logger); !slices.Equal(got[len(got)-2:], actions) { + t.Fatalf("performed %q, want it to end with %q", got, actions) } if event := loggedAny(t, logger, remoteTestHost, remoteTestHome); event != "" { t.Fatalf("logged the host or its paths: %s", event) @@ -531,6 +563,7 @@ func TestRemoteWorkspaceReconnectsWhenTheConnectionCloses(t *testing.T) { k.once = &core.Error{Command: "remote.serverState", Code: core.CodeConnectionClosed, Message: "closed"} }) h.fire(t, timers) + h.fireReconnect(t, timers, r) h.await("the new session", func() bool { return r.session == "session-2" && !r.beating && !p.tree.reading }) if r.link != remoteConnected || !slices.Contains(k.closed, "session-1") { t.Fatalf("link %v, closed %q: the lost session was not replaced", r.link, k.closed) diff --git a/desktop/internal/workbench/settings_toolchains.go b/desktop/internal/workbench/settings_toolchains.go index 743fa7cfc..2c512ed1f 100644 --- a/desktop/internal/workbench/settings_toolchains.go +++ b/desktop/internal/workbench/settings_toolchains.go @@ -3,10 +3,12 @@ package workbench import ( "context" "errors" + "os" "github.com/1lck/Lithe-IDEA/desktop/internal/core" "github.com/1lck/Lithe-IDEA/desktop/internal/pluginruntime" "github.com/1lck/Lithe-IDEA/desktop/internal/remoteconn" + "github.com/1lck/Lithe-IDEA/desktop/internal/settingswindow" "github.com/1lck/Lithe-IDEA/desktop/internal/toolchain" ) @@ -121,6 +123,40 @@ func (s settingsToolchains) SaveRemoteTrust(ctx context.Context, trust remotecon return remoteconn.ReadTrust(ctx, s.app.kernel, s.app.globalToolchainRoot(), "", "") } +// LoadRemotePreferences reads the remote workspace preferences and what each value resolves to +// when it is automatic. A damaged file still names its path. Core's message may name local paths, +// so only its code is logged. +func (s settingsToolchains) LoadRemotePreferences(ctx context.Context) (prefs settingswindow.RemotePreferences, err error) { + defer func() { s.recordFailure(ctx, "remote_preferences_settings_load", documentLogError(err)) }() + return s.readRemotePreferences(ctx) +} + +// SaveRemotePreferences applies the page's edits in order against the bytes prefs was read from; +// a refused or conflicting edit stops the rest. Connections read the file each time OpenSSH +// starts, and a lost connection reads the reconnect limit when it is lost. +func (s settingsToolchains) SaveRemotePreferences(ctx context.Context, prefs settingswindow.RemotePreferences, edits []core.RemotePreferenceEdit) (updated settingswindow.RemotePreferences, err error) { + ctx = s.app.performedIn(ctx, "remote.preferences.edit", surfaceButton) + defer func() { s.recordFailure(ctx, "remote_preferences_settings_save", documentLogError(err)) }() + saved := prefs.Saved + for _, edit := range edits { + if saved, _, err = saved.Edit(ctx, s.app.kernel, edit); err != nil { + return prefs, err + } + } + return s.readRemotePreferences(ctx) +} + +func (s settingsToolchains) readRemotePreferences(ctx context.Context) (settingswindow.RemotePreferences, error) { + // The home directory only names ~/.ssh/config; without one the row is left out. + home, _ := os.UserHomeDir() + automatic, err := s.app.kernel.RemotePreferences(ctx, nil, "") + if err != nil { + return settingswindow.RemotePreferences{}, err + } + saved, err := remoteconn.ReadPreferences(ctx, s.app.kernel, s.app.globalToolchainRoot(), home) + return settingswindow.RemotePreferences{Saved: saved, Automatic: automatic}, err +} + // settingsToolchains is the settings window's adapter onto the workbench: it // reads the open project's enabled plugin manifests and writes explicit // directory pins. All calls run on the settings window's background worker. diff --git a/docs/assets/remote-settings/README.md b/docs/assets/remote-settings/README.md new file mode 100644 index 000000000..f7f0d3a2c --- /dev/null +++ b/docs/assets/remote-settings/README.md @@ -0,0 +1,16 @@ +# “设置 › 工具 › 远程工作区”页(#2231)无头测试截图 + +来自生产 Viva 设置窗口的无头渲染,由 `TestVisualRemoteWorkspace` 生成。页面经真实的 Core 客户端调用 `remote.preferences`,偏好目录和主目录都是测试里的虚构路径(`/Users/example`),打开页面和起草都不创建任何文件。截图覆盖深色与浅色主题、中文与英文界面,用于确认: + +- “SSH 程序”默认显示“自动(Core 在 PATH 上找到的 ssh 路径)”,旁边的“选择…”选一个文件作为草稿; +- “SSH 配置文件”只读显示 Core 读取的 `~/.ssh/config` 路径,文件不存在时在路径后注明“不存在”,注明不随宽度截断; +- “自动重连时长”默认“自动(1 分钟)”,草稿状态选了 5 分钟; +- “保存位置”显示偏好目录下的 `remote/preferences.json`,还没有文件时注明“修改后才创建”,路径过长时截断并在悬停提示里给出完整路径; +- 修改只是草稿:侧栏页名后有圆点,底部显示未应用的数量和写入目标,点“应用”或“好”才写入。 + +截图不代表 macOS/Windows 原生窗口验收,也不代表真实 SSH 主机上的整机验收。 + +| 场景 | 浅色英文 | 深色中文 | +| --- | --- | --- | +| 自动值 | [浅色英文](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) | 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 new file mode 100644 index 000000000..a2dc847d3 Binary files /dev/null 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 new file mode 100644 index 000000000..cea59a5ef Binary files /dev/null and b/docs/assets/remote-settings/remote-settings-automatic-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 new file mode 100644 index 000000000..c9d2c9c06 Binary files /dev/null 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 new file mode 100644 index 000000000..d563cd867 Binary files /dev/null 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 789e17d79..52ec1a6e1 100755 --- a/scripts/desktop/build-desktop-core.sh +++ b/scripts/desktop/build-desktop-core.sh @@ -324,7 +324,9 @@ PINNED_CORE_REPOSITORY="https://github.com/Lithe-IDEA/Lithe-core-rust.git" # typed into the Ports window (#2231). # Lithe-core-rust main at 5c163e9: #157 remote.connect opens a local WSL distribution through # wsl.exe (the wsl field) and remote.listWslDistributions lists the installed ones (#2231). -PINNED_CORE_REVISION="5c163e9660d1447d17a8279aec151d23099e47e1" +# 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="49fb750ad8acfe5a208f9352be9a371c4f7c2967" PROFILE="debug" CHECKOUT_ONLY="no" while [[ $# -gt 0 ]]; do diff --git a/shared/i18n/features/remote-settings.json b/shared/i18n/features/remote-settings.json new file mode 100644 index 000000000..d66393204 --- /dev/null +++ b/shared/i18n/features/remote-settings.json @@ -0,0 +1,350 @@ +{ + "schemaVersion": 1, + "messages": [ + { + "id": "desktop.remoteSettings.title", + "description": "Settings sidebar and breadcrumb: title of the page holding the remote workspace preferences (SSH program, reconnection)", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remoteSettings.keywords", + "description": "Settings search: extra words that find the Remote Workspace page, separated by spaces", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remoteSettings.target", + "description": "Settings footer: where Apply writes the remote workspace drafts, joined into the list of targets; lowercase in English", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remoteSettings.connection", + "description": "Remote Workspace page: title of the card about how hosts are reached", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remoteSettings.sshProgram", + "description": "Remote Workspace page: label of the row choosing the OpenSSH client program", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remoteSettings.sshProgramHelp", + "description": "Remote Workspace page: help behind the info glyph of the SSH program row", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remoteSettings.programAutomatic", + "description": "Remote Workspace page: the automatic choice of the SSH program, with the program it resolves to", + "platforms": [ + "desktop" + ], + "parameters": { + "path": "string" + } + }, + { + "id": "desktop.remoteSettings.programAutomaticMissing", + "description": "Remote Workspace page: the automatic choice of the SSH program when no ssh is on PATH", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remoteSettings.chooseProgram", + "description": "Remote Workspace page: button that picks an SSH program file", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remoteSettings.chooseProgramTitle", + "description": "Remote Workspace page: title of the file dialog picking the SSH program", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remoteSettings.programMissing", + "description": "Remote Workspace page: the saved SSH program no longer exists", + "platforms": [ + "desktop" + ], + "parameters": { + "path": "string" + } + }, + { + "id": "desktop.remoteSettings.programNotExecutable", + "description": "Remote Workspace page: the saved SSH program is not an executable file", + "platforms": [ + "desktop" + ], + "parameters": { + "path": "string" + } + }, + { + "id": "desktop.remoteSettings.sshConfig", + "description": "Remote Workspace page: label of the row naming the user's OpenSSH configuration file", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remoteSettings.sshConfigHelp", + "description": "Remote Workspace page: help behind the info glyph of the SSH configuration row", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remoteSettings.sshConfigMissing", + "description": "Remote Workspace page: the note after the OpenSSH configuration file's path when the file does not exist", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remoteSettings.reconnection", + "description": "Remote Workspace page: title of the card about connecting again after a connection is lost", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remoteSettings.reconnectLimit", + "description": "Remote Workspace page: label of the row choosing how long a lost connection is retried", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remoteSettings.reconnectLimitHelp", + "description": "Remote Workspace page: help behind the info glyph of the reconnect row", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remoteSettings.reconnectAutomatic", + "description": "Remote Workspace page: the automatic reconnect choice, with the time it resolves to", + "platforms": [ + "desktop" + ], + "parameters": { + "duration": "string" + } + }, + { + "id": "desktop.remoteSettings.reconnectNever", + "description": "Remote Workspace page: reconnect choice that never retries automatically", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remoteSettings.seconds", + "description": "Remote Workspace page: a duration in seconds", + "platforms": [ + "desktop" + ], + "parameters": { + "count": "string" + } + }, + { + "id": "desktop.remoteSettings.minutes", + "description": "Remote Workspace page: a duration in whole minutes", + "platforms": [ + "desktop" + ], + "parameters": { + "count": "string" + } + }, + { + "id": "desktop.remoteSettings.storage", + "description": "Remote Workspace page: label of the row naming the file the preferences are kept in", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remoteSettings.storageHelp", + "description": "Remote Workspace page: help behind the info glyph of the storage row", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remoteSettings.storageNone", + "description": "Remote Workspace page: the note after the preference file's path while every value is automatic and no file exists yet", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remoteSettings.damaged", + "description": "Remote Workspace page: the preference file cannot be decoded; the path is shown", + "platforms": [ + "desktop" + ], + "parameters": { + "path": "string" + } + }, + { + "id": "desktop.remoteSettings.conflict", + "description": "Remote Workspace page: the preference file changed while the user edited it", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remoteSettings.unavailable", + "description": "Remote Workspace page: there is no preference folder to keep the preferences in", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remoteSettings.failed", + "description": "Remote Workspace page: the preferences could not be read or written; the reason follows", + "platforms": [ + "desktop" + ], + "parameters": { + "reason": "string" + } + }, + { + "id": "desktop.remoteSettings.refusedProgramRelative", + "description": "Remote Workspace page: Apply refused an SSH program that is not an absolute path", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remoteSettings.refusedProgramMissing", + "description": "Remote Workspace page: Apply refused an SSH program that does not exist", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remoteSettings.refusedProgramNotExecutable", + "description": "Remote Workspace page: Apply refused an SSH program that is not executable", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remoteSettings.refusedProgram", + "description": "Remote Workspace page: Apply refused the SSH program path for another reason (too long, invalid)", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remoteSettings.refusedLimit", + "description": "Remote Workspace page: Apply refused the reconnect time", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.preferences.damaged", + "description": "Remote connection failure: the remote workspace preference file is damaged, so OpenSSH is not started", + "platforms": [ + "desktop" + ] + } + ], + "locales": { + "en-US": { + "desktop.remoteSettings.title": "Remote Workspace", + "desktop.remoteSettings.keywords": "remote ssh openssh host server reconnect reconnection connection wsl", + "desktop.remoteSettings.target": "remote workspace settings", + "desktop.remoteSettings.connection": "Connection", + "desktop.remoteSettings.sshProgram": "SSH program", + "desktop.remoteSettings.sshProgramHelp": "The OpenSSH client started to reach a host. Automatic uses the ssh found on PATH. WSL distributions are reached without SSH and do not use it.", + "desktop.remoteSettings.programAutomatic": "Automatic ({path})", + "desktop.remoteSettings.programAutomaticMissing": "Automatic (no ssh found)", + "desktop.remoteSettings.chooseProgram": "Choose…", + "desktop.remoteSettings.chooseProgramTitle": "Choose SSH Program", + "desktop.remoteSettings.programMissing": "{path} does not exist. Connecting fails until it is back or the program is set to Automatic.", + "desktop.remoteSettings.programNotExecutable": "{path} is not an executable file. Connecting fails until it is or the program is set to Automatic.", + "desktop.remoteSettings.sshConfig": "SSH configuration", + "desktop.remoteSettings.sshConfigHelp": "Host aliases, ports, keys and jump hosts come from this file. Lithe reads it and never writes it.", + "desktop.remoteSettings.sshConfigMissing": "Does not exist", + "desktop.remoteSettings.reconnection": "Reconnection", + "desktop.remoteSettings.reconnectLimit": "Retry for", + "desktop.remoteSettings.reconnectLimitHelp": "After a connection is lost, Lithe tries again within this time, waiting 1, 2, 4… seconds and at most 29 seconds between attempts. With Don't Reconnect the workspace stays disconnected until you reconnect it.", + "desktop.remoteSettings.reconnectAutomatic": "Automatic ({duration})", + "desktop.remoteSettings.reconnectNever": "Don't Reconnect", + "desktop.remoteSettings.seconds": "{count} s", + "desktop.remoteSettings.minutes": "{count} min", + "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.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.", + "desktop.remoteSettings.failed": "The remote workspace settings could not be read or saved: {reason}", + "desktop.remoteSettings.refusedProgramRelative": "The SSH program must be an absolute path.", + "desktop.remoteSettings.refusedProgramMissing": "The chosen SSH program does not exist.", + "desktop.remoteSettings.refusedProgramNotExecutable": "The chosen SSH program is not an executable file.", + "desktop.remoteSettings.refusedProgram": "The SSH program path cannot be used.", + "desktop.remoteSettings.refusedLimit": "The reconnect time must be between 0 and 3600 seconds.", + "desktop.remote.preferences.damaged": "The remote workspace settings file is damaged, so the host was not connected. Open Settings › Tools › Remote Workspace to see it." + }, + "zh-CN": { + "desktop.remoteSettings.title": "远程工作区", + "desktop.remoteSettings.keywords": "远程 主机 服务器 重连 断线 连接 remote ssh openssh wsl", + "desktop.remoteSettings.target": "远程工作区设置", + "desktop.remoteSettings.connection": "连接", + "desktop.remoteSettings.sshProgram": "SSH 程序", + "desktop.remoteSettings.sshProgramHelp": "连接主机时启动的 OpenSSH 客户端。自动时使用 PATH 中找到的 ssh。WSL 发行版不经过 SSH,不受影响。", + "desktop.remoteSettings.programAutomatic": "自动({path})", + "desktop.remoteSettings.programAutomaticMissing": "自动(未找到 ssh)", + "desktop.remoteSettings.chooseProgram": "选择…", + "desktop.remoteSettings.chooseProgramTitle": "选择 SSH 程序", + "desktop.remoteSettings.programMissing": "找不到 {path}。在它恢复或改回自动之前,连接会失败。", + "desktop.remoteSettings.programNotExecutable": "{path} 不是可执行文件。在修好或改回自动之前,连接会失败。", + "desktop.remoteSettings.sshConfig": "SSH 配置文件", + "desktop.remoteSettings.sshConfigHelp": "主机别名、端口、密钥和跳板机都从这个文件读取。Lithe 只读取,不会写入。", + "desktop.remoteSettings.sshConfigMissing": "不存在", + "desktop.remoteSettings.reconnection": "断线重连", + "desktop.remoteSettings.reconnectLimit": "自动重连时长", + "desktop.remoteSettings.reconnectLimitHelp": "连接断开后,在这段时间内自动重试,间隔依次为 1、2、4…秒,最长 29 秒。选“不自动重连”时,工作区保持断开,直到你手动重连。", + "desktop.remoteSettings.reconnectAutomatic": "自动({duration})", + "desktop.remoteSettings.reconnectNever": "不自动重连", + "desktop.remoteSettings.seconds": "{count} 秒", + "desktop.remoteSettings.minutes": "{count} 分钟", + "desktop.remoteSettings.storage": "保存位置", + "desktop.remoteSettings.storageHelp": "只保存你改过的值,放在本机的偏好设置目录中,不会写到主机上。", + "desktop.remoteSettings.storageNone": "修改后才创建", + "desktop.remoteSettings.damaged": "无法读取 {path}。请修正或删除这个文件;修好之前不会用它连接主机。", + "desktop.remoteSettings.conflict": "设置文件在此期间被改过,已重新读取。请再次应用你的修改。", + "desktop.remoteSettings.unavailable": "没有可以保存这些设置的偏好设置目录。", + "desktop.remoteSettings.failed": "无法读取或保存远程工作区设置:{reason}", + "desktop.remoteSettings.refusedProgramRelative": "SSH 程序必须是绝对路径。", + "desktop.remoteSettings.refusedProgramMissing": "找不到选择的 SSH 程序。", + "desktop.remoteSettings.refusedProgramNotExecutable": "选择的 SSH 程序不是可执行文件。", + "desktop.remoteSettings.refusedProgram": "这个 SSH 程序路径不能使用。", + "desktop.remoteSettings.refusedLimit": "自动重连时长必须在 0 到 3600 秒之间。", + "desktop.remote.preferences.damaged": "远程工作区设置文件已损坏,因此没有连接主机。请在 设置 › 工具 › 远程工作区 中查看。" + } + } +} diff --git a/shared/platform-feature-matrix/features/remote-workspace.json b/shared/platform-feature-matrix/features/remote-workspace.json index 97db91539..6f8b29036 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、端口转发", + "capability": "远程连接(SSH 主机与本机 WSL 发行版)、远程路径工作区、主机文件编辑与监听、主机终端、主机搜索与替换、远程信任与主机 Git、端口转发、远程工作区设置(SSH 程序与断线重连)", "macos": { "implementationStatus": "partial", "verificationStatus": "pending", @@ -47,7 +47,15 @@ "desktop/internal/workbench/remote_ports_test.go", "desktop/internal/workbench/remote_ports_visual_test.go", "desktop/internal/workbench/remote_wsl.go", - "desktop/internal/workbench/remote_wsl_test.go" + "desktop/internal/workbench/remote_wsl_test.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/remoteconn/preferences_test.go", + "desktop/internal/settingswindow/remote_workspace_view_test.go", + "desktop/internal/settingswindow/remote_workspace_visual_test.go" ] }, "windows": { @@ -80,11 +88,16 @@ "desktop/internal/core/remote_forward.go", "desktop/internal/workbench/remote_ports.go", "desktop/internal/workbench/remote_ports_view.go", - "desktop/internal/workbench/remote_wsl.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" ] }, "owner": "Remote", - "verification": "在“远程开发”窗口选中已保存的 Linux SSH 连接点“连接”:SSH 询问出现在窗口中,连接后窗口改为主机的文件夹选择,从主目录开始列出子文件夹(跳过名称不是 UTF-8 的条目并说明数量),可输入 ~ 或 / 开头的路径跳转,不存在的路径说明原因且不能打开;“返回”断开这次会话回到连接表单。选中文件夹点“打开”:新标签页打开远程工作区,窗口标题为“文件夹 [SSH: 连接名]”,项目树经 Core 列出主机目录(本机占位目录始终为空),右键只有复制主机路径和刷新;以安全模式打开的文件夹,编辑器上方说明可以浏览、编辑、保存和搜索主机文件,信任文件夹后才能用 Git;受信任的文件夹说明文件、终端和 Git 都在主机上,运行、调试和语言服务器暂不可用;空白编辑区提示 Search Everywhere 和 Find in Files。在项目树双击文件:编辑器经会话读取主机文件(不超过 16 MiB),保存时带上打开时的大小和修改时间写回主机,新建的文件只在主机上不存在时创建;主机上的文件期间被别人改过时保存被拒绝并显示外部修改冲突,“加载磁盘版本”载入主机内容,本机占位目录始终为空。超过 8 MiB 的保存说明主机单次保存上限,编辑内容保留;主机上缺失、无权限、不是普通文件、超时和连接断开分别说明原因,连接断开后自动重连并把打开的文档和主机重新比对。图片、PDF 等查看器、文件夹外的文件、本地历史和插件终端都被拒绝并提示,不回退到本机。打开“终端”工具窗口:经会话的 remote.runTerminal 在主机文件夹运行主机账户的登录 shell(不带参数,不读本机 Shell 设置,没有本机 Shell 菜单),标签名为连接名,之后的标签为“连接名 (2)”等;输入按顺序、每块不超过 32 KiB 写入,主机说忙时稍后重试,窗口尺寸随输入发送;输出超过 8 MiB 未显示时丢弃最旧的部分并记一次失败。程序退出显示退出码,被信号结束显示 128+信号,关闭标签不算失败。连接断开时终端显示会话已结束,工作区按退避重连;未连接时按回车说明工作区未连接,重连后按回车在新会话上运行。终端起不来时显示 Core 给出的原因(可能含主机路径),日志只记命令名和错误码。拖到终端的文件粘贴为主机路径并按 POSIX shell 加引号,本机工作区外的文件不粘贴并提示原因;粘贴图片不可用(图片会存到本机)。每个会话连接后,经 remote.runWatch 在主机上递归监听整个文件夹,跳过已启用插件隐藏的文件夹名(按原样比较大小写),插件改变隐藏名称时重新开始监听;在主机上新建、修改、删除文件后,项目树重新列出受影响的目录(Core 的 workspace.filterChanges 按可见性规则过滤,不需要会话),打开的文档与主机比对:没有编辑的重新载入,有编辑的显示外部修改冲突;文件夹外和被隐藏文件夹里的变化不触发列表。监听开始时、主机丢失变化(overflow)时、一次超过 4096 个变化时,重新列出树中展开的目录并比对所有文档,日志每次监听各记一次;主机监听数用尽时其余部分继续监听,提示一次“项目文件可能无法自动更新”。监听中文件夹被删除或移走时立即重新监听;主机找不到文件夹时项目树显示根目录不可用,监听等树重新列出文件夹后再开始,主机与树结论不一致时也只等待、不反复重试。其他监听失败只记命令名和错误码、提示一次,等下一个会话再开始;监听发现连接断开时与心跳一样结束会话并重连。Find in Files 的搜索、计数和替换预览带远程绑定发送,Core 从主机文件夹建立索引并读取主机上的当前内容,结果路径相对主机文件夹;点结果在远程编辑器打开主机文件并定位到匹配处,本机占位目录始终为空。主机监听报告的变化路径在下一次查询前增量更新索引,不重建;监听开始和主机丢失变化时重建一次。包含生成文件的查询每次都重建索引(主机监听跳过插件隐藏的文件夹);主机监听数用尽后、会话断开到下一个会话的监听开始之间,每次查询都重建,只由监听提示一次“项目文件可能无法自动更新”,搜索不再另外提示。查询显示期间主机上的变化让结果重新查询。Search Everywhere 所有页签都可用,文件名和文本来自主机,打开弹窗时重新读取生成文件的名称;远程工作区不启动语言服务器,符号只有 Core 在主机文件中找到的。Replace All 在编辑器中替换打开的文档;未打开的文件经会话读取主机内容,由 Core 替换后,只在主机文件仍是读取时的内容时写回,期间被改过的报告冲突,已被删除的说明主机上找不到文件,其余文件照常替换,都不写本机占位目录。在文件夹选择中打开从未决定过的文件夹:先询问是否信任(显示连接名和主机文件夹,Core 给出上级文件夹时可勾选信任其下的所有文件夹),“信任并打开”把决定按连接名记入 Core 的远程信任记录后以受信任方式打开,“以安全模式打开”只读打开,“返回”回到文件夹选择;之前决定过的文件夹直接按记录打开。安全模式下 Git、提交和日志窗口与本机项目一样说明需要信任,编辑器上方的提示里可以信任文件夹,信任后不重开窗口就在主机上启动 Git。受信任的工作区经会话在主机上运行 Git:状态、暂存、提交、差异(含编辑器行号旁的变更标记)、日志与分支、逐行追溯(读取主机上的文件内容)、搁置与储藏都读写主机仓库,本机占位目录始终没有 .git;“排除到本地”写入主机仓库的 info/exclude(缺少 info 文件夹时在主机上创建,读写期间文件被别人改过时这次排除失败、不覆盖)。同一会话经 remote.runWatch 递归监听主机仓库的 git 目录(公共目录在别处时一并监听),主机上 git checkout、commit 等改动元数据后按路径分类并重新读取状态;监听开始、丢失变化或主机监听数用尽时重新读取一次完整状态,新会话重新开始监听。主机文件夹位于上级目录开始的仓库内时,Git 和提交窗口说明要打开仓库顶层文件夹,不显示变更也不记为失败。工作树列表、锁定、解锁、删除在主机上执行,复制路径复制主机路径;打开、在新窗口打开、在文件浏览器中显示和新建工作树被拒绝并提示。受信任的远程工作区里运行、调试、当前文件运行、测试、构建任务和插件语言服务器都不在本机启动,都记为拒绝并提示,运行、测试和构建工具窗口说明暂不可用。状态栏前端显示连接名和心跳往返时间;连续两次心跳无响应显示“无响应”,第三次结束会话并按 1、2、4、8、16 秒退避重连,共六次失败后显示“已断开”和原因,菜单里可“重新连接”;连接被关闭时立即重连。菜单里“断开并关闭”关闭工作区并结束会话,退出 Lithe 时关闭所有远程会话。最近项目不记录远程工作区。日志只有 remote.connect、remote.workspace.open/reconnect/disconnect 等动作和失败的操作名,不含主机、用户名、主机路径或主目录。运行 remote_workspace_test.go 的 5 个测试、remote_git_test.go 的 6 个测试、remoteplaceholder 的 TestHostAndLocalPathsMapBothWays、remote_documents_test.go 的 2 个测试、remote_terminal_test.go 的 9 个测试、remote_watch_test.go 的 5 个测试、remote_search_test.go 的 4 个测试、internal/core 的 TestRemoteTerminal*、TestRemoteWatch* 与 TestRemoteWorkspaceFiltersChangesWithoutTheHost、termview 的 TestOpenStartsTheProgramElsewhere,以及 TestVisualRemoteWorkspace 无头截图;在 Windows 运行 TestCoreRefusesUnadaptedCommandsAndAClosedSessionDetachesTheBinding,验证 Linux 主机路径能通过绑定校验。真实 SSH 主机上的整机验收(包括终端里 vim、top 等全屏程序与窗口缩放,主机上 git checkout 等大批量修改后的监听,以及大仓库上的搜索)仍待完成。远程工作区左侧多出“端口”工具窗口(本机工作区没有,关闭工作区后消失):窗口打开时每 3 秒经 ports.listening 读取主机上正在监听的端口和会话的转发,窗口关闭或未显示时停止读取;同一端口在 0.0.0.0 与 :: 上监听只显示一行;远端端口带上主机监听的 IP 地址,多个地址时显示第一个和其余数量,悬停提示列出全部,地址或网址过长被截断时悬停提示给出全文;列出远端端口、本机地址、进程(名称与 PID,读不到时为“未知”)、来源(监听发现、手动添加)和状态。默认不自动转发任何端口,打开窗口和发现新端口都不转发;行尾“转发”把端口转发到主机上对应族的回环地址,本机在 127.0.0.1 的同号端口监听,该端口被本机其他程序占用时改用空闲端口,本机地址用警告色显示并在提示里说明原端口。右键“转发到指定本机端口…”和已转发行的“更改本机端口…”打开对话框输入 1–65535 的本机端口,非法输入就地说明且不转发;改到另一个端口时先停止原转发再在新端口转发,选择在工作区打开期间保留,停止后再转发仍用该端口。顶部输入端口、主机:端口或网址(http、https、ws、wss,省略端口时按协议默认端口)可手动添加并转发,由 Core 的 remote.parseForwardAddress 解析;格式不对就地说明,网址里带用户名或密码时拒绝并说明,输入框保留原文、日志不记输入内容;同一目标再次添加不重复。网址行按输入的样子显示,转发到主机上提供该端口的回环地址;在浏览器打开和复制本机地址把主机部分换成本机地址并保留路径和查询,ws/wss 网址不提供在浏览器打开;浏览器打不开时提示网址,日志只记失败、不记网址。主机回环地址以外的目标先询问(S28),确认后才带 AllowNonLoopback 转发,取消记为拒绝。已转发行可在浏览器打开、复制本机地址、停止;手动添加且已停止、主机上也没有在监听的行可移除;窗口标题栏可全部停止,标题栏的 ⓘ 说明转发对本机其他程序可见(S30);会话转发数达到 Core 上限时说明上限;状态栏显示已转发数量,点击打开端口窗口;会话结束时转发随之结束,重连后不自动恢复。日志只记 remote.ports.forward/localPort/move/stop/status 等动作和失败操作名,不含主机、地址或进程名。运行 remote_ports_test.go 的 12 个测试、internal/core 的 TestRemoteSessionCommandsOfAnUnknownSession 与 TestRemoteParseForwardAddressReadsPortsAndURLs,以及 TestVisualRemotePorts 无头截图。手动添加的端口和本机端口选择只在工作区打开期间保留,关闭后不保存(需 Core 存储,后续阶段);主机侧监听的转发规则(主机端口转到另一台服务器)和反向转发只完成设计,尚未实现。远程 Git 的 AskPass 转交(推送、拉取时的凭据询问)、从上级目录开始的仓库、打开或新建远程工作树尚未支持。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 进程是否退出、未知用户)仍待完成。", + "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 存储,后续阶段);主机侧监听的转发规则(主机端口转到另一台服务器)和反向转发只完成设计,尚未实现。远程 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* 4 个测试、remoteconn 的 preferences_test.go、internal/core 的 TestRemotePreferences*,以及 TestVisualRemoteWorkspace 无头截图(中英文、深浅色,自动值与草稿两种状态)。", "legacy": { "revision": "5a54c41aa37a4e6e6b68918a4b05765b9dd07a36", "macos": { @@ -121,5 +134,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。读取在窗口的后台任务里进行,只在窗口打开且被绘制过时排下一次,不做空闲轮询。 WSL:remote.connect 的 connection 与 wsl 二选一,Core 经 wsl.exe --distribution … --exec 启动同一个远端服务,会话身份为 wsl:[用户@]发行版;桌面端的 remoteHost 在 SSH 连接与 WSL 发行版之间二选一,步骤、文件夹选择、信任、工作区和重连共用同一流程。remote.listWslDistributions 在 Windows 以外直接返回不可用,不运行任何程序。" + "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。读取在窗口的后台任务里进行,只在窗口打开且被绘制过时排下一次,不做空闲轮询。 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 的默认值,所以保存了其他值时也能显示自动值。" }