diff --git a/.agents/notes/implemented/feature/2026-11-21-remote-connections-window.md b/.agents/notes/implemented/feature/2026-11-21-remote-connections-window.md new file mode 100644 index 000000000..e1301a219 --- /dev/null +++ b/.agents/notes/implemented/feature/2026-11-21-remote-connections-window.md @@ -0,0 +1,64 @@ +# Agent 笔记:远程开发连接窗口——已保存的连接与测试连接 + +状态:已实现 + +## 先说结论 + +欢迎页“更多”菜单和标题栏项目菜单里的“远程开发”会打开一个窗口:左边是保存的 SSH 连接,右边是选中连接的表单、“测试连接”和测试到的主机信息。连接列表由 Rust Core 定义格式和规则(`remote.connections`、`remote.editConnections`),桌面端只负责读文件、把 Core 生成的整份文档原子写回。窗口里不保存任何秘密:密码、私钥口令和主机指纹确认都由 OpenSSH 在测试时经 AskPass(Lithe 自己充当 `SSH_ASKPASS` 程序,把问题转回主程序)提出,和 Git 认证共用同一个提问框,答完即丢。 + +## 问题 + +Issue #2231 要求远程开发先能“告诉 Lithe 连哪台机器、怎么登录”,并在打开项目前确认这台机器能用。旧客户端做过一版(见已归档的 `archived/feature/2026-10-24-remote-ssh-connections.md`),但它把密码记进钥匙串、把整张列表当工作副本编辑,而且字段规则写在 Swift 里。Viva 桌面端重新实现时要解决: + +- 字段规则(主机不能带 `user@`、端口范围、名称去重、最多 128 项)放在哪里,换 UI 壳子时不用重写; +- 保存时如果文件已被另一个窗口或手工改过,不能把别人的修改覆盖掉; +- 设计 S12 规定秘密只出现在 AskPass 的问题和答案里,S15 规定 Lithe 不读私钥内容。 + +## 决策 + +### 连接规则在 Core,文件读写在桌面端 + +- 字段的规范化、逐字段检查和文档格式都在 Core 的 `lithe_remote::client::connections`。Core 拒绝时返回 `{ field, reason }`,窗口把原因显示在对应字段下面,不弹通用错误框。 +- `desktop/internal/remoteconn` 只做两件事:按 Core 给出的相对路径和大小上限,从平台偏好目录读取 `remote/connections.json`;把 Core 编辑后返回的整份文档,以“读取时的字节”为前提原子写回(`configfile`)。文件在读取之后被改过,写入就失败(`ErrConflict`),窗口提示重新读取,不会覆盖。 +- 每次点“保存”或确认“删除”都立即写一次,并且写完重新读取文件来显示,不维护一份和磁盘不同的工作副本。打开窗口只读不写,没有文件时不会创建。 + +### 秘密不经过窗口 + +- 表单只有“认证方式”和私钥路径,没有密码框。私钥只保存路径,Lithe 不打开、不读取私钥文件,也不接受粘贴的私钥。 +- “测试连接”调用 Core 的 `RemoteProbe`,Core 运行 PATH 里的 OpenSSH。OpenSSH 的每个问题(密码、口令、验证码、首次连接时的主机指纹确认)通过 AskPass 回到窗口,进入和 Git 认证相同的队列(`gitAuthState`),问题带 `Remote` 标记,只换标题、提示和回答用的 Core 方法(`RemoteAuthRespond`)。 +- 取消提问、点“停止”或关闭窗口都会取消测试;被取消的测试不再追问,也不显示结果。 + +### 日志只记动作 + +窗口只记录 `remote.connections.open`、`remote.connection.new/select/save/remove/test/test.stop` 和 `remote.authentication.answer/retry/cancel` 等动作,以及 Core 的固定状态或错误码。主机、用户名、私钥路径、OpenSSH 输出、提问原文和答案都不进日志,`remote_test.go` 用 `loggedAny` 检查。 + +### 列表选中行跟着表单走 + +Viva 的 `ListState.Select` 只能选到列表上一帧已经声明过的行。保存一个新连接后,表单立刻编辑它,但列表这一帧还不认识新行,选中会被截到旧的最后一行。因此:行高亮直接按“表单正在编辑的连接”画;列表声明完行之后,再调用 `syncListSelection` 把键盘选中行同步过去。这是 Viva 的既定行为,不是缺陷,不在 Viva 侧改。 + +## 考虑过的备选方案 + +- **桌面端自己校验字段、自己定义 JSON 格式**:Go 里写一遍,将来换 UI 壳子还要再写一遍,和“通用逻辑进 Rust Core”的约定冲突。没有采用。 +- **沿用旧客户端的“记住到钥匙串”**:用户少输一次密码,但秘密会离开 AskPass 的问答,违反 S12;而且记错的密码会被重复发送。没有采用。 +- **把整张列表当工作副本编辑,关窗口时统一保存**:可以批量修改,但关窗口时要么丢修改,要么要再问一次;和“保存后重新读取显示真实来源”的设置规则也不一致。没有采用。 +- **为远程连接单独做一个认证弹窗**:两个弹窗可能同时出现、互相遮挡。共用 Git 的队列后,同一时间只显示一个问题,按提出顺序逐个回答。 + +## 后果 + +- 收益:字段规则只有 Core 一份;Windows 和 macOS 用同一份 Go 代码;秘密只在 OpenSSH 和 AskPass 之间流动;并发修改不会互相覆盖。 +- 代价:每次保存都是一次完整的读、改、写和重新读取;Core 没有返回字段的错误只能显示在窗口底部。 +- Windows 上 OpenSSH 能否通过 GUI 子系统的 `lithe` 助手读到答案仍待实机验证;打开远程项目、文件夹选择和远端服务部署在后续阶段实现。 + +## 验证 + +- `desktop/internal/remoteconn/remoteconn_test.go`:读取不创建文件、冲突时不写入、损坏文件报 `ErrDamaged`。 +- `desktop/internal/workbench/remote_test.go`:保存、改名、删除前确认;字段被拒绝时显示在字段下且不写文件;新保存的连接是列表选中行;测试时在窗口中回答密码并显示主机信息;停止和关窗口都会取消测试且不再追问;日志不含主机和用户名。 +- `desktop/internal/workbench/remote_connections_visual_test.go` 生成 `docs/assets/remote-connections/` 下的截图。 + +```bash +scripts/desktop/desktop-go.sh test ./internal/remoteconn ./internal/workbench -run 'Remote|GitAuth' -count=1 +``` + +## 适用范围 + +`desktop/internal/remoteconn/`、`desktop/internal/workbench/remote.go`、`desktop/internal/workbench/remote_view.go`,以及 `desktop/internal/workbench/git_auth.go` 中带 `Remote` 标记的提问。后续“打开远程工作区”“记住最近文件夹”都要通过同一个 `remoteconn` 和 Core 的 `remote.editConnections`,不要另存一份连接信息。 diff --git a/desktop/internal/core/gitauth.go b/desktop/internal/core/gitauth.go index f6f543a53..484953d28 100644 --- a/desktop/internal/core/gitauth.go +++ b/desktop/internal/core/gitauth.go @@ -33,6 +33,9 @@ type GitAuthChallenge struct { Attempt int // WorkingDirectory is the directory the Git process runs in. WorkingDirectory string + // Remote says the question comes from the SSH client of a remote connection (RemoteProbe), + // not from Git: it is answered with RemoteAuthRespond. + Remote bool // Done is closed once the request that asked has returned; no answer reaches it after that. Done <-chan struct{} } diff --git a/desktop/internal/core/remote.go b/desktop/internal/core/remote.go new file mode 100644 index 000000000..2b63233b1 --- /dev/null +++ b/desktop/internal/core/remote.go @@ -0,0 +1,249 @@ +package core + +import ( + "context" + "encoding/json" + "errors" +) + +// Remote development connections: the SSH connections the user saved, and the probe that checks +// one reaches a Linux host a remote server build exists for. Core validates every entry, picks +// ids and applies one edit at a time against a machine-local document the host keeps in its +// preference directory; it never stores a secret (design S08–S10, S12, S15). Questions OpenSSH +// asks during a probe (passwords, key passphrases, one-time codes, unknown host keys) reach the +// host as authentication challenges, like Git's. + +// Authentication modes of an SSHConnection. The empty mode is RemoteAuthenticationAuto. +const ( + // RemoteAuthenticationAuto lets OpenSSH and the user's ~/.ssh/config choose. + RemoteAuthenticationAuto = "auto" + // RemoteAuthenticationAgent uses only the keys of the running SSH agent. + RemoteAuthenticationAgent = "agent" + // RemoteAuthenticationPrivateKey uses only IdentityFile; Lithe passes its path to OpenSSH and + // never reads the key. + RemoteAuthenticationPrivateKey = "privateKey" + // RemoteAuthenticationPassword asks for a password or one-time code during the connection. + RemoteAuthenticationPassword = "password" +) + +// SSHConnection is how OpenSSH reaches a host. Empty and zero fields are left to OpenSSH and the +// user's ~/.ssh/config, so Host may be an alias defined there. +type SSHConnection struct { + // Host is a host name, an address or a ~/.ssh/config alias, without a user or a port. + Host string `json:"host"` + // Port is the SSH port; 0 leaves it to OpenSSH. + Port uint16 `json:"port,omitempty"` + // User is the login name; empty leaves it to OpenSSH. + User string `json:"user,omitempty"` + // Authentication is one of the RemoteAuthentication modes; empty is RemoteAuthenticationAuto. + Authentication string `json:"authentication,omitempty"` + // IdentityFile is the private key path, required by RemoteAuthenticationPrivateKey and + // dropped by Core in every other mode. + IdentityFile string `json:"identityFile,omitempty"` + // ProxyJump is OpenSSH's jump host list, for example "bastion" or "user@a,user@b:2222". + ProxyJump string `json:"proxyJump,omitempty"` + // ConnectTimeoutSeconds bounds the TCP connection, 1 to 600; 0 is Core's default of 15. + ConnectTimeoutSeconds uint32 `json:"connectTimeoutSeconds,omitempty"` + // KeepAliveSeconds sends a keep-alive this often, 1 to 3600; 0 sends none. + KeepAliveSeconds uint32 `json:"keepAliveSeconds,omitempty"` +} + +// SavedRemoteConnection is one entry of the saved connections. +type SavedRemoteConnection struct { + // ID is Core's stable identifier of the entry. + ID string `json:"id"` + // Name is the user's label. + Name string `json:"name"` + // Connection is how to reach the host. + Connection SSHConnection `json:"connection"` + // RecentFolders are the host folders opened over the entry, the latest first. + RecentFolders []string `json:"recentFolders,omitempty"` +} + +// RemoteConnectionsStorage says where the host keeps the document: RelativePath inside the +// platform preference directory, at most MaximumBytes long. +type RemoteConnectionsStorage struct { + RelativePath string `json:"relativePath"` + MaximumBytes int64 `json:"maximumBytes"` +} + +// RemoteConnectionsState is the document as Core reads it. +type RemoteConnectionsState struct { + Connections []SavedRemoteConnection `json:"connections"` + Storage RemoteConnectionsStorage `json:"storage"` +} + +// RemoteConnectionSave adds a connection, or replaces the entry ID when ID is set. +type RemoteConnectionSave struct { + ID string `json:"id,omitempty"` + Name string `json:"name"` + Connection SSHConnection `json:"connection"` +} + +// RemoteConnectionID names an entry to remove. +type RemoteConnectionID struct { + ID string `json:"id"` +} + +// RemoteConnectionFolder records a host folder opened over the entry ID. +type RemoteConnectionFolder struct { + ID string `json:"id"` + Path string `json:"path"` +} + +// RemoteConnectionEdit is exactly one of Save, Remove and RememberFolder. +type RemoteConnectionEdit struct { + Save *RemoteConnectionSave `json:"save,omitempty"` + Remove *RemoteConnectionID `json:"remove,omitempty"` + RememberFolder *RemoteConnectionFolder `json:"rememberFolder,omitempty"` +} + +// RemoteConnectionsPublication is the outcome of an edit. Document is the text to publish, nil +// when the edit changed nothing; ID names the entry a save wrote. +type RemoteConnectionsPublication struct { + Changed bool `json:"changed"` + Document *string `json:"document"` + Connections []SavedRemoteConnection `json:"connections"` + ID string `json:"id"` +} + +// RemoteConnections reads the saved connections from document, the text of the source or nil +// when it does not exist. A document Core cannot decode fails with CodeParseFailed, with the +// field and the reason in RemoteConnectionFieldError. +func (c *Client) RemoteConnections(ctx context.Context, document *string) (RemoteConnectionsState, error) { + var state RemoteConnectionsState + err := c.Execute(ctx, "remote.connections", struct { + Document *string `json:"document"` + }{document}, &state) + return state, err +} + +// EditRemoteConnections applies edit to document. A refused entry fails with CodeInvalidRequest, +// with the field and the reason in RemoteConnectionFieldError. +func (c *Client) EditRemoteConnections(ctx context.Context, document *string, edit RemoteConnectionEdit) (RemoteConnectionsPublication, error) { + var publication RemoteConnectionsPublication + err := c.Execute(ctx, "remote.editConnections", struct { + Document *string `json:"document"` + RemoteConnectionEdit + }{document, edit}, &publication) + return publication, err +} + +// RemoteConnectionFieldError reads the field and the reason Core named when it refused a +// connection or a document: field is a JSON name such as "host" or "connectTimeoutSeconds", and +// reason one of "required", "invalid", "tooLong", "duplicate", "full" and "unknown". +func RemoteConnectionFieldError(err error) (field, reason string, ok bool) { + var coreErr *Error + if !errors.As(err, &coreErr) || coreErr.Details == "" { + return "", "", false + } + if coreErr.Code != CodeInvalidRequest && coreErr.Code != CodeParseFailed { + return "", "", false + } + var details struct { + Field string `json:"field"` + Reason string `json:"reason"` + } + if json.Unmarshal([]byte(coreErr.Details), &details) != nil || details.Field == "" || details.Reason == "" { + return "", "", false + } + return details.Field, details.Reason, true +} + +// RemoteProbeStatus is the outcome of a probe. A host that cannot be reached is an outcome, not +// an error. +type RemoteProbeStatus string + +const ( + // RemoteProbeConnected means a shell ran on the host and a server build exists for it. + RemoteProbeConnected RemoteProbeStatus = "connected" + // RemoteProbeUnsupportedPlatform means the host answered, but no server build exists for it. + RemoteProbeUnsupportedPlatform RemoteProbeStatus = "unsupportedPlatform" + // RemoteProbeAuthenticationFailed means the server rejected every offered credential. + RemoteProbeAuthenticationFailed RemoteProbeStatus = "authenticationFailed" + // RemoteProbeHostKeyRejected means the host key is unknown and was declined, or changed. + RemoteProbeHostKeyRejected RemoteProbeStatus = "hostKeyRejected" + // RemoteProbeUnreachable means the name did not resolve or the host did not answer in time. + RemoteProbeUnreachable RemoteProbeStatus = "unreachable" + // RemoteProbeFailed means the connection failed for another reason; see Diagnostics. + RemoteProbeFailed RemoteProbeStatus = "failed" +) + +// RemoteHostDetails are facts about a probed host for display; each is empty or zero when the +// host did not report it. +type RemoteHostDetails struct { + HostName string `json:"hostName"` + OperatingSystem string `json:"operatingSystem"` + Kernel string `json:"kernel"` + CPUCount uint32 `json:"cpuCount"` + MemoryBytes uint64 `json:"memoryBytes"` + DiskTotalBytes uint64 `json:"diskTotalBytes"` + DiskAvailableBytes uint64 `json:"diskAvailableBytes"` + UptimeSeconds uint64 `json:"uptimeSeconds"` +} + +// RemoteProbedHost is what the host's shell reported. +type RemoteProbedHost struct { + // System is `uname -s`, for example "Linux". + System string `json:"system"` + // Machine is `uname -m`, for example "x86_64" or "aarch64". + Machine string `json:"machine"` + // HomeDirectory is the login's home directory, empty when unknown. + HomeDirectory string `json:"homeDirectory"` + // ServerTarget is the Rust target of the server build for the host, empty when none exists. + ServerTarget string `json:"serverTarget"` + // Details are facts for display. + Details RemoteHostDetails `json:"details"` +} + +// RemoteProbeResult is the outcome of a probe, and the host when its shell ran. +type RemoteProbeResult struct { + Status RemoteProbeStatus `json:"status"` + Host *RemoteProbedHost `json:"host"` + // Diagnostics is the redacted end of OpenSSH's standard error. It is upstream text, shown + // as it is, and may still name the host, so it is never logged. + Diagnostics string `json:"diagnostics"` +} + +// RemoteProbe connects to the host of connection with the system OpenSSH client and reports its +// platform. Each question OpenSSH asks reaches the prompt WithGitAuthentication put in ctx as a +// 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) { + prompt, _ := ctx.Value(gitAuthenticationKey{}).(func(GitAuthChallenge)) + if prompt == nil { + prompt = func(challenge GitAuthChallenge) { + // The answer must not wait on the request's goroutine, which delivers the event. + go func() { _, _ = c.RemoteAuthRespond(context.Background(), challenge.RequestID, nil) }() + } + } + returned := make(chan struct{}) + defer close(returned) + observer := gitAuthenticationObserver(func(challenge GitAuthChallenge) { + challenge.Remote = true + prompt(challenge) + }, returned, nil) + var result RemoteProbeResult + observationErr, err := c.ExecuteWithEvents(ctx, "remote.probe", struct { + Connection SSHConnection `json:"connection"` + }{connection}, &result, observer) + if err != nil { + return RemoteProbeResult{}, err + } + if observationErr != nil { + return RemoteProbeResult{}, observationErr + } + return result, nil +} + +// RemoteAuthRespond answers the Remote challenge requestID with the text the user typed, or nil +// to cancel. accepted is false when the challenge no longer waits. The answer is never logged. +// Core answers at once, so the call may run on any goroutine, but not on the UI thread. +func (c *Client) RemoteAuthRespond(ctx context.Context, requestID string, answer *string) (accepted bool, err error) { + var result struct { + Accepted bool `json:"accepted"` + } + err = c.Execute(ctx, "remote.authRespond", gitAuthReply{RequestID: requestID, Answer: answer}, &result) + return result.Accepted, err +} diff --git a/desktop/internal/core/remote_test.go b/desktop/internal/core/remote_test.go new file mode 100644 index 000000000..5cd78ace2 --- /dev/null +++ b/desktop/internal/core/remote_test.go @@ -0,0 +1,164 @@ +package core + +import ( + "errors" + "os" + "path/filepath" + "runtime" + "strings" + "sync" + "testing" +) + +// standInSSH puts an ssh on PATH that ignores its options and, after asking for a password +// through the AskPass helper Core names, runs the remote command with the local shell. A wrong +// or cancelled answer fails like a server rejecting it. +func standInSSH(t *testing.T) { + t.Helper() + if runtime.GOOS == "windows" { + t.Skip("the stand-in SSH client is a POSIX shell script") + } + dir := t.TempDir() + script := `#!/bin/sh +for last; do :; done +answer=$("$SSH_ASKPASS" "dev@devbox's password: ") || answer= +if [ "$answer" != "s3cret" ]; then + echo 'dev@devbox: Permission denied (password).' >&2 + exit 255 +fi +exec /bin/sh -c "$last" +` + if err := os.WriteFile(filepath.Join(dir, "ssh"), []byte(script), 0o755); err != nil { + t.Fatal(err) + } + t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH")) +} + +// A probe relays OpenSSH's password question as a Remote challenge, sends the answer, and reports +// the platform the host's shell printed. +func TestRemoteProbeAsksThroughTheHostAndReportsThePlatform(t *testing.T) { + standInSSH(t) + client := NewClient() + var mu sync.Mutex + var challenges []GitAuthChallenge + var replies sync.WaitGroup + prompt := func(challenge GitAuthChallenge) { + mu.Lock() + challenges = append(challenges, challenge) + mu.Unlock() + replies.Add(1) + go func() { + defer replies.Done() + accepted, err := client.RemoteAuthRespond(testContext(t), challenge.RequestID, answerText("s3cret")) + if err != nil || !accepted { + t.Errorf("answer: accepted = %v, err = %v", accepted, err) + } + }() + } + var result RemoteProbeResult + var err error + finishesWithin(t, "probe", testDeadline, func() { + result, err = client.RemoteProbe(WithGitAuthentication(testContext(t), prompt), SSHConnection{Host: "devbox", User: "dev"}) + }) + finishesWithin(t, "answers", testDeadline, replies.Wait) + if err != nil { + t.Fatalf("probe: %v", err) + } + mu.Lock() + defer mu.Unlock() + if len(challenges) != 1 { + t.Fatalf("challenges = %+v, want the one password question", challenges) + } + asked := challenges[0] + if !asked.Remote || asked.Retry || !asked.Secret || !strings.Contains(asked.Prompt, "password") || asked.Attempt != 1 { + t.Fatalf("question = %+v, want OpenSSH's secret password question from a remote connection", asked) + } + select { + case <-asked.Done: + default: + t.Fatal("the question is still open after the probe returned") + } + if result.Host == nil || result.Host.System == "" || result.Host.Machine == "" || !filepath.IsAbs(result.Host.HomeDirectory) { + t.Fatalf("host = %+v, want the shell's platform report", result.Host) + } + // The local machine is the host here, so whether a server build exists depends on it. + want := RemoteProbeUnsupportedPlatform + if result.Host.ServerTarget != "" { + want = RemoteProbeConnected + } + if result.Status != want || result.Host.Details.CPUCount == 0 { + t.Fatalf("result = %+v, want %s with details", result, want) + } +} + +// Without a prompt in the context each question is cancelled at once, so the probe ends with the +// server's refusal instead of waiting for Core's prompt deadline. +func TestRemoteProbeWithoutAPromptCancelsEachQuestion(t *testing.T) { + standInSSH(t) + var result RemoteProbeResult + var err error + finishesWithin(t, "probe", testDeadline, func() { + result, err = NewClient().RemoteProbe(testContext(t), SSHConnection{Host: "devbox", User: "dev"}) + }) + if err != nil { + t.Fatalf("probe: %v", err) + } + if result.Status != RemoteProbeAuthenticationFailed || result.Host != nil || !strings.Contains(result.Diagnostics, "Permission denied") { + t.Fatalf("result = %+v, want the authentication failure", result) + } +} + +// The saved connections round-trip through the document Core returns, an edit that changes +// nothing returns no document, and a refused entry or document names the field and the reason. +func TestRemoteConnectionsRoundTripAndNameRefusedFields(t *testing.T) { + client := NewClient() + ctx := testContext(t) + plan, err := client.RemoteConnections(ctx, nil) + if err != nil || len(plan.Connections) != 0 || plan.Storage.RelativePath != "remote/connections.json" || plan.Storage.MaximumBytes <= 0 { + t.Fatalf("plan = %+v, err = %v", plan, err) + } + saved, err := client.EditRemoteConnections(ctx, nil, RemoteConnectionEdit{Save: &RemoteConnectionSave{ + Name: "Build box", + Connection: SSHConnection{ + Host: "build.example", + User: "dev", + Authentication: RemoteAuthenticationPrivateKey, + IdentityFile: "~/.ssh/id_ed25519", + }, + }}) + if err != nil || !saved.Changed || saved.Document == nil || saved.ID == "" { + t.Fatalf("save = %+v, err = %v", saved, err) + } + listed, err := client.RemoteConnections(ctx, saved.Document) + if err != nil || len(listed.Connections) != 1 { + t.Fatalf("listed = %+v, err = %v", listed, err) + } + entry := listed.Connections[0] + if entry.ID != saved.ID || entry.Name != "Build box" || entry.Connection.IdentityFile != "~/.ssh/id_ed25519" { + t.Fatalf("entry = %+v", entry) + } + unchanged, err := client.EditRemoteConnections(ctx, saved.Document, RemoteConnectionEdit{Remove: &RemoteConnectionID{ID: "absent"}}) + if err != nil || unchanged.Changed || unchanged.Document != nil || len(unchanged.Connections) != 1 { + t.Fatalf("no-op = %+v, err = %v", unchanged, err) + } + + _, err = client.EditRemoteConnections(ctx, nil, RemoteConnectionEdit{Save: &RemoteConnectionSave{ + Name: "Box", + Connection: SSHConnection{Host: "dev@box"}, + }}) + if field, reason, ok := RemoteConnectionFieldError(err); !ok || field != "host" || reason != "invalid" { + t.Fatalf("host with a user: %v (%q, %q, %v)", err, field, reason, ok) + } + damaged := `{"version":2,"connections":[]}` + _, err = client.RemoteConnections(ctx, &damaged) + var coreErr *Error + if !errors.As(err, &coreErr) || coreErr.Code != CodeParseFailed { + t.Fatalf("damaged document: %v, want a parse failure", err) + } + if field, reason, ok := RemoteConnectionFieldError(err); !ok || field != "version" || reason != "invalid" { + t.Fatalf("damaged document: (%q, %q, %v)", field, reason, ok) + } + if _, _, ok := RemoteConnectionFieldError(&Error{Code: CodeUnknown, Details: `{"field":"host","reason":"invalid"}`}); ok { + t.Fatal("an unrelated error named a field") + } +} diff --git a/desktop/internal/i18n/shared.generated.go b/desktop/internal/i18n/shared.generated.go index 5036b9e01..b77efa6f2 100644 --- a/desktop/internal/i18n/shared.generated.go +++ b/desktop/internal/i18n/shared.generated.go @@ -1570,6 +1570,90 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.refs.rebased": "Rebased the current branch onto {branch}", "desktop.refs.trackingSet": "{branch} now tracks {upstream}", "desktop.refs.trackingStopped": "{branch} no longer tracks a remote branch", + "desktop.remote.advanced": "Advanced", + "desktop.remote.auth.agent": "SSH agent", + "desktop.remote.auth.auto": "Auto", + "desktop.remote.auth.password": "Password", + "desktop.remote.auth.privateKey": "Private key file", + "desktop.remote.authentication": "Authentication", + "desktop.remote.authenticationHelp": "Auto: as your SSH config and ssh-agent decide. SSH agent: only keys held by ssh-agent. Private key: only the key file you choose; its passphrase is asked when connecting. Password: asked when connecting. Lithe never saves an answer.", + "desktop.remote.cancel": "Cancel", + "desktop.remote.choose": "Choose File…", + "desktop.remote.chooseFailed": "Cannot open the file picker: {reason}", + "desktop.remote.close": "Close", + "desktop.remote.conflict": "The saved connections changed elsewhere and were read again. Save once more.", + "desktop.remote.damaged": "The saved connections in {path} cannot be read. Repair or remove the file before saving.", + "desktop.remote.delete": "Delete", + "desktop.remote.deleteConfirm": "Delete “{name}”?", + "desktop.remote.deleteFailed": "Cannot delete the connection: {reason}", + "desktop.remote.diagnostics": "OpenSSH Output", + "desktop.remote.empty": "No saved connections yet. Fill in the form and save it.", + "desktop.remote.error.duplicate": "Another saved connection already uses this.", + "desktop.remote.error.fieldTooLong": "Too long: at most 1024 bytes.", + "desktop.remote.error.full": "At most 128 connections can be saved. Delete one first.", + "desktop.remote.error.hostInvalid": "Enter only a host name, an IP address or an SSH alias; put the user and the port in their own fields.", + "desktop.remote.error.invalid": "This value is not accepted.", + "desktop.remote.error.keepAliveInvalid": "Enter 1 to 3600 seconds.", + "desktop.remote.error.nameDuplicate": "Another saved connection already has this name.", + "desktop.remote.error.nameTooLong": "Too long: at most 128 characters.", + "desktop.remote.error.portInvalid": "Enter a port from 1 to 65535.", + "desktop.remote.error.proxyJumpInvalid": "Use [user@]host[:port], several separated by commas.", + "desktop.remote.error.required": "Required.", + "desktop.remote.error.textInvalid": "Remove the spaces at either end and any control characters.", + "desktop.remote.error.timeoutInvalid": "Enter 1 to 600 seconds.", + "desktop.remote.error.unknown": "This connection no longer exists.", + "desktop.remote.error.userInvalid": "This user name has characters SSH does not accept.", + "desktop.remote.host": "Host", + "desktop.remote.hostHelp": "A host name, an IP address, or a Host alias from ~/.ssh/config. OpenSSH applies its configuration as usual: a field left empty here does not override it.", + "desktop.remote.hostPlaceholder": "build.example.com or an SSH config alias", + "desktop.remote.identityFile": "Private Key", + "desktop.remote.identityFileHelp": "Only the path is saved and handed to OpenSSH; Lithe never reads the key.", + "desktop.remote.identityFilePlaceholder": "~/.ssh/id_ed25519", + "desktop.remote.keepAlive": "Keep-Alive (s)", + "desktop.remote.keepAliveHelp": "How often OpenSSH checks that the server still answers (ServerAliveInterval), so a dropped network is noticed.", + "desktop.remote.keepAlivePlaceholder": "Auto (SSH config)", + "desktop.remote.menuItem": "Remote Development…", + "desktop.remote.name": "Name", + "desktop.remote.namePlaceholder": "Defaults to the host", + "desktop.remote.new": "New Connection", + "desktop.remote.port": "Port", + "desktop.remote.portPlaceholder": "Auto (SSH config, otherwise 22)", + "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", + "desktop.remote.probe.disk": "Disk (home)", + "desktop.remote.probe.diskSpace": "{available} free of {total}", + "desktop.remote.probe.error": "Cannot test the connection: {reason}", + "desktop.remote.probe.failed": "The connection failed.", + "desktop.remote.probe.hostKeyRejected": "The host key was not accepted: it was declined, or it differs from the one in known_hosts.", + "desktop.remote.probe.hostName": "Host name", + "desktop.remote.probe.memory": "Memory", + "desktop.remote.probe.noSSH": "No ssh client found. Install the OpenSSH client first.", + "desktop.remote.probe.os": "System", + "desktop.remote.probe.unreachable": "Cannot reach the host: check the host, the port and the network.", + "desktop.remote.probe.unsupported": "Connected to {system} {machine}, but Lithe’s remote server does not run there yet: only x86_64 and arm64 Linux are supported.", + "desktop.remote.proxyJump": "Proxy Jump", + "desktop.remote.proxyJumpHelp": "Hosts to connect through first, as OpenSSH ProxyJump: [user@]host[:port], several separated by commas.", + "desktop.remote.proxyJumpPlaceholder": "None (or SSH config)", + "desktop.remote.readFailed": "Cannot read the saved connections: {reason}", + "desktop.remote.save": "Save", + "desktop.remote.saveFailed": "Cannot save the connection: {reason}", + "desktop.remote.saved": "Saved Connections", + "desktop.remote.saving": "Saving…", + "desktop.remote.stop": "Stop", + "desktop.remote.storageHelp": "Kept on this computer in {path}. Passwords and the contents of private keys are never saved.", + "desktop.remote.test": "Test Connection", + "desktop.remote.testing": "Connecting… OpenSSH may ask for a password or to confirm the host key.", + "desktop.remote.timeout": "Connect Timeout (s)", + "desktop.remote.timeoutPlaceholder": "Auto (15)", + "desktop.remote.title": "Remote Development", + "desktop.remote.unavailable": "There is no preference folder to keep connections in.", + "desktop.remote.user": "User", + "desktop.remote.userPlaceholder": "Auto (SSH config, otherwise your local user name)", + "desktop.remoteAuth.failed": "Cannot pass the answer to SSH: {reason}", + "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.run.closeSession": "Close", "desktop.run.durationHours": "{hours} h {minutes} min", "desktop.run.durationMilliseconds": "{milliseconds} ms", @@ -4899,6 +4983,90 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.refs.rebased": "已把当前分支变基到 {branch}", "desktop.refs.trackingSet": "{branch} 现在跟踪 {upstream}", "desktop.refs.trackingStopped": "{branch} 不再跟踪远程分支", + "desktop.remote.advanced": "高级", + "desktop.remote.auth.agent": "SSH Agent", + "desktop.remote.auth.auto": "自动", + "desktop.remote.auth.password": "密码", + "desktop.remote.auth.privateKey": "私钥文件", + "desktop.remote.authentication": "身份验证", + "desktop.remote.authenticationHelp": "自动:按 SSH 配置和 ssh-agent 决定。SSH Agent:只用 ssh-agent 里的密钥。私钥文件:只用选定的私钥,口令在连接时询问。密码:在连接时询问。Lithe 不保存任何回答。", + "desktop.remote.cancel": "取消", + "desktop.remote.choose": "选择文件…", + "desktop.remote.chooseFailed": "无法打开文件选择器:{reason}", + "desktop.remote.close": "关闭", + "desktop.remote.conflict": "已保存的连接在别处被修改过,已重新读取,请再保存一次。", + "desktop.remote.damaged": "无法读取 {path} 里保存的连接。修复或删除这个文件之前不能保存。", + "desktop.remote.delete": "删除", + "desktop.remote.deleteConfirm": "删除“{name}”?", + "desktop.remote.deleteFailed": "无法删除连接:{reason}", + "desktop.remote.diagnostics": "OpenSSH 输出", + "desktop.remote.empty": "还没有保存的连接。填写右侧表单后保存。", + "desktop.remote.error.duplicate": "另一个已保存的连接已在使用这个值。", + "desktop.remote.error.fieldTooLong": "太长:最多 1024 字节。", + "desktop.remote.error.full": "最多保存 128 个连接,请先删除一个。", + "desktop.remote.error.hostInvalid": "只填主机名、IP 地址或 SSH 别名;用户名和端口请填到各自的字段。", + "desktop.remote.error.invalid": "这个值不被接受。", + "desktop.remote.error.keepAliveInvalid": "请填 1 到 3600 秒。", + "desktop.remote.error.nameDuplicate": "已有同名的连接(不区分大小写)。", + "desktop.remote.error.nameTooLong": "太长:最多 128 个字符。", + "desktop.remote.error.portInvalid": "请填 1 到 65535 之间的端口。", + "desktop.remote.error.proxyJumpInvalid": "格式为 [用户@]主机[:端口],多个用逗号分隔。", + "desktop.remote.error.required": "必填。", + "desktop.remote.error.textInvalid": "请去掉首尾空格和控制字符。", + "desktop.remote.error.timeoutInvalid": "请填 1 到 600 秒。", + "desktop.remote.error.unknown": "这个连接已不存在。", + "desktop.remote.error.userInvalid": "用户名含有 SSH 不接受的字符。", + "desktop.remote.host": "主机", + "desktop.remote.hostHelp": "主机名、IP 地址或 ~/.ssh/config 里的 Host 别名。OpenSSH 照常读取它的配置;这里留空的字段不会覆盖配置里的值。", + "desktop.remote.hostPlaceholder": "build.example.com 或 SSH 配置里的别名", + "desktop.remote.identityFile": "私钥", + "desktop.remote.identityFileHelp": "只保存路径并交给 OpenSSH;Lithe 不读取私钥内容。", + "desktop.remote.identityFilePlaceholder": "~/.ssh/id_ed25519", + "desktop.remote.keepAlive": "保活间隔(秒)", + "desktop.remote.keepAliveHelp": "OpenSSH 每隔多久确认一次服务器仍有响应(ServerAliveInterval),以便发现网络已断开。", + "desktop.remote.keepAlivePlaceholder": "自动(SSH 配置)", + "desktop.remote.menuItem": "远程开发…", + "desktop.remote.name": "名称", + "desktop.remote.namePlaceholder": "默认使用主机名", + "desktop.remote.new": "新建连接", + "desktop.remote.port": "端口", + "desktop.remote.portPlaceholder": "自动(SSH 配置,否则 22)", + "desktop.remote.probe.authenticationFailed": "身份验证失败:服务器没有接受提供的密钥或密码。", + "desktop.remote.probe.connected": "已连接:{system} {machine}", + "desktop.remote.probe.cpu": "CPU 数", + "desktop.remote.probe.disk": "磁盘(主目录)", + "desktop.remote.probe.diskSpace": "可用 {available},共 {total}", + "desktop.remote.probe.error": "无法测试连接:{reason}", + "desktop.remote.probe.failed": "连接失败。", + "desktop.remote.probe.hostKeyRejected": "主机密钥没有通过验证:你拒绝了它,或者它与 known_hosts 里记录的不一致。", + "desktop.remote.probe.hostName": "主机名", + "desktop.remote.probe.memory": "内存", + "desktop.remote.probe.noSSH": "找不到 ssh 客户端,请先安装 OpenSSH 客户端。", + "desktop.remote.probe.os": "系统", + "desktop.remote.probe.unreachable": "无法连接到主机:请检查主机、端口和网络。", + "desktop.remote.probe.unsupported": "已连接到 {system} {machine},但 Lithe 远程服务目前不支持该平台:只支持 x86_64 和 arm64 的 Linux。", + "desktop.remote.proxyJump": "跳板机", + "desktop.remote.proxyJumpHelp": "先经过这些主机再连接,等同 OpenSSH 的 ProxyJump:[用户@]主机[:端口],多个用逗号分隔。", + "desktop.remote.proxyJumpPlaceholder": "无(或按 SSH 配置)", + "desktop.remote.readFailed": "无法读取已保存的连接:{reason}", + "desktop.remote.save": "保存", + "desktop.remote.saveFailed": "无法保存连接:{reason}", + "desktop.remote.saved": "已保存的连接", + "desktop.remote.saving": "正在保存…", + "desktop.remote.stop": "停止", + "desktop.remote.storageHelp": "保存在本机的 {path}。不会保存密码和私钥内容。", + "desktop.remote.test": "测试连接", + "desktop.remote.testing": "正在连接…OpenSSH 可能会询问密码或请你确认主机密钥。", + "desktop.remote.timeout": "连接超时(秒)", + "desktop.remote.timeoutPlaceholder": "自动(15)", + "desktop.remote.title": "远程开发", + "desktop.remote.unavailable": "没有可以保存连接的偏好设置目录。", + "desktop.remote.user": "用户名", + "desktop.remote.userPlaceholder": "自动(SSH 配置,否则本机用户名)", + "desktop.remoteAuth.failed": "无法把回答交给 SSH:{reason}", + "desktop.remoteAuth.refused": "SSH 没有接受这个回答:回答最多 8192 字节,且不能包含换行。这个问题已取消。", + "desktop.remoteAuth.secretHint": "回答只交给这次 SSH 连接,Lithe 不会保存。", + "desktop.remoteAuth.title": "SSH 身份验证", "desktop.run.closeSession": "关闭", "desktop.run.durationHours": "{hours}小时{minutes}分", "desktop.run.durationMilliseconds": "{milliseconds}毫秒", diff --git a/desktop/internal/remoteconn/remoteconn.go b/desktop/internal/remoteconn/remoteconn.go new file mode 100644 index 000000000..22199d7e0 --- /dev/null +++ b/desktop/internal/remoteconn/remoteconn.go @@ -0,0 +1,117 @@ +// Package remoteconn keeps the SSH connections the user saved for remote development. +// +// The list lives in /remote/connections.json, the path and the size limit Core +// names (remote.connections), inside the platform user preference directory (Application Support +// on macOS, LocalAppData on Windows). It is machine-local: it is never written to the app bundle, +// the installation directory, a plugin package or a workspace, so it does not affect code signing +// or Sparkle delta updates, and it is never copied across worktrees. It holds no secret: Core +// refuses entries that carry one, and private keys are kept as paths only (design S12, S15). +// Reading creates nothing; an edit publishes the whole document atomically against the bytes it +// was read from, and the caller reads the source again afterwards. +package remoteconn + +import ( + "context" + "errors" + + "github.com/1lck/Lithe-IDEA/desktop/internal/configfile" + "github.com/1lck/Lithe-IDEA/desktop/internal/core" +) + +// Kernel is the part of the Core client the saved connections use. +type Kernel interface { + RemoteConnections(ctx context.Context, document *string) (core.RemoteConnectionsState, error) + EditRemoteConnections(ctx context.Context, document *string, edit core.RemoteConnectionEdit) (core.RemoteConnectionsPublication, error) +} + +var ( + // ErrUnavailable means there is no preference directory to keep the list in. + ErrUnavailable = errors.New("remoteconn: no preference directory") + // ErrDamaged means Core cannot decode the stored list; nothing can be saved until the user + // repairs or removes the file at Source.Path. + ErrDamaged = errors.New("remoteconn: the saved connections cannot be read") + // ErrConflict means the file changed after it was read; nothing was written. + ErrConflict = errors.New("remoteconn: the saved connections changed on disk") +) + +// Source is the saved list with the bytes it was read from. +type Source struct { + // Connections are the saved entries in their stored order. + Connections []core.SavedRemoteConnection + root string + file configfile.Snapshot +} + +// Path is the file the list is kept in, for display. +func (s Source) Path() string { return s.file.Path() } + +// Read reads the list kept under root, the platform preference directory. A list Core cannot +// decode fails with ErrDamaged joined to Core's error; the returned Source still names its Path. +func Read(ctx context.Context, kernel Kernel, root string) (Source, error) { + if root == "" { + return Source{}, ErrUnavailable + } + plan, err := kernel.RemoteConnections(ctx, nil) + if err != nil { + return Source{}, err + } + file, err := configfile.Capture(ctx, root, plan.Storage.RelativePath, plan.Storage.MaximumBytes) + source := Source{root: root, file: file} + if errors.Is(err, configfile.ErrTooLarge) || errors.Is(err, configfile.ErrEncoding) { + return source, errors.Join(ErrDamaged, err) + } + if err != nil { + return Source{}, err + } + text, err := file.Text() + if err != nil { + return source, errors.Join(ErrDamaged, err) + } + state, err := kernel.RemoteConnections(ctx, text) + if err != nil { + var coreErr *core.Error + if errors.As(err, &coreErr) && coreErr.Code == core.CodeParseFailed { + return source, errors.Join(ErrDamaged, err) + } + return Source{}, err + } + source.Connections = state.Connections + return source, nil +} + +// Edit applies edit to the bytes s was read from, publishes the result and reads the list again. +// It returns the list as it is now and the id of the entry a save wrote. A refused entry fails +// with Core's error (core.RemoteConnectionFieldError names the field); a file changed since s was +// read fails with ErrConflict and writes nothing. committed reports that the new list reached the +// disk even when a later step failed. +func (s Source) Edit(ctx context.Context, kernel Kernel, edit core.RemoteConnectionEdit) (after Source, id string, committed bool, err error) { + if s.root == "" { + return s, "", false, ErrUnavailable + } + text, err := s.file.Text() + if err != nil { + return s, "", false, errors.Join(ErrDamaged, err) + } + publication, err := kernel.EditRemoteConnections(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 s, "", false, err + } + if publication.Changed { + if publication.Document == nil { + return s, "", false, errors.New("remoteconn: Core changed the list without a document") + } + committed, err = s.file.Replace(ctx, []byte(*publication.Document), func() error { return s.file.Verify(ctx) }) + if errors.Is(err, configfile.ErrConflict) { + err = errors.Join(ErrConflict, err) + } + if err != nil { + return s, "", committed, err + } + } + after, err = Read(ctx, kernel, s.root) + return after, publication.ID, committed, err +} diff --git a/desktop/internal/remoteconn/remoteconn_test.go b/desktop/internal/remoteconn/remoteconn_test.go new file mode 100644 index 000000000..878896391 --- /dev/null +++ b/desktop/internal/remoteconn/remoteconn_test.go @@ -0,0 +1,128 @@ +package remoteconn + +import ( + "context" + "errors" + "os" + "path/filepath" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" +) + +func testContext(t *testing.T) context.Context { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + t.Cleanup(cancel) + return ctx +} + +func save(name, host string) core.RemoteConnectionEdit { + return core.RemoteConnectionEdit{Save: &core.RemoteConnectionSave{Name: name, Connection: core.SSHConnection{Host: host}}} +} + +// Reading an absent list creates nothing; a save writes the document Core returned under the +// preference root and the list is read back from it. +func TestSavingWritesOnlyThePreferenceDocument(t *testing.T) { + ctx := testContext(t) + kernel := core.NewClient() + root := filepath.Join(t.TempDir(), "preferences") + source, err := Read(ctx, kernel, root) + if err != nil || len(source.Connections) != 0 { + t.Fatalf("read = %+v, err = %v", source, err) + } + if _, err := os.Stat(root); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("reading created %s: %v", root, err) + } + after, id, committed, err := source.Edit(ctx, kernel, save("Build box", "build.example")) + if err != nil || !committed || id == "" { + t.Fatalf("save: id = %q, committed = %v, err = %v", id, committed, err) + } + if len(after.Connections) != 1 || after.Connections[0].ID != id || after.Connections[0].Name != "Build box" { + t.Fatalf("after = %+v", after.Connections) + } + want := filepath.Join(root, "remote", "connections.json") + if after.Path() != want { + t.Fatalf("path = %q, want %q", after.Path(), want) + } + reread, err := Read(ctx, kernel, root) + if err != nil || len(reread.Connections) != 1 || reread.Connections[0].ID != id { + t.Fatalf("reread = %+v, err = %v", reread, err) + } + removed, _, committed, err := reread.Edit(ctx, kernel, core.RemoteConnectionEdit{Remove: &core.RemoteConnectionID{ID: id}}) + if err != nil || !committed || len(removed.Connections) != 0 { + t.Fatalf("remove: %+v, committed = %v, err = %v", removed.Connections, committed, err) + } +} + +// An edit against bytes that changed on disk writes nothing. +func TestEditingAChangedListIsAConflict(t *testing.T) { + ctx := testContext(t) + kernel := core.NewClient() + root := t.TempDir() + initial, err := Read(ctx, kernel, root) + if err != nil { + t.Fatal(err) + } + first, _, _, err := initial.Edit(ctx, kernel, save("A", "a.example")) + if err != nil { + t.Fatal(err) + } + stale, err := Read(ctx, kernel, root) + if err != nil { + t.Fatal(err) + } + if _, _, _, err := first.Edit(ctx, kernel, save("B", "b.example")); err != nil { + t.Fatal(err) + } + before, err := os.ReadFile(stale.Path()) + if err != nil { + t.Fatal(err) + } + _, _, committed, err := stale.Edit(ctx, kernel, save("C", "c.example")) + if !errors.Is(err, ErrConflict) || committed { + t.Fatalf("stale edit: committed = %v, err = %v, want a conflict", committed, err) + } + if now, _ := os.ReadFile(stale.Path()); string(now) != string(before) { + t.Fatal("a stale edit changed the file") + } +} + +// A list Core cannot decode is reported as damaged with its path, and is never overwritten; a +// refused entry names the field. +func TestADamagedListIsNeverOverwritten(t *testing.T) { + ctx := testContext(t) + kernel := core.NewClient() + root := t.TempDir() + path := filepath.Join(root, "remote", "connections.json") + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + t.Fatal(err) + } + damaged := []byte(`{"version":2,"connections":[]}`) + if err := os.WriteFile(path, damaged, 0o600); err != nil { + t.Fatal(err) + } + source, err := Read(ctx, kernel, root) + if !errors.Is(err, ErrDamaged) || source.Path() != path { + t.Fatalf("read: path = %q, err = %v, want the damaged list at %s", source.Path(), err, path) + } + if _, _, committed, err := source.Edit(ctx, kernel, save("A", "a.example")); !errors.Is(err, ErrDamaged) || committed { + t.Fatalf("edit: committed = %v, err = %v, want the damaged list refused", committed, err) + } + if now, _ := os.ReadFile(path); string(now) != string(damaged) { + t.Fatal("the damaged list was overwritten") + } + + empty, err := Read(ctx, kernel, t.TempDir()) + if err != nil { + t.Fatal(err) + } + _, _, _, err = empty.Edit(ctx, kernel, save("Box", "dev@box")) + if field, reason, ok := core.RemoteConnectionFieldError(err); !ok || field != "host" || reason != "invalid" { + t.Fatalf("host with a user: %v", err) + } + if _, err := Read(ctx, kernel, ""); !errors.Is(err, ErrUnavailable) { + t.Fatalf("no root: %v", err) + } +} diff --git a/desktop/internal/workbench/app.go b/desktop/internal/workbench/app.go index 5b29c95bf..11c9d746f 100644 --- a/desktop/internal/workbench/app.go +++ b/desktop/internal/workbench/app.go @@ -208,6 +208,10 @@ type Kernel interface { GitForceDeleteBranch(ctx context.Context, root string, branch core.GitReference, expectedTarget string) (core.GitBranchDeletion, error) GitDeleteRemoteBranch(ctx context.Context, root string, reference core.GitReference) error 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) + RemoteAuthRespond(ctx context.Context, requestID string, answer *string) (bool, error) GitCreateTag(ctx context.Context, root, name, revision, message string) error GitRebasePreview(ctx context.Context, root, base string) (core.RebasePreview, error) GitRebaseStart(ctx context.Context, root string, preview core.RebasePreview, steps []core.RebaseStep) (*core.RebaseSession, error) @@ -766,6 +770,8 @@ type App struct { welcome welcomeState clone cloneState + // remote is the Remote Development window (remote.go). + remote remoteState // gitAuth holds the questions of the Git operations the user started (git_auth.go). gitAuth gitAuthState newProject newProjectState diff --git a/desktop/internal/workbench/chrome_view.go b/desktop/internal/workbench/chrome_view.go index d3663cc1b..899db4647 100644 --- a/desktop/internal/workbench/chrome_view.go +++ b/desktop/internal/workbench/chrome_view.go @@ -628,7 +628,7 @@ func (a *App) chromeBranch(c ui.C) { func (a *App) projectMenu(c ui.C, anchor ui.Box) { var buf [chromeMenuRecents]int recents := a.menuRecents(&buf) - var created, chosen, cloned, current, closing bool + var created, chosen, cloned, remote, current, closing bool picked, removed := -1, -1 spec := ui.PopoverSpec{Align: ui.Start, Offset: chromeMenuOffset, Width: chromeMenuWidth, ConsumeOutsidePress: true} open := true @@ -637,6 +637,7 @@ func (a *App) projectMenu(c ui.C, anchor ui.Box) { created = a.menuAction(c.Part("new"), icons.Plus, a.text.Title.NewProjectItem) chosen = a.menuAction(c.Part("open"), icons.FolderOpen, a.text.Title.OpenItem) cloned = a.menuAction(c.Part("clone"), icons.Download, a.text.Title.CloneItem) + remote = a.menuAction(c.Part("remote"), icons.Server, i18n.Shared(a.language(), "desktop.remote.menuItem")) a.menuDivider(c) a.menuTitle(c, a.text.Title.OpenProjects) @@ -674,6 +675,9 @@ func (a *App) projectMenu(c ui.C, anchor ui.Box) { case cloned: a.title.projectOpen = false c.After(func() { a.openClone(surfaceMenu) }) + case remote: + a.title.projectOpen = false + c.After(func() { a.openRemote(surfaceMenu) }) case closing: a.title.projectOpen = false a.performed("workspace.close", surfaceMenu) diff --git a/desktop/internal/workbench/git_auth.go b/desktop/internal/workbench/git_auth.go index 8c22dc7f7..e46169d16 100644 --- a/desktop/internal/workbench/git_auth.go +++ b/desktop/internal/workbench/git_auth.go @@ -18,6 +18,9 @@ import ( // here instead of the credential helper (core.WithGitAuthentication). The questions queue in // the order Git asked them. One dialog, over everything else, answers the first, and the next // follows; a question leaves the queue once it is answered or its request has returned. +// +// The SSH client of a remote connection asks through the same queue and dialog (core.RemoteProbe +// marks its questions Remote): only the title, the hint and the command that answers differ. const ( // gitAuthRespondTimeout bounds passing one answer to Core, which replies at once. @@ -79,7 +82,11 @@ func (a *App) gitAuthDialog(c ui.C) { lang := a.language() g.open = true submitted, cancelled, confirmed := false, false, false - closed := ui.ModalWith(c, &g.open, i18n.Shared(lang, "desktop.gitAuth.title"), ui.ModalSpec{Width: gitAuthDialogWidth}, func() { + title := i18n.Shared(lang, "desktop.gitAuth.title") + if head.Remote { + title = i18n.Shared(lang, "desktop.remoteAuth.title") + } + closed := ui.ModalWith(c, &g.open, title, ui.ModalSpec{Width: gitAuthDialogWidth}, func() { ui.Column(c).FillWidth().Gap(10).Children(func() { if head.Retry { ui.Wrap(c, i18n.Shared(lang, "desktop.gitAuth.retryMessage")) @@ -97,7 +104,11 @@ func (a *App) gitAuthDialog(c ui.C) { } submitted = field.Submitted() if head.Secret { - ui.Wrap(c, i18n.Shared(lang, "desktop.gitAuth.secretHint")).FontSize(12).Color(a.colors.Subtle) + hint := i18n.Shared(lang, "desktop.gitAuth.secretHint") + if head.Remote { + hint = i18n.Shared(lang, "desktop.remoteAuth.secretHint") + } + ui.Wrap(c, hint).FontSize(12).Color(a.colors.Subtle) } } if head.WorkingDirectory != "" { @@ -135,35 +146,46 @@ func (a *App) answerGitAuth(requestID string, confirm bool) { head := g.queue[0] g.queue = g.queue[1:] var answer *string - action := "git.authentication.cancel" + kind, site, respond := "git.authentication.", "git_authentication", a.kernel.GitAuthRespond + if head.Remote { + kind, site, respond = "remote.authentication.", "remote_authentication", a.kernel.RemoteAuthRespond + } + action := kind + "cancel" switch { case confirm && head.Retry: retry := core.GitRetryAnswer - answer, action = &retry, "git.authentication.retry" + answer, action = &retry, kind+"retry" case confirm: typed := g.field.Text() - answer, action = &typed, "git.authentication.answer" + answer, action = &typed, kind+"answer" } g.field, g.fieldFor = ui.Field{}, "" a.performed(action, surfaceButton) - kernel := a.kernel a.background(nil, gitAuthRespondTimeout, func(ctx context.Context) func(*App) { - accepted, err := kernel.GitAuthRespond(ctx, head.RequestID, answer) + accepted, err := respond(ctx, head.RequestID, answer) refused := false if err == nil && !accepted && answer != nil && !requestReturned(head.Done) { // Core took no answer although the request still runs: either it refused this one // or the question expired. Only a question that still waits accepts the cancel. - refused, err = kernel.GitAuthRespond(ctx, head.RequestID, nil) + refused, err = respond(ctx, head.RequestID, nil) } return func(a *App) { lang := a.language() switch { case err != nil: - a.operationFailed("git_authentication", err) - a.notifyError(i18n.SharedFormat(lang, "desktop.gitAuth.failed", map[string]string{"reason": err.Error()})) + a.operationFailed(site, err) + text := i18n.SharedFormat(lang, "desktop.gitAuth.failed", map[string]string{"reason": err.Error()}) + if head.Remote { + text = i18n.SharedFormat(lang, "desktop.remoteAuth.failed", map[string]string{"reason": err.Error()}) + } + a.notifyError(text) case refused: - a.operationRejected("git_authentication", "answer_refused") - a.notifyError(i18n.Shared(lang, "desktop.gitAuth.refused")) + a.operationRejected(site, "answer_refused") + text := i18n.Shared(lang, "desktop.gitAuth.refused") + if head.Remote { + text = i18n.Shared(lang, "desktop.remoteAuth.refused") + } + a.notifyError(text) } } }) diff --git a/desktop/internal/workbench/logevents_test.go b/desktop/internal/workbench/logevents_test.go index d388a9344..96c16bc7b 100644 --- a/desktop/internal/workbench/logevents_test.go +++ b/desktop/internal/workbench/logevents_test.go @@ -50,6 +50,26 @@ func TestLogEventsMatchCatalog(t *testing.T) { {core.LevelInfo, "app.action.performed", map[string]any{"action": "git.authentication.answer", "surface": surfaceButton}}, {core.LevelInfo, "app.action.performed", map[string]any{"action": "git.authentication.retry", "surface": surfaceButton}}, {core.LevelInfo, "app.action.performed", map[string]any{"action": "git.authentication.cancel", "surface": surfaceButton}}, + {operationFailedLevel, operationFailedEvent, operationFailedFields("remote_authentication", failure)}, + {operationRejectedLevel, operationRejectedEvent, operationRejectedFields("remote_authentication", "answer_refused")}, + {core.LevelInfo, "app.action.performed", map[string]any{"action": "remote.authentication.answer", "surface": surfaceButton}}, + {core.LevelInfo, "app.action.performed", map[string]any{"action": "remote.authentication.cancel", "surface": surfaceButton}}, + {operationFailedLevel, operationFailedEvent, operationFailedFields("remote_connections_read", documentLogError(failure))}, + {operationFailedLevel, operationFailedEvent, operationFailedFields("remote_connection_save", documentLogError(failure))}, + {operationFailedLevel, operationFailedEvent, operationFailedFields("remote_connection_remove", documentLogError(failure))}, + {operationFailedLevel, operationFailedEvent, operationFailedFields("remote_choose_identity", documentLogError(failure))}, + {operationFailedLevel, operationFailedEvent, operationFailedFields("remote_probe", errors.New("remote probe: unreachable"))}, + {operationRejectedLevel, operationRejectedEvent, operationRejectedFields("remote_connection_save", "field_refused")}, + {operationRejectedLevel, operationRejectedEvent, operationRejectedFields("remote_connection_save", "number_invalid")}, + {operationRejectedLevel, operationRejectedEvent, operationRejectedFields("remote_connection_save", "changed_on_disk")}, + {operationRejectedLevel, operationRejectedEvent, operationRejectedFields("remote_probe", "field_refused")}, + {core.LevelInfo, "app.action.performed", map[string]any{"action": "remote.connections.open", "surface": surfaceMenu}}, + {core.LevelInfo, "app.action.performed", map[string]any{"action": "remote.connection.new", "surface": surfaceButton}}, + {core.LevelInfo, "app.action.performed", map[string]any{"action": "remote.connection.select", "surface": surfaceButton}}, + {core.LevelInfo, "app.action.performed", map[string]any{"action": "remote.connection.save", "surface": surfaceButton}}, + {core.LevelInfo, "app.action.performed", map[string]any{"action": "remote.connection.remove", "surface": surfaceButton}}, + {core.LevelInfo, "app.action.performed", map[string]any{"action": "remote.connection.test", "surface": surfaceButton}}, + {core.LevelInfo, "app.action.performed", map[string]any{"action": "remote.connection.test.stop", "surface": surfaceButton}}, {operationFailedLevel, operationFailedEvent, operationFailedFields("settings_save", failure)}, {operationFailedLevel, operationFailedEvent, operationFailedFields("workspace_reveal_recent", failure)}, {operationFailedLevel, operationFailedEvent, operationFailedFields("editor_open_in_browser", failure)}, diff --git a/desktop/internal/workbench/remote.go b/desktop/internal/workbench/remote.go new file mode 100644 index 000000000..1a80575f7 --- /dev/null +++ b/desktop/internal/workbench/remote.go @@ -0,0 +1,600 @@ +package workbench + +import ( + "context" + "errors" + "strconv" + "strings" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/1lck/Lithe-IDEA/desktop/internal/remoteconn" + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/ui" +) + +// The Remote Development window keeps the SSH connections the user saved (remoteconn) and tests +// one: the saved list on the left, the selected connection's form on the right. It belongs to the +// window, not to a project, so it opens on the welcome screen as over a project. +// +// Nothing secret passes through it: a password or a key's passphrase is asked by OpenSSH through +// Core's AskPass helper while a test runs, answered in the authentication dialog and never kept; +// a private key is kept as its path, and its contents are never read (design S12, S15). Neither +// the host, the user nor OpenSSH's output is logged: the log names only the operation and Core's +// fixed status or error. + +const ( + // remoteReadTimeout bounds reading or editing the saved list, a local file of at most Core's + // size limit. + remoteReadTimeout = 10 * time.Second + // remoteProbeTimeout bounds a test, which may wait for the user to answer OpenSSH's questions + // for up to Core's prompt deadline each. + remoteProbeTimeout = 6 * time.Minute +) + +// remoteState is the window's state. +type remoteState struct { + open bool + // generation counts the openings and closings, so that a result arriving after the window + // closed is dropped. + generation uint64 + loading bool + loaded bool + source remoteconn.Source + // readErr is why the list could not be read; nothing can be saved until it can. + readErr string + list ui.ListState + // selected is the id of the saved connection the form edits, "" for a new one. + selected string + form remoteForm + saving bool + // confirmDelete is the footer's question whether to delete the selected connection. + confirmDelete bool + // probe is the running test, nil when none runs; result is the last one's outcome. + probe *remoteProbe + result *remoteProbeOutcome + // err is the last failure that names no field of the form; fieldErr names one. + err string + fieldErr remoteFieldRefusal +} + +// remoteForm is what the user types for one connection. +type remoteForm struct { + name, host, port, user, identityFile, proxyJump, timeout, keepAlive ui.Field + authentication string + advanced ui.CollapsibleState +} + +// remoteProbe is a test in progress, cancelled by Stop or by closing the window. +type remoteProbe struct { + cancel context.CancelFunc +} + +// remoteProbeOutcome is what a test found: Core's result, or the error that kept it from running. +type remoteProbeOutcome struct { + result core.RemoteProbeResult + err error +} + +// remoteFieldRefusal is the field of the form Core (or the form's own number check) refused, and +// why: one of Core's reasons (required, invalid, tooLong, duplicate, full, unknown). +type remoteFieldRefusal struct { + field, reason string +} + +// remoteAuthentications are the ways a connection may authenticate, in the order the form offers. +var remoteAuthentications = []string{ + core.RemoteAuthenticationAuto, + core.RemoteAuthenticationAgent, + core.RemoteAuthenticationPrivateKey, + core.RemoteAuthenticationPassword, +} + +// openRemote opens the window and reads the saved list. +func (a *App) openRemote(surface actionSurface) { + r := &a.remote + if r.open { + return + } + r.generation++ + *r = remoteState{open: true, generation: r.generation} + r.form.clear() + a.performed("remote.connections.open", surface) + a.loadRemote(remoteLoadSelectFirst, "") +} + +// closeRemote closes the window, stopping a running test. What was typed and not saved is +// dropped. +func (a *App) closeRemote() { + r := &a.remote + r.stopProbe() + r.generation++ + r.open, r.saving, r.loading = false, false, false + r.form = remoteForm{} +} + +// remoteLoad says which connection the form shows once the list is read. +type remoteLoad int + +const ( + // remoteLoadSelectFirst selects the first saved connection, or a new one without any. + remoteLoadSelectFirst remoteLoad = iota + // remoteLoadSelect selects the connection the load names and fills the form from it. + remoteLoadSelect + // remoteLoadKeepForm leaves the form as typed, after a save found the list changed on disk. + remoteLoadKeepForm +) + +// loadRemote reads the saved list in the background and then applies how. +func (a *App) loadRemote(how remoteLoad, id string) { + r := &a.remote + r.loading = true + generation, kernel, root := r.generation, a.kernel, a.globalToolchainRoot() + a.background(nil, remoteReadTimeout, func(ctx context.Context) func(*App) { + source, err := remoteconn.Read(ctx, kernel, root) + return func(a *App) { + r := &a.remote + if !r.open || r.generation != generation { + // log-exempt: 用户取消:窗口关闭后不再应用读取结果。 + return + } + r.loading, r.loaded, r.source, r.readErr = false, true, source, "" + if err != nil { + a.operationFailed("remote_connections_read", documentLogError(err)) + r.readErr = remoteReadFailure(a.language(), source, err) + } + switch how { + case remoteLoadKeepForm: + r.syncListSelection() + case remoteLoadSelect: + if r.entry(id) != nil { + r.selectEntry(id) + return + } + r.selectFirst() + default: + r.selectFirst() + } + } + }) +} + +// remoteReadFailure is the window's text for a list that could not be read. +func remoteReadFailure(language i18n.Language, source remoteconn.Source, err error) string { + switch { + case errors.Is(err, remoteconn.ErrUnavailable): + return i18n.Shared(language, "desktop.remote.unavailable") + case errors.Is(err, remoteconn.ErrDamaged): + return i18n.SharedFormat(language, "desktop.remote.damaged", map[string]string{"path": source.Path()}) + } + return i18n.SharedFormat(language, "desktop.remote.readFailed", map[string]string{"reason": err.Error()}) +} + +// entry is the saved connection id, nil when the list has none of that id. +func (r *remoteState) entry(id string) *core.SavedRemoteConnection { + if id == "" { + return nil + } + for index := range r.source.Connections { + if r.source.Connections[index].ID == id { + return &r.source.Connections[index] + } + } + return nil +} + +// selectFirst selects the first saved connection, or starts a new one when there is none. +func (r *remoteState) selectFirst() { + if len(r.source.Connections) == 0 { + r.selectNew() + return + } + r.selectEntry(r.source.Connections[0].ID) +} + +// selectEntry shows the saved connection id in the form, dropping what was typed, the last test +// and its errors; a test still running for the previous form is stopped. +func (r *remoteState) selectEntry(id string) { + entry := r.entry(id) + if entry == nil { + r.selectNew() + return + } + r.resetEditing() + r.selected = id + r.form.fill(*entry) + r.syncListSelection() +} + +// selectNew starts a new connection with an empty form. +func (r *remoteState) selectNew() { + r.resetEditing() + r.selected = "" + r.form.clear() + r.syncListSelection() +} + +// resetEditing drops the last test, its errors and the delete question. +func (r *remoteState) resetEditing() { + r.stopProbe() + r.result, r.err, r.fieldErr, r.confirmDelete = nil, "", remoteFieldRefusal{}, false +} + +// syncListSelection selects the row of the edited connection, none for a new one. +func (r *remoteState) syncListSelection() { + at := -1 + for index, entry := range r.source.Connections { + if entry.ID == r.selected { + at = index + break + } + } + if r.list.Selected() != at { + r.list.Select(at) + if at >= 0 { + r.list.ScrollIntoView(at) + } + } +} + +// stopProbe cancels a running test; its result is dropped when it returns. +func (r *remoteState) stopProbe() { + if r.probe != nil { + r.probe.cancel() + r.probe = nil + } +} + +// clear empties the form for a new connection, which authenticates the way OpenSSH's own +// configuration says. +func (f *remoteForm) clear() { + for _, field := range f.fields() { + field.SetText("") + } + f.authentication = core.RemoteAuthenticationAuto + f.advanced.Open = false +} + +// fill shows a saved connection in the form; the advanced options are shown open when one is set. +func (f *remoteForm) fill(entry core.SavedRemoteConnection) { + connection := entry.Connection + f.name.SetText(entry.Name) + f.host.SetText(connection.Host) + f.port.SetText(optionalNumber(uint64(connection.Port))) + f.user.SetText(connection.User) + f.identityFile.SetText(connection.IdentityFile) + f.proxyJump.SetText(connection.ProxyJump) + f.timeout.SetText(optionalNumber(uint64(connection.ConnectTimeoutSeconds))) + f.keepAlive.SetText(optionalNumber(uint64(connection.KeepAliveSeconds))) + f.authentication = connection.Authentication + if f.authentication == "" { + f.authentication = core.RemoteAuthenticationAuto + } + f.advanced.Open = connection.ProxyJump != "" || connection.ConnectTimeoutSeconds != 0 || connection.KeepAliveSeconds != 0 +} + +// fields are the form's text fields. +func (f *remoteForm) fields() []*ui.Field { + return []*ui.Field{&f.name, &f.host, &f.port, &f.user, &f.identityFile, &f.proxyJump, &f.timeout, &f.keepAlive} +} + +// optionalNumber is value as the form shows it: empty for an unset 0. +func optionalNumber(value uint64) string { + if value == 0 { + return "" + } + return strconv.FormatUint(value, 10) +} + +// connection is the connection the form describes. A number field that is not a whole number in +// range is refused here, naming Core's field, since Core receives only numbers; every other check +// is Core's. Text is passed as typed, and Core trims it. +func (f *remoteForm) connection() (core.SSHConnection, *remoteFieldRefusal) { + port, refused := formNumber(&f.port, "port", 16) + if refused != nil { + return core.SSHConnection{}, refused + } + timeout, refused := formNumber(&f.timeout, "connectTimeoutSeconds", 32) + if refused != nil { + return core.SSHConnection{}, refused + } + keepAlive, refused := formNumber(&f.keepAlive, "keepAliveSeconds", 32) + if refused != nil { + return core.SSHConnection{}, refused + } + connection := core.SSHConnection{ + Host: f.host.Text(), + Port: uint16(port), + User: f.user.Text(), + Authentication: f.authentication, + ProxyJump: f.proxyJump.Text(), + ConnectTimeoutSeconds: uint32(timeout), + KeepAliveSeconds: uint32(keepAlive), + } + if f.authentication == core.RemoteAuthenticationPrivateKey { + connection.IdentityFile = f.identityFile.Text() + } + return connection, nil +} + +// formNumber reads an optional whole number of at most bits bits from field; empty is 0, unset. +func formNumber(field *ui.Field, name string, bits int) (uint64, *remoteFieldRefusal) { + text := strings.TrimSpace(field.Text()) + if text == "" { + return 0, nil + } + value, err := strconv.ParseUint(text, 10, bits) + if err != nil { + return 0, &remoteFieldRefusal{field: name, reason: "invalid"} + } + return value, nil +} + +// saveName is the name the form saves: the name typed, or the host when none was. +func (f *remoteForm) saveName() string { + if name := strings.TrimSpace(f.name.Text()); name != "" { + return name + } + return strings.TrimSpace(f.host.Text()) +} + +// dirty says whether the form differs from the saved connection it shows. A new connection is +// dirty once a host is typed. +func (r *remoteState) dirty() bool { + entry := r.entry(r.selected) + if entry == nil { + return strings.TrimSpace(r.form.host.Text()) != "" + } + connection, refused := r.form.connection() + if refused != nil { + return true + } + saved := entry.Connection + if saved.Authentication == "" { + saved.Authentication = core.RemoteAuthenticationAuto + } + trim := func(text string) string { return strings.TrimSpace(text) } + connection.Host, connection.User = trim(connection.Host), trim(connection.User) + connection.IdentityFile, connection.ProxyJump = trim(connection.IdentityFile), trim(connection.ProxyJump) + return r.form.saveName() != entry.Name || connection != saved +} + +// editable says whether the list can take an edit now. +func (r *remoteState) editable() bool { + return r.loaded && !r.loading && !r.saving && r.readErr == "" +} + +// saveRemote saves the form as a new connection or over the selected one, then reads the list +// again and shows what was stored. +func (a *App) saveRemote() { + r := &a.remote + if !r.open || !r.editable() { + return + } + r.err, r.fieldErr, r.confirmDelete = "", remoteFieldRefusal{}, false + connection, refused := r.form.connection() + if refused != nil { + a.operationRejected("remote_connection_save", "number_invalid") + r.fieldErr = *refused + return + } + a.performed("remote.connection.save", surfaceButton) + edit := core.RemoteConnectionEdit{Save: &core.RemoteConnectionSave{ID: r.selected, Name: r.form.saveName(), Connection: connection}} + a.editRemote("remote_connection_save", edit) +} + +// removeRemote deletes the selected connection once the user confirmed it. +func (a *App) removeRemote() { + r := &a.remote + if !r.open || !r.editable() || r.entry(r.selected) == nil { + return + } + r.err, r.fieldErr, r.confirmDelete = "", remoteFieldRefusal{}, false + a.performed("remote.connection.remove", surfaceButton) + a.editRemote("remote_connection_remove", core.RemoteConnectionEdit{Remove: &core.RemoteConnectionID{ID: r.selected}}) +} + +// editRemote applies edit to the list as it was read, in the background. site names the +// operation in the log. +func (a *App) editRemote(site string, edit core.RemoteConnectionEdit) { + r := &a.remote + r.saving = true + generation, kernel, source := r.generation, a.kernel, r.source + a.background(nil, remoteReadTimeout, func(ctx context.Context) func(*App) { + after, id, committed, err := source.Edit(ctx, kernel, edit) + return func(a *App) { + r := &a.remote + if !r.open || r.generation != generation { + if err != nil { + a.operationFailed(site, documentLogError(err)) + } + // log-exempt: 用户取消:窗口关闭后不再应用保存结果;文件已按原子方式写入或未写入。 + return + } + r.saving = false + language := a.language() + if field, reason, ok := core.RemoteConnectionFieldError(err); ok { + a.operationRejected(site, "field_refused") + refusal := remoteFieldRefusal{field: field, reason: reason} + if remoteFormField(field) { + r.fieldErr = refusal + } else { + r.err = remoteRefusalText(language, refusal) + } + return + } + switch { + case errors.Is(err, remoteconn.ErrConflict): + a.operationRejected(site, "changed_on_disk") + r.err = i18n.Shared(language, "desktop.remote.conflict") + a.loadRemote(remoteLoadKeepForm, "") + return + case err != nil && committed: + // The list reached the disk, but reading it back failed: the read shows why. + a.operationFailed(site, documentLogError(err)) + a.loadRemote(remoteLoadSelect, id) + return + case err != nil: + a.operationFailed(site, documentLogError(err)) + if errors.Is(err, remoteconn.ErrDamaged) { + r.readErr = remoteReadFailure(language, source, err) + return + } + if edit.Remove != nil { + r.err = i18n.SharedFormat(language, "desktop.remote.deleteFailed", map[string]string{"reason": err.Error()}) + } else { + r.err = i18n.SharedFormat(language, "desktop.remote.saveFailed", map[string]string{"reason": err.Error()}) + } + return + } + r.source, r.loaded = after, true + if edit.Remove != nil { + r.selectFirst() + return + } + r.selectEntry(id) + } + }) +} + +// chooseRemoteIdentity lets the user pick the private key file; only its path is kept. +func (a *App) chooseRemoteIdentity() { + r := &a.remote + generation := r.generation + title := i18n.Shared(a.language(), "desktop.remote.identityFile") + a.background(nil, 0, func(context.Context) func(*App) { + paths, err := app.OpenFiles(app.OpenFileOptions{Title: title}) + return func(a *App) { + r := &a.remote + if errors.Is(err, app.ErrCanceled) { + // log-exempt: 用户取消:文件选择器没有选择结果。 + return + } + if err != nil { + a.operationFailed("remote_choose_identity", documentLogError(err)) + if r.open && r.generation == generation { + r.err = i18n.SharedFormat(a.language(), "desktop.remote.chooseFailed", map[string]string{"reason": documentLogError(err).Error()}) + } + return + } + if !r.open || r.generation != generation || len(paths) == 0 { + // log-exempt: 用户取消:窗口关闭后不再应用选择结果。 + return + } + r.form.identityFile.SetText(paths[0]) + } + }) +} + +// testRemote connects with what the form holds, saved or not, and reports what the host is. +// OpenSSH's questions (a password, a passphrase, an unknown host key) are asked in the +// authentication dialog while it runs. +func (a *App) testRemote() { + r := &a.remote + if !r.open || r.probe != nil { + return + } + r.result, r.err, r.fieldErr = nil, "", remoteFieldRefusal{} + connection, refused := r.form.connection() + if refused != nil { + a.operationRejected("remote_probe", "number_invalid") + r.fieldErr = *refused + return + } + a.performed("remote.connection.test", surfaceButton) + ctx, cancel := context.WithTimeout(a.operationContext(context.Background()), remoteProbeTimeout) + probe := &remoteProbe{cancel: cancel} + r.probe = probe + generation, kernel := r.generation, a.kernel + a.background(nil, 0, func(context.Context) func(*App) { + defer cancel() + result, err := kernel.RemoteProbe(a.gitAuthentication(ctx), connection) + return func(a *App) { + r := &a.remote + if !r.open || r.generation != generation || r.probe != probe { + // log-exempt: 用户取消:测试已停止、换了连接或窗口已关闭,不再应用结果。 + return + } + r.probe = nil + switch { + case err != nil: + if field, reason, ok := core.RemoteConnectionFieldError(err); ok { + a.operationRejected("remote_probe", "field_refused") + refusal := remoteFieldRefusal{field: field, reason: reason} + if remoteFormField(field) { + r.fieldErr = refusal + } else { + r.err = remoteRefusalText(a.language(), refusal) + } + return + } + a.operationFailed("remote_probe", documentLogError(err)) + case result.Status != core.RemoteProbeConnected: + // The status is Core's fixed token; OpenSSH's output may name the host and user + // and is only shown. + a.operationFailed("remote_probe", errors.New("remote probe: "+string(result.Status))) + } + r.result = &remoteProbeOutcome{result: result, err: err} + } + }) +} + +// stopRemoteTest stops the running test. +func (a *App) stopRemoteTest() { + r := &a.remote + if r.probe == nil { + return + } + a.performed("remote.connection.test.stop", surfaceButton) + r.stopProbe() +} + +// remoteFormField says whether the form shows field, Core's name of a connection's field. +func remoteFormField(field string) bool { + switch field { + case "name", "host", "port", "user", "authentication", "identityFile", "proxyJump", "connectTimeoutSeconds", "keepAliveSeconds": + return true + } + return false +} + +// remoteRefusalText says why Core, or the form's number check, refused a field. +func remoteRefusalText(language i18n.Language, refusal remoteFieldRefusal) string { + switch refusal.reason { + case "required": + return i18n.Shared(language, "desktop.remote.error.required") + case "tooLong": + if refusal.field == "name" { + return i18n.Shared(language, "desktop.remote.error.nameTooLong") + } + return i18n.Shared(language, "desktop.remote.error.fieldTooLong") + case "duplicate": + if refusal.field == "name" { + return i18n.Shared(language, "desktop.remote.error.nameDuplicate") + } + return i18n.Shared(language, "desktop.remote.error.duplicate") + case "full": + return i18n.Shared(language, "desktop.remote.error.full") + case "unknown": + return i18n.Shared(language, "desktop.remote.error.unknown") + case "invalid": + switch refusal.field { + case "host": + return i18n.Shared(language, "desktop.remote.error.hostInvalid") + case "port": + return i18n.Shared(language, "desktop.remote.error.portInvalid") + case "user": + return i18n.Shared(language, "desktop.remote.error.userInvalid") + case "proxyJump": + return i18n.Shared(language, "desktop.remote.error.proxyJumpInvalid") + case "connectTimeoutSeconds": + return i18n.Shared(language, "desktop.remote.error.timeoutInvalid") + case "keepAliveSeconds": + return i18n.Shared(language, "desktop.remote.error.keepAliveInvalid") + case "name", "identityFile": + return i18n.Shared(language, "desktop.remote.error.textInvalid") + } + } + return i18n.Shared(language, "desktop.remote.error.invalid") +} diff --git a/desktop/internal/workbench/remote_connections_visual_test.go b/desktop/internal/workbench/remote_connections_visual_test.go new file mode 100644 index 000000000..986881dae --- /dev/null +++ b/desktop/internal/workbench/remote_connections_visual_test.go @@ -0,0 +1,132 @@ +//go:build vivahead && lithevisual + +package workbench + +import ( + "context" + "os" + "path/filepath" + "testing" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/store" + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/headless" +) + +// remoteVisualKernel reports a fixed probe outcome instead of starting OpenSSH; everything else +// is the real Core. +type remoteVisualKernel struct { + *core.Client + result core.RemoteProbeResult +} + +func (k *remoteVisualKernel) RemoteProbe(context.Context, core.SSHConnection) (core.RemoteProbeResult, error) { + return k.result, nil +} + +// TestVisualRemoteConnections captures the Remote Development window: two saved connections +// with the tested one's host report, a host Core refused under its field, and OpenSSH's password +// question over the window. +func TestVisualRemoteConnections(t *testing.T) { + out := os.Getenv("LITHE_VISUAL_OUTPUT_DIR") + if out == "" { + t.Skip("set LITHE_VISUAL_OUTPUT_DIR") + } + if err := os.MkdirAll(out, 0755); err != nil { + t.Fatal(err) + } + const gib = uint64(1) << 30 + probed := core.RemoteProbeResult{ + Status: core.RemoteProbeConnected, + Host: &core.RemoteProbedHost{ + System: "Linux", Machine: "x86_64", HomeDirectory: "/home/dev", ServerTarget: "x86_64-unknown-linux-musl", + Details: core.RemoteHostDetails{ + HostName: "build", OperatingSystem: "Ubuntu 24.04.1 LTS", Kernel: "6.8.0-49-generic", + CPUCount: 16, MemoryBytes: 64 * gib, DiskTotalBytes: 512 * gib, DiskAvailableBytes: 301 * gib, + }, + }, + } + for _, look := range []struct{ theme, language, suffix string }{ + {"light", "en-US", "light-en-US"}, + {"dark", "zh-Hans", "dark-zh-CN"}, + } { + t.Run(look.suffix, func(t *testing.T) { + prefs := store.At(t.TempDir()) + if err := prefs.Save(settingsFile, settings{Theme: themeChoice(look.theme), Language: look.language, DisableAutoSave: true}); err != nil { + t.Fatal(err) + } + var session *headless.Session + kernel := &remoteVisualKernel{Client: core.NewClient(), result: probed} + h := newHarnessWithDriver(t, Options{Kernel: kernel, Store: prefs, Languages: []string{look.language}}, func(config app.Config) (*app.Driver, func(), error) { + config.Width, config.Height = 1200, 760 + var err error + session, err = headless.Open(config, nil, headless.Options{}) + if err != nil { + return nil, nil, err + } + return session.Driver(), session.Close, nil + }) + shot := func(scene string) { + t.Helper() + // The scenes set the window's state directly, which does not ask for a frame. + h.app.invalidator.Invalidate() + h.settleChain() + if err := session.Screenshot(filepath.Join(out, "remote-connections-"+scene+"-"+look.suffix+".png")); err != nil { + t.Fatal(err) + } + } + h.app.openRemote(surfaceMenu) + h.settleChain() + r := &h.app.remote + + save := func(name, host, port, user, authentication, identityFile string) { + t.Helper() + r.selectNew() + r.form.name.SetText(name) + r.form.host.SetText(host) + r.form.port.SetText(port) + r.form.user.SetText(user) + r.form.authentication = authentication + r.form.identityFile.SetText(identityFile) + h.app.saveRemote() + h.settleChain() + if r.err != "" || r.fieldErr.field != "" { + t.Fatalf("saving %s: %q %+v", name, r.err, r.fieldErr) + } + } + save("Lab ARM", "lab-arm.internal", "", "dev", core.RemoteAuthenticationAgent, "") + save("Build box", "build.example", "2222", "dev", core.RemoteAuthenticationPrivateKey, "/home/me/.ssh/id_ed25519") + h.app.testRemote() + h.settleChain() + if r.result == nil { + t.Fatal("the test did not report") + } + shot("tested") + + r.selectNew() + r.form.host.SetText("dev@build.example") + h.app.saveRemote() + h.settleChain() + if r.fieldErr.field != "host" { + t.Fatalf("refusal = %+v, want the host", r.fieldErr) + } + shot("refused") + + for _, entry := range r.source.Connections { + if entry.Name == "Build box" { + r.selectEntry(entry.ID) + } + } + done := make(chan struct{}) + h.app.gitAuth.queue = append(h.app.gitAuth.queue, core.GitAuthChallenge{ + RequestID: "visual", Prompt: "dev@build.example's password: ", Secret: true, Attempt: 1, Remote: true, Done: done, + }) + shot("password") + h.app.gitAuth.queue = nil + close(done) + h.app.closeRemote() + h.settleChain() + }) + } +} diff --git a/desktop/internal/workbench/remote_test.go b/desktop/internal/workbench/remote_test.go new file mode 100644 index 000000000..e933c1091 --- /dev/null +++ b/desktop/internal/workbench/remote_test.go @@ -0,0 +1,375 @@ +package workbench + +import ( + "context" + "encoding/json" + "errors" + "io/fs" + "os" + "path/filepath" + "runtime" + "slices" + "strings" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/1lck/Lithe-IDEA/desktop/internal/remoteconn" + "github.com/vivaui/viva/gfx" +) + +// redraw repaints the window after a test changed its state directly, as SetText does without +// invalidating, and lets the work it started finish. +func (h *harness) redraw() { + h.t.Helper() + h.app.invalidator.Invalidate() + h.settle() +} + +// pressTest clicks Test Connection and paints the frame that started the test, without waiting +// for background work: the test waits on the question the window has yet to show. +func (h *harness) pressTest() { + h.t.Helper() + point := center(h.hitLabeled(i18n.Shared(h.app.language(), "desktop.remote.test"))) + if err := h.driver.Click(point.X, point.Y); err != nil { + h.t.Fatal(err) + } + if err := h.driver.Pump(); err != nil { + h.t.Fatal(err) + } + if h.app.remote.probe == nil { + h.t.Fatal("clicking Test Connection did not start a test") + } +} + +// remoteHarness is an English window with the Remote Development window open and its saved list +// read, through the real Core. +func remoteHarness(t *testing.T) (*harness, *treeRecordingLog) { + t.Helper() + h := newHarnessWithLanguages(t, &testKernel{Client: core.NewClient()}, []string{"en-US"}) + logger := &treeRecordingLog{} + h.app.logSink = logger + h.app.openRemote(surfaceMenu) + h.settle() + h.settle() + if !h.app.remote.loaded || h.app.remote.readErr != "" { + t.Fatalf("loaded = %v, read error = %q", h.app.remote.loaded, h.app.remote.readErr) + } + return h, logger +} + +// savedRemoteDocument reports whether the saved list exists on disk, in the preference directory. +func savedRemoteDocument(t *testing.T, h *harness) bool { + t.Helper() + _, err := os.Stat(filepath.Join(h.store.Dir(), "remote", "connections.json")) + if err != nil && !errors.Is(err, fs.ErrNotExist) { + t.Fatal(err) + } + return err == nil +} + +// savedRemoteConnections are the entries of the saved list on disk, as Core reads them back. +func savedRemoteConnections(t *testing.T, h *harness) []core.SavedRemoteConnection { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + source, err := remoteconn.Read(ctx, core.NewClient(), h.store.Dir()) + if err != nil { + t.Fatalf("read the saved list: %v", err) + } + return source.Connections +} + +// remoteActions are the actions of the window and of its authentication dialog logged as +// performed, in order. +func remoteActions(logger *treeRecordingLog) []string { + logger.mu.Lock() + defer logger.mu.Unlock() + var actions []string + for _, event := range logger.events { + if action, _ := event.Fields["action"].(string); event.Event == "app.action.performed" && strings.HasPrefix(action, "remote.") { + actions = append(actions, action) + } + } + return actions +} + +// loggedAny reports whether any logged field holds one of values. +func loggedAny(t *testing.T, logger *treeRecordingLog, values ...string) string { + t.Helper() + logger.mu.Lock() + defer logger.mu.Unlock() + for _, event := range logger.events { + encoded, err := json.Marshal(event) + if err != nil { + t.Fatal(err) + } + for _, value := range values { + if strings.Contains(string(encoded), value) { + return string(encoded) + } + } + } + return "" +} + +// rejected reports whether operation was logged as rejected for reason. +func rejected(logger *treeRecordingLog, operation, reason string) bool { + logger.mu.Lock() + defer logger.mu.Unlock() + return slices.ContainsFunc(logger.events, func(event core.LogEvent) bool { + return event.Event == operationRejectedEvent && event.Fields["operation"] == operation && event.Fields["reason"] == reason + }) +} + +// A connection typed into the window is saved to the preference directory under the host's name, +// edited in place and deleted after the footer's question; only the operations are logged, never +// the host or the user. +func TestRemoteConnectionsSaveEditAndDelete(t *testing.T) { + h, logger := remoteHarness(t) + lang := h.app.language() + if !h.shows(i18n.Shared(lang, "desktop.remote.title")) || !h.showsWrapped(i18n.Shared(lang, "desktop.remote.empty")) { + t.Fatal("the window does not open on the empty list") + } + if savedRemoteDocument(t, h) { + t.Fatal("opening the window wrote the list") + } + r := &h.app.remote + r.form.host.SetText("build.example") + r.form.user.SetText("dev") + h.redraw() + h.clickLabeled(i18n.Shared(lang, "desktop.remote.save")) + h.settle() + entries := savedRemoteConnections(t, h) + if len(entries) != 1 || entries[0].Name != "build.example" { + t.Fatalf("saved %+v, want one connection named after its host", entries) + } + if connection := entries[0].Connection; connection.Host != "build.example" || connection.User != "dev" { + t.Fatalf("saved connection %+v", connection) + } + if r.selected == "" || r.selected != entries[0].ID || !h.shows("dev@build.example") || r.dirty() { + t.Fatalf("selected = %q, dirty = %v: the saved connection is not the one the form edits", r.selected, r.dirty()) + } + + r.form.name.SetText("Build box") + r.form.port.SetText("2222") + h.redraw() + h.clickLabeled(i18n.Shared(lang, "desktop.remote.save")) + h.settle() + entries = savedRemoteConnections(t, h) + if len(entries) != 1 || entries[0].Name != "Build box" || entries[0].Connection.Port != 2222 || !h.shows("Build box") { + t.Fatalf("edited %+v, want the one connection renamed with its port", entries) + } + + h.clickLabeled(i18n.Shared(lang, "desktop.remote.delete")) + h.settle() + if !r.confirmDelete || !h.shows(i18n.SharedFormat(lang, "desktop.remote.deleteConfirm", map[string]string{"name": "Build box"})) { + t.Fatal("Delete does not ask first") + } + if len(savedRemoteConnections(t, h)) != 1 { + t.Fatal("Delete deleted before it was confirmed") + } + h.clickLabeled(i18n.Shared(lang, "desktop.remote.delete")) + h.settle() + if got := savedRemoteConnections(t, h); len(got) != 0 || r.selected != "" || !h.showsWrapped(i18n.Shared(lang, "desktop.remote.empty")) { + t.Fatalf("after deleting: saved %v, selected %q", got, r.selected) + } + want := []string{"remote.connections.open", "remote.connection.save", "remote.connection.save", "remote.connection.remove"} + if got := remoteActions(logger); !slices.Equal(got, want) { + t.Fatalf("performed %q, want %q", got, want) + } + if event := loggedAny(t, logger, "build.example", "Build box", h.store.Dir()); event != "" { + t.Fatalf("logged the connection: %s", event) + } + + h.clickLabeled(i18n.Shared(lang, "desktop.remote.close")) + h.settle() + if r.open || h.shows(i18n.Shared(lang, "desktop.remote.title")) { + t.Fatal("Close left the window open") + } +} + +// A connection saved from New is the list's selected row, also when the list had fewer rows the +// frame before: the keyboard moves from the connection the form edits. +func TestRemoteSavedConnectionIsTheSelectedRow(t *testing.T) { + h, _ := remoteHarness(t) + lang := h.app.language() + r := &h.app.remote + for _, host := range []string{"lab-arm.internal", "build.example"} { + h.clickLabeled(i18n.Shared(lang, "desktop.remote.new")) + r.form.host.SetText(host) + h.redraw() + h.clickLabeled(i18n.Shared(lang, "desktop.remote.save")) + h.redraw() + at := slices.IndexFunc(r.source.Connections, func(entry core.SavedRemoteConnection) bool { return entry.ID == r.selected }) + if r.selected == "" || at < 0 || r.list.Selected() != at { + t.Fatalf("after saving %d: list row %d, want %d, the connection the form edits", len(r.source.Connections), r.list.Selected(), at) + } + } +} + +// A field Core refuses is named under that field and nothing is written; a number the form +// cannot parse is refused before it reaches Core. +func TestRemoteConnectionRefusedFieldsAreShownUnderTheField(t *testing.T) { + h, logger := remoteHarness(t) + lang := h.app.language() + r := &h.app.remote + r.form.host.SetText("dev@box") + h.redraw() + h.clickLabeled(i18n.Shared(lang, "desktop.remote.save")) + h.settle() + if r.fieldErr != (remoteFieldRefusal{field: "host", reason: "invalid"}) || !h.showsWrapped(i18n.Shared(lang, "desktop.remote.error.hostInvalid")) { + t.Fatalf("field refusal = %+v, want the host refused under its field", r.fieldErr) + } + if savedRemoteDocument(t, h) || !rejected(logger, "remote_connection_save", "field_refused") { + t.Fatal("a refused connection was written, or the refusal was not logged") + } + + r.form.host.SetText("box") + r.form.port.SetText("70000") + h.redraw() + h.clickLabeled(i18n.Shared(lang, "desktop.remote.save")) + h.settle() + if r.fieldErr != (remoteFieldRefusal{field: "port", reason: "invalid"}) || !h.showsWrapped(i18n.Shared(lang, "desktop.remote.error.portInvalid")) { + t.Fatalf("field refusal = %+v, want the port refused under its field", r.fieldErr) + } + if savedRemoteDocument(t, h) || !rejected(logger, "remote_connection_save", "number_invalid") { + t.Fatal("a port out of range was written, or the refusal was not logged") + } + + // The private key path is only asked for, and only kept, with private key authentication. + if h.shows(i18n.Shared(lang, "desktop.remote.identityFile")) { + t.Fatal("the private key field shows for automatic authentication") + } + r.form.authentication = core.RemoteAuthenticationPrivateKey + r.form.port.SetText("") + r.form.identityFile.SetText("~/.ssh/id_ed25519") + h.redraw() + if !h.shows(i18n.Shared(lang, "desktop.remote.identityFile")) { + t.Fatal("the private key field is missing for private key authentication") + } + r.form.authentication = core.RemoteAuthenticationAgent + h.redraw() + h.clickLabeled(i18n.Shared(lang, "desktop.remote.save")) + h.settle() + entries := savedRemoteConnections(t, h) + if len(entries) != 1 || entries[0].Connection.Authentication != core.RemoteAuthenticationAgent || entries[0].Connection.IdentityFile != "" { + t.Fatalf("saved %+v, want the agent connection without a key path", entries) + } +} + +// standInSSH puts an ssh on PATH that ignores its options and, after asking for a password +// through the AskPass helper Core names, runs the remote command with the local shell. A wrong +// or cancelled answer fails like a server rejecting it. +func standInSSH(t *testing.T) { + t.Helper() + if runtime.GOOS == "windows" { + t.Skip("the stand-in SSH client is a POSIX shell script") + } + dir := t.TempDir() + script := `#!/bin/sh +for last; do :; done +answer=$("$SSH_ASKPASS" "dev@devbox's password: ") || answer= +if [ "$answer" != "s3cret" ]; then + echo 'dev@devbox: Permission denied (password).' >&2 + exit 255 +fi +exec /bin/sh -c "$last" +` + if err := os.WriteFile(filepath.Join(dir, "ssh"), []byte(script), 0o755); err != nil { + t.Fatal(err) + } + t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH")) +} + +// Testing a connection asks OpenSSH's password question in the SSH authentication dialog over +// the window, and shows what the host reported once it is answered; cancelling the question +// shows the server's refusal with OpenSSH's output. Neither the password, the host nor the user +// is logged. +func TestRemoteTestAsksInTheWindowAndReportsTheHost(t *testing.T) { + standInSSH(t) + h, logger := remoteHarness(t) + lang := h.app.language() + r := &h.app.remote + r.form.host.SetText("devbox") + r.form.user.SetText("dev") + h.redraw() + + h.pressTest() + h.awaitGitQuestion("the password question", func(c core.GitAuthChallenge) bool { return c.Remote && c.Secret }) + if !h.shows(i18n.Shared(lang, "desktop.remoteAuth.title")) || !h.shows("password") || !h.showsWrapped(i18n.Shared(lang, "desktop.remoteAuth.secretHint")) { + t.Fatal("the dialog does not show OpenSSH's question as the SSH client's") + } + if h.shows(i18n.Shared(lang, "desktop.gitAuth.title")) { + t.Fatal("the remote question is titled as Git's") + } + if got := h.focusedName(); got != i18n.Shared(lang, "desktop.gitAuth.answer") { + t.Fatalf("focused %q, want the answer field", got) + } + h.typeText("s3cret") + h.key(gfx.KeyEnter) + h.await("the test to finish", func() bool { return r.probe == nil && r.result != nil }) + h.settle() + result := r.result.result + if r.result.err != nil || result.Host == nil { + t.Fatalf("outcome = %+v, want the host's report", r.result) + } + // The local machine is the host here, so whether a server build exists depends on it. + key := "desktop.remote.probe.unsupported" + if result.Status == core.RemoteProbeConnected { + key = "desktop.remote.probe.connected" + } + platform := map[string]string{"system": result.Host.System, "machine": result.Host.Machine} + if !h.showsWrapped(i18n.SharedFormat(lang, key, platform)) || !h.shows(i18n.Shared(lang, "desktop.remote.probe.cpu")) { + t.Fatalf("the window does not show the platform the host reported (%s)", result.Status) + } + + h.pressTest() + h.awaitGitQuestion("the password question again", func(c core.GitAuthChallenge) bool { return c.Remote }) + // Escape dismisses the topmost dialog, the question, and leaves the window open. + h.key(gfx.KeyEscape) + h.await("the test to fail", func() bool { return r.probe == nil && r.result != nil }) + h.settle() + if !r.open || r.result.result.Status != core.RemoteProbeAuthenticationFailed { + t.Fatalf("open = %v, outcome = %+v, want the refusal in the open window", r.open, r.result) + } + if !h.showsWrapped(i18n.Shared(lang, "desktop.remote.probe.authenticationFailed")) || !h.showsWrapped("Permission denied (password).") { + t.Fatal("the window does not show the refusal with OpenSSH's output") + } + want := []string{"remote.connections.open", "remote.connection.test", "remote.authentication.answer", "remote.connection.test", "remote.authentication.cancel"} + if got := remoteActions(logger); !slices.Equal(got, want) { + t.Fatalf("performed %q, want %q", got, want) + } + if event := loggedAny(t, logger, "s3cret", "devbox", "Permission denied"); event != "" { + t.Fatalf("logged what the connection is or OpenSSH said: %s", event) + } +} + +// Stopping a test drops its result, and closing the window stops a test that waits on a question. +func TestRemoteTestStopsWithTheWindow(t *testing.T) { + standInSSH(t) + h, _ := remoteHarness(t) + lang := h.app.language() + r := &h.app.remote + r.form.host.SetText("devbox") + h.redraw() + h.pressTest() + h.awaitGitQuestion("the password question", func(c core.GitAuthChallenge) bool { return c.Remote }) + // The question covers the window, so Stop is the window's own action here. + h.app.stopRemoteTest() + h.await("the question to leave after Stop", func() bool { return len(h.app.gitAuth.queue) == 0 }) + h.settle() + if !r.open || r.probe != nil || r.result != nil || h.showsWrapped(i18n.Shared(lang, "desktop.remote.probe.authenticationFailed")) { + t.Fatalf("open = %v, probe = %v, result = %+v after Stop, want the open window without an outcome", r.open, r.probe, r.result) + } + + h.pressTest() + h.awaitGitQuestion("the password question again", func(c core.GitAuthChallenge) bool { return c.Remote }) + h.app.closeRemote() + h.await("the question to leave after closing", func() bool { return len(h.app.gitAuth.queue) == 0 }) + h.settle() + if r.open || r.probe != nil || r.result != nil { + t.Fatalf("open = %v, probe = %v, result = %+v after closing", r.open, r.probe, r.result) + } +} diff --git a/desktop/internal/workbench/remote_view.go b/desktop/internal/workbench/remote_view.go new file mode 100644 index 000000000..304fa33aa --- /dev/null +++ b/desktop/internal/workbench/remote_view.go @@ -0,0 +1,391 @@ +package workbench + +import ( + "errors" + "strconv" + "strings" + + "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/gfx" + "github.com/vivaui/viva/ui" +) + +// This file draws the Remote Development window of remote.go. + +const ( + // remoteWindowWidth and remoteWindowHeight size the window: the list beside a form whose + // labels and fields stay on one line each. + remoteWindowWidth = 820 + remoteWindowHeight = 580 + // remoteListWidth is the width of the saved list. + remoteListWidth = 240 + // remoteLabelWidth is the width of the form's label column. + remoteLabelWidth = 132 + // remoteRowHeight is the height of a saved connection's row: its name over its address. + remoteRowHeight = 44 +) + +// remoteView declares the window while it is open. Escape, the scrim and the close button end it +// like Close. +func (a *App) remoteView(c ui.C) { + r := &a.remote + if !r.open { + return + } + language := a.language() + open := true + ui.ModalWith(c, &open, i18n.Shared(language, "desktop.remote.title"), ui.ModalSpec{Width: remoteWindowWidth, Height: remoteWindowHeight}, func() { + k := c.Part("remote") + ui.Row(k).Fill().Children(func() { + a.remoteList(k) + ui.Column(k).Width(1).FillHeight().Shrink(0).Background(a.colors.Line) + a.remoteDetail(k) + }) + }, func() { + a.remoteFooter(c.Part("remote-footer")) + }) + if !open { + c.After(a.closeRemote) + } +} + +// remoteList declares the saved connections, under a header with the button that starts a new one. +func (a *App) remoteList(c ui.C) { + r := &a.remote + language := a.language() + k := c.Part("list") + title := i18n.Shared(language, "desktop.remote.saved") + ui.Column(k).Width(remoteListWidth).FillHeight().Shrink(0).Children(func() { + ui.Row(k.Part("header")).FillWidth().Height(panelHeaderHeight).Shrink(0).Items(ui.Center).Gap(4).PadSides(0, 6, 0, 10).Children(func() { + ui.Text(k, title).FontSize(a.theme.Metrics.FontSizeS).Weight(gfx.WeightSemibold).Color(a.colors.Subtle).Ellipsis().Shrink(1).MinWidth(0) + if path := r.source.Path(); path != "" { + a.remoteHelp(k.Part("storage"), i18n.SharedFormat(language, "desktop.remote.storageHelp", map[string]string{"path": path})) + } + ui.Spacer(k) + if a.gitIconButton(k.Part("new"), i18n.Shared(language, "desktop.remote.new"), icons.Plus, false, r.saving) { + c.After(func() { + a.performed("remote.connection.new", surfaceButton) + r.selectNew() + }) + } + }) + ui.Row(k).FillWidth().Height(1).Shrink(0).Background(a.colors.Line) + connections := r.source.Connections + if len(connections) == 0 { + text := i18n.Shared(language, "desktop.remote.empty") + if r.loading { + text = i18n.Shared(language, "native.loading") + } + ui.Row(k.Part("empty")).FillWidth().Pad(10).Children(func() { + ui.Paragraph(k, text, 3).FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Subtle) + }) + return + } + r.list.Label = func(row int) string { + if row < 0 || row >= len(r.source.Connections) { + return "" + } + return r.source.Connections[row].Name + } + ui.List(k.Part("rows"), &r.list, len(connections), func(row ui.ListRow) { + entry := connections[row.Index] + rc := row.C + row.Element.Height(remoteRowHeight).PadX(10).Gap(8).Items(ui.Center).Hover(ui.Look{}.Background(a.colors.Hover)) + // The row of the edited connection is highlighted, also in the frame a save added it, + // before the list's own selection can reach it. + if entry.ID == r.selected { + row.Element.Background(a.colors.Selection) + } + row.Element.Children(func() { + ui.Icon(rc, icons.Server).Size(16, 16).Shrink(0).Color(a.colors.Subtle) + ui.Column(rc).Grow(1).Shrink(1).MinWidth(0).Gap(2).Children(func() { + ui.Text(rc, entry.Name).Weight(gfx.WeightSemibold).Ellipsis() + ui.Text(rc, remoteAddress(entry.Connection)).FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Subtle).Ellipsis() + }) + }) + }).Scrollbars().FillWidth().Grow(1).Shrink(1).MinHeight(0).Label(title) + if r.list.Changed() { + if at := r.list.Selected(); at >= 0 && at < len(connections) && connections[at].ID != r.selected { + id := connections[at].ID + c.After(func() { + a.performed("remote.connection.select", surfaceButton) + r.selectEntry(id) + }) + } + } else { + // The list selects only rows it has declared, so the row a save added becomes the + // keyboard's row here, once the list declared it. + r.syncListSelection() + } + }) +} + +// remoteAddress is a connection as OpenSSH would address it: [user@]host[:port]. +func remoteAddress(connection core.SSHConnection) string { + address := connection.Host + if connection.User != "" { + address = connection.User + "@" + address + } + if connection.Port != 0 { + host := address + if strings.Contains(connection.Host, ":") { + // An IPv6 address keeps its brackets apart from the port. + host = strings.TrimSuffix(address, connection.Host) + "[" + connection.Host + "]" + } + address = host + ":" + strconv.Itoa(int(connection.Port)) + } + return address +} + +// remoteDetail declares the form of the edited connection, then what the last test found. +func (a *App) remoteDetail(c ui.C) { + r := &a.remote + language := a.language() + k := c.Part("detail") + ui.Scroll(k).Scrollbars().Grow(1).FillHeight().MinWidth(0).Children(func() { + ui.Column(k.Part("form")).FillWidth().Pad(16).Gap(10).Children(func() { + if r.readErr != "" { + a.remoteNotice(k.Part("read"), icons.CircleAlert, a.theme.Danger, r.readErr) + } + a.remoteFields(k) + if r.err != "" { + ui.Paragraph(k.Part("error"), r.err, 4).FontSize(a.theme.Metrics.FontSizeS).Color(a.theme.Danger) + } + a.remoteResult(k.Part("result"), language) + }) + }) +} + +// remoteFields declares the connection's fields, each a row of its label and control, with the +// reason a refused one was refused under it. +func (a *App) remoteFields(c ui.C) { + r := &a.remote + f := &r.form + language := a.language() + disabled := r.saving + text := func(key, label, placeholder, help string, field *ui.Field) { + a.remoteRow(c.Part(key), key, label, help, func(k ui.C) { + ui.TextField(k, field, label, placeholder).Grow(1).MinWidth(0).Disabled(disabled) + }) + } + text("name", i18n.Shared(language, "desktop.remote.name"), i18n.Shared(language, "desktop.remote.namePlaceholder"), "", &f.name) + text("host", i18n.Shared(language, "desktop.remote.host"), i18n.Shared(language, "desktop.remote.hostPlaceholder"), i18n.Shared(language, "desktop.remote.hostHelp"), &f.host) + text("port", i18n.Shared(language, "desktop.remote.port"), i18n.Shared(language, "desktop.remote.portPlaceholder"), "", &f.port) + text("user", i18n.Shared(language, "desktop.remote.user"), i18n.Shared(language, "desktop.remote.userPlaceholder"), "", &f.user) + authLabel := i18n.Shared(language, "desktop.remote.authentication") + a.remoteRow(c.Part("authentication"), "authentication", authLabel, i18n.Shared(language, "desktop.remote.authenticationHelp"), func(k ui.C) { + ui.Select(k, &f.authentication, remoteAuthentications, func(way string) string { + return remoteAuthenticationLabel(language, way) + }).Label(authLabel).Grow(1).MinWidth(0).Disabled(disabled) + }) + if f.authentication == core.RemoteAuthenticationPrivateKey { + label := i18n.Shared(language, "desktop.remote.identityFile") + a.remoteRow(c.Part("identityFile"), "identityFile", label, i18n.Shared(language, "desktop.remote.identityFileHelp"), func(k ui.C) { + box := ui.TextField(k, &f.identityFile, label, i18n.Shared(language, "desktop.remote.identityFilePlaceholder")).Grow(1).MinWidth(0).Disabled(disabled). + Action(icons.FolderOpen, i18n.Shared(language, "desktop.remote.choose")) + if box.ActionClicked() { + c.After(a.chooseRemoteIdentity) + } + }) + } + ui.Collapsible(c.Part("advanced"), &f.advanced, i18n.Shared(language, "desktop.remote.advanced"), func() { + k := c.Part("advanced-fields") + ui.Column(k).FillWidth().Gap(10).Children(func() { + text := func(key, label, placeholder, help string, field *ui.Field) { + a.remoteRow(k.Part(key), key, label, help, func(k ui.C) { + ui.TextField(k, field, label, placeholder).Grow(1).MinWidth(0).Disabled(disabled) + }) + } + text("proxyJump", i18n.Shared(language, "desktop.remote.proxyJump"), i18n.Shared(language, "desktop.remote.proxyJumpPlaceholder"), i18n.Shared(language, "desktop.remote.proxyJumpHelp"), &f.proxyJump) + text("connectTimeoutSeconds", i18n.Shared(language, "desktop.remote.timeout"), i18n.Shared(language, "desktop.remote.timeoutPlaceholder"), "", &f.timeout) + text("keepAliveSeconds", i18n.Shared(language, "desktop.remote.keepAlive"), i18n.Shared(language, "desktop.remote.keepAlivePlaceholder"), i18n.Shared(language, "desktop.remote.keepAliveHelp"), &f.keepAlive) + }) + }) +} + +// remoteAuthenticationLabel names way, one of remoteAuthentications. +func remoteAuthenticationLabel(language i18n.Language, way string) string { + switch way { + case core.RemoteAuthenticationAgent: + return i18n.Shared(language, "desktop.remote.auth.agent") + case core.RemoteAuthenticationPrivateKey: + return i18n.Shared(language, "desktop.remote.auth.privateKey") + case core.RemoteAuthenticationPassword: + return i18n.Shared(language, "desktop.remote.auth.password") + } + return i18n.Shared(language, "desktop.remote.auth.auto") +} + +// remoteRow declares one field: its label and ⓘ in the label column, the control beside them, +// and the reason Core refused field under the control. +func (a *App) remoteRow(c ui.C, field, label, help string, control func(ui.C)) { + r := &a.remote + ui.Column(c).FillWidth().Gap(4).Children(func() { + ui.Row(c).FillWidth().Gap(12).Items(ui.Center).Children(func() { + ui.Row(c.Part("label")).Width(remoteLabelWidth).MinHeight(28).Shrink(0).Items(ui.Center).Gap(4).Children(func() { + ui.Text(c, label).Ellipsis().Shrink(1).MinWidth(0) + if help != "" { + a.remoteHelp(c, help) + } + }) + control(c) + }) + if r.fieldErr.field == field { + ui.Row(c.Part("error")).FillWidth().PadSides(0, 0, 0, remoteLabelWidth+12).Children(func() { + ui.Paragraph(c, remoteRefusalText(a.language(), r.fieldErr), 3).FontSize(a.theme.Metrics.FontSizeS).Color(a.theme.Danger) + }) + } + }) +} + +// remoteHelp declares an ⓘ whose tip is help. +func (a *App) remoteHelp(c ui.C, help string) { + ui.Button(c.Part("help"), i18n.Shared(a.language(), "native.moreInformation")).Icon(icons.Info).IconOnly().Ghost(). + Size(18, 18).Shrink(0).Tooltip(help).TooltipOn(ui.TooltipRight) +} + +// remoteNotice declares a line with an icon in color. +func (a *App) remoteNotice(c ui.C, icon gfx.Icon, color gfx.Color, text string) { + ui.Row(c).FillWidth().Gap(8).Items(ui.Start).Children(func() { + ui.Icon(c, icon).Size(16, 16).Shrink(0).Color(color) + ui.Paragraph(c, text, 6).Color(color).Grow(1).MinWidth(0) + }) +} + +// remoteResult declares what the running or last test found: the host's platform and what it has +// for a connection, or why it failed with OpenSSH's own output under it. That output is upstream +// text, shown as Core passed it and never logged. +func (a *App) remoteResult(c ui.C, language i18n.Language) { + r := &a.remote + if r.probe != nil { + a.remoteNotice(c, icons.LoaderCircle, a.colors.Subtle, i18n.Shared(language, "desktop.remote.testing")) + return + } + outcome := r.result + if outcome == nil { + return + } + ui.Column(c).FillWidth().Gap(8).PadTop(6).Children(func() { + ui.Row(c).FillWidth().Height(1).Shrink(0).Background(a.colors.Line) + if outcome.err != nil { + text := i18n.SharedFormat(language, "desktop.remote.probe.error", map[string]string{"reason": outcome.err.Error()}) + var coreErr *core.Error + if errors.As(outcome.err, &coreErr) && coreErr.Code == core.CodeRuntimeMissing { + text = i18n.Shared(language, "desktop.remote.probe.noSSH") + } + a.remoteNotice(c.Part("status"), icons.CircleX, a.theme.Danger, text) + return + } + result := outcome.result + host := result.Host + var system, machine string + if host != nil { + system, machine = host.System, host.Machine + } + switch result.Status { + case core.RemoteProbeConnected: + a.remoteNotice(c.Part("status"), icons.CircleCheck, a.colors.Success, + i18n.SharedFormat(language, "desktop.remote.probe.connected", map[string]string{"system": system, "machine": machine})) + case core.RemoteProbeUnsupportedPlatform: + a.remoteNotice(c.Part("status"), icons.CircleAlert, a.colors.Warning, + i18n.SharedFormat(language, "desktop.remote.probe.unsupported", map[string]string{"system": system, "machine": machine})) + case core.RemoteProbeAuthenticationFailed: + a.remoteNotice(c.Part("status"), icons.CircleX, a.theme.Danger, i18n.Shared(language, "desktop.remote.probe.authenticationFailed")) + case core.RemoteProbeHostKeyRejected: + a.remoteNotice(c.Part("status"), icons.CircleX, a.theme.Danger, i18n.Shared(language, "desktop.remote.probe.hostKeyRejected")) + case core.RemoteProbeUnreachable: + a.remoteNotice(c.Part("status"), icons.CircleX, a.theme.Danger, i18n.Shared(language, "desktop.remote.probe.unreachable")) + default: + a.remoteNotice(c.Part("status"), icons.CircleX, a.theme.Danger, i18n.Shared(language, "desktop.remote.probe.failed")) + } + if host != nil { + a.remoteHostDetails(c.Part("details"), language, *host) + } + if diagnostics := strings.TrimSpace(result.Diagnostics); diagnostics != "" && result.Status != core.RemoteProbeConnected { + ui.Text(c, i18n.Shared(language, "desktop.remote.diagnostics")).FontSize(a.theme.Metrics.FontSizeS).Weight(gfx.WeightSemibold).Color(a.colors.Subtle) + ui.Paragraph(c.Part("diagnostics"), diagnostics, 8).Mono().FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Subtle) + } + }) +} + +// remoteHostDetails declares what the host reported about itself, each item that it reported. +func (a *App) remoteHostDetails(c ui.C, language i18n.Language, host core.RemoteProbedHost) { + details := host.Details + type item struct{ label, value string } + var items []item + if details.HostName != "" { + items = append(items, item{i18n.Shared(language, "desktop.remote.probe.hostName"), details.HostName}) + } + if system := strings.TrimSpace(details.OperatingSystem + " " + details.Kernel); system != "" { + items = append(items, item{i18n.Shared(language, "desktop.remote.probe.os"), system}) + } + if details.CPUCount > 0 { + items = append(items, item{i18n.Shared(language, "desktop.remote.probe.cpu"), strconv.FormatUint(uint64(details.CPUCount), 10)}) + } + if details.MemoryBytes > 0 { + items = append(items, item{i18n.Shared(language, "desktop.remote.probe.memory"), memorySize(language, details.MemoryBytes)}) + } + if details.DiskTotalBytes > 0 { + items = append(items, item{i18n.Shared(language, "desktop.remote.probe.disk"), i18n.SharedFormat(language, "desktop.remote.probe.diskSpace", map[string]string{ + "available": memorySize(language, details.DiskAvailableBytes), + "total": memorySize(language, details.DiskTotalBytes), + })}) + } + if len(items) == 0 { + return + } + ui.Column(c).FillWidth().Gap(4).PadSides(0, 0, 0, 24).Children(func() { + for index, entry := range items { + k := c.KeyInt(index) + ui.Row(k).FillWidth().Gap(12).Items(ui.Center).Children(func() { + ui.Text(k, entry.label).FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Subtle).Width(remoteLabelWidth - 24).Shrink(0).Ellipsis() + ui.Text(k, entry.value).FontSize(a.theme.Metrics.FontSizeS).Ellipsis().Grow(1).MinWidth(0) + }) + } + }) +} + +// remoteFooter declares Delete, or the question whether to delete, then Test Connection, Close and +// Save. +func (a *App) remoteFooter(c ui.C) { + r := &a.remote + language := a.language() + entry := r.entry(r.selected) + if r.confirmDelete && entry != nil { + ui.Text(c, i18n.SharedFormat(language, "desktop.remote.deleteConfirm", map[string]string{"name": entry.Name})).Ellipsis().Shrink(1).MinWidth(0) + if ui.Button(c.Part("delete-confirm"), i18n.Shared(language, "desktop.remote.delete")).Destructive().Disabled(!r.editable()).Clicked() { + c.After(a.removeRemote) + } + if ui.Button(c.Part("delete-cancel"), i18n.Shared(language, "desktop.remote.cancel")).Outline().Clicked() { + c.After(func() { r.confirmDelete = false }) + } + ui.Spacer(c) + return + } + if entry != nil { + if ui.Button(c.Part("delete"), i18n.Shared(language, "desktop.remote.delete")).DestructiveOutline().Disabled(!r.editable()).Clicked() { + c.After(func() { r.confirmDelete = true }) + } + } + ui.Spacer(c) + if r.probe != nil { + if ui.Button(c.Part("stop"), i18n.Shared(language, "desktop.remote.stop")).Outline().Clicked() { + c.After(a.stopRemoteTest) + } + } else if ui.Button(c.Part("test"), i18n.Shared(language, "desktop.remote.test")).Outline(). + Disabled(strings.TrimSpace(r.form.host.Text()) == "").Clicked() { + c.After(a.testRemote) + } + if ui.Button(c.Part("close"), i18n.Shared(language, "desktop.remote.close")).Outline().Clicked() { + c.After(a.closeRemote) + } + label := i18n.Shared(language, "desktop.remote.save") + if r.saving { + label = i18n.Shared(language, "desktop.remote.saving") + } + if ui.Button(c.Part("save"), label).Disabled(!r.editable() || !r.dirty()).Clicked() { + c.After(a.saveRemote) + } +} diff --git a/desktop/internal/workbench/root.go b/desktop/internal/workbench/root.go index 37b6d6097..5eee9e04f 100644 --- a/desktop/internal/workbench/root.go +++ b/desktop/internal/workbench/root.go @@ -299,13 +299,15 @@ func (a *App) runShortcut(id string, view *editorview.View, term *terminal) { // overlays declares everything the window shows over the workbench: the dialogs, the search // and navigation popups, the language popups, the plugin prompts, the import of an -// earlier client's plugin secrets, the Git dialogs, the New Project dialog and the questions -// Git asks while it authenticates. Each dialog's +// earlier client's plugin secrets, the Git dialogs, the New Project dialog, the Remote +// Development window and the questions Git or a remote connection's SSH client asks while it +// authenticates. Each dialog's // state stays with its own file; the toasts are declared last, over all of them. func (a *App) overlays(c ui.C) { a.scratchPopup(c) a.recentFilesPopup(c) a.cloneView(c) + a.remoteView(c) if a.project != nil { a.everywherePopup(c) a.navigationPopup(c) diff --git a/desktop/internal/workbench/welcome_view.go b/desktop/internal/workbench/welcome_view.go index 8c255cd13..234e2740d 100644 --- a/desktop/internal/workbench/welcome_view.go +++ b/desktop/internal/workbench/welcome_view.go @@ -118,6 +118,9 @@ func (a *App) welcomeContent(c ui.C) { if menu.Item(i18n.Shared(a.language(), "desktop.clone.title")).Clicked() { c.After(func() { a.openClone(surfaceMenu) }) } + if menu.Item(i18n.Shared(a.language(), "desktop.remote.menuItem")).Clicked() { + c.After(func() { a.openRemote(surfaceMenu) }) + } }) }) ui.Row(c).FillWidth().Height(1).Shrink(0).PadX(12).Children(func() { diff --git a/docs/assets/remote-connections/README.md b/docs/assets/remote-connections/README.md new file mode 100644 index 000000000..e71f11a5c --- /dev/null +++ b/docs/assets/remote-connections/README.md @@ -0,0 +1,18 @@ +# 远程开发连接窗口(#2231)无头测试截图 + +来自生产 Viva Page 的无头渲染。连接列表由真实 Core 写入测试临时偏好目录;“测试连接”的结果由测试替换的内核直接返回固定的主机信息,不启动 OpenSSH,密码询问由测试直接放入提问队列。截图覆盖深色与浅色主题、中文与英文界面,用于确认: + +- 保存第二个连接后,列表高亮的是表单正在编辑的连接;测试成功后显示主机名、系统、CPU 数、内存和主目录磁盘; +- 主机字段填了 `user@host` 时,Core 拒绝的原因显示在主机字段下方,没有写入列表; +- OpenSSH 询问密码时,窗口上方弹出“SSH 身份验证”,提示原文照搬,输入框为密码框,说明答案只交给这次连接、不会保存。 + +截图不代表 macOS/Windows 原生窗口验收。 + +| 场景 | 浅色英文 | 深色中文 | +| --- | --- | --- | +| 测试连接成功 | [浅色英文](remote-connections-tested-light-en-US.png) | [深色中文](remote-connections-tested-dark-zh-CN.png) | +| 主机字段被拒绝 | [浅色英文](remote-connections-refused-light-en-US.png) | [深色中文](remote-connections-refused-dark-zh-CN.png) | +| SSH 密码询问 | [浅色英文](remote-connections-password-light-en-US.png) | [深色中文](remote-connections-password-dark-zh-CN.png) | + +复验:从仓库根目录设置绝对路径 `LITHE_VISUAL_OUTPUT_DIR="$(pwd)/docs/assets/remote-connections"`,在 `desktop/` 下通过 +`../scripts/desktop/desktop-go.sh test -tags vivahead,lithevisual ./internal/workbench -run '^TestVisualRemoteConnections$' -count=1 -timeout 180s` 生成。 diff --git a/docs/assets/remote-connections/remote-connections-password-dark-zh-CN.png b/docs/assets/remote-connections/remote-connections-password-dark-zh-CN.png new file mode 100644 index 000000000..131e4915e Binary files /dev/null and b/docs/assets/remote-connections/remote-connections-password-dark-zh-CN.png differ diff --git a/docs/assets/remote-connections/remote-connections-password-light-en-US.png b/docs/assets/remote-connections/remote-connections-password-light-en-US.png new file mode 100644 index 000000000..78d5f2c54 Binary files /dev/null and b/docs/assets/remote-connections/remote-connections-password-light-en-US.png differ diff --git a/docs/assets/remote-connections/remote-connections-refused-dark-zh-CN.png b/docs/assets/remote-connections/remote-connections-refused-dark-zh-CN.png new file mode 100644 index 000000000..cd0d3147d Binary files /dev/null and b/docs/assets/remote-connections/remote-connections-refused-dark-zh-CN.png differ diff --git a/docs/assets/remote-connections/remote-connections-refused-light-en-US.png b/docs/assets/remote-connections/remote-connections-refused-light-en-US.png new file mode 100644 index 000000000..80942ebca Binary files /dev/null and b/docs/assets/remote-connections/remote-connections-refused-light-en-US.png differ diff --git a/docs/assets/remote-connections/remote-connections-tested-dark-zh-CN.png b/docs/assets/remote-connections/remote-connections-tested-dark-zh-CN.png new file mode 100644 index 000000000..39dfe7e37 Binary files /dev/null and b/docs/assets/remote-connections/remote-connections-tested-dark-zh-CN.png differ diff --git a/docs/assets/remote-connections/remote-connections-tested-light-en-US.png b/docs/assets/remote-connections/remote-connections-tested-light-en-US.png new file mode 100644 index 000000000..769da3c51 Binary files /dev/null and b/docs/assets/remote-connections/remote-connections-tested-light-en-US.png differ diff --git a/scripts/desktop/build-desktop-core.sh b/scripts/desktop/build-desktop-core.sh index 029844e1d..735e09a72 100755 --- a/scripts/desktop/build-desktop-core.sh +++ b/scripts/desktop/build-desktop-core.sh @@ -306,10 +306,11 @@ PINNED_CORE_REPOSITORY="https://github.com/Lithe-IDEA/Lithe-core-rust.git" # code for a workspace the user has not trusted (#2208). # Lithe-core-rust main at 94408ca: #142 returns Git's authentication failure without asking to # retry once a credential question was cancelled or expired unanswered (#2231). -# Lithe-core-rust main at 7c1cd55: #143 shares one peer_uid implementation across the remote -# crate; #144 lets toolchains.editCatalog add and remove trustedLocations, refusing filesystem -# roots and lists over 256 entries (#2207). -PINNED_CORE_REVISION="7c1cd55e6947d41ce8cb30f569cd896a61bf6bd5" +# Lithe-core-rust feat/2231-saved-connections at d1a5b82 (#145, on main 7c1cd55): #143 shares the +# Unix socket peer check, #144 adds and removes single trusted locations (#2207), #145 keeps the +# saved SSH connections (remote.connections, remote.editConnections) and refuses a field of a +# connection by name. Replace with the main commit once #145 is merged. +PINNED_CORE_REVISION="d1a5b829ef508f3b1a692a7d05df66004fe87b08" PROFILE="debug" CHECKOUT_ONLY="no" while [[ $# -gt 0 ]]; do diff --git a/shared/i18n/features/remote-connections.json b/shared/i18n/features/remote-connections.json new file mode 100644 index 000000000..3cabe2fc1 --- /dev/null +++ b/shared/i18n/features/remote-connections.json @@ -0,0 +1,806 @@ +{ + "schemaVersion": 1, + "messages": [ + { + "id": "desktop.remote.title", + "description": "Remote Development window: title", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.menuItem", + "description": "Welcome screen More menu and project menu: item that opens the Remote Development window", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.saved", + "description": "Remote Development window: heading of the list of saved SSH connections", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.storageHelp", + "description": "Remote Development window: tip of the ⓘ beside the list heading: where the list is kept and what it never holds", + "platforms": [ + "desktop" + ], + "parameters": { + "path": "string" + } + }, + { + "id": "desktop.remote.new", + "description": "Remote Development window: accessible label and tooltip of the + button that starts a new connection", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.empty", + "description": "Remote Development window: shown in place of the list when no connection is saved", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.name", + "description": "Remote Development window: label of the connection name field", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.namePlaceholder", + "description": "Remote Development window: placeholder of the name field", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.host", + "description": "Remote Development window: label of the host field", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.hostPlaceholder", + "description": "Remote Development window: placeholder of the host field", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.hostHelp", + "description": "Remote Development window: tip of the ⓘ beside the host field", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.port", + "description": "Remote Development window: label of the port field", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.portPlaceholder", + "description": "Remote Development window: placeholder of the port field while it is empty", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.user", + "description": "Remote Development window: label of the user name field", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.userPlaceholder", + "description": "Remote Development window: placeholder of the user name field while it is empty", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.authentication", + "description": "Remote Development window: label of the authentication method picker", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.authenticationHelp", + "description": "Remote Development window: tip of the ⓘ beside the authentication picker", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.auth.auto", + "description": "Remote Development window: authentication choice: let OpenSSH decide", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.auth.agent", + "description": "Remote Development window: authentication choice: keys held by ssh-agent", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.auth.privateKey", + "description": "Remote Development window: authentication choice: one private key file", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.auth.password", + "description": "Remote Development window: authentication choice: a password asked when connecting", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.identityFile", + "description": "Remote Development window: label of the private key path field, also the title of its file picker", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.identityFilePlaceholder", + "description": "Remote Development window: placeholder of the private key path field", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.identityFileHelp", + "description": "Remote Development window: tip of the ⓘ beside the private key path field", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.choose", + "description": "Remote Development window: accessible label of the button that opens the file picker for the private key", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.advanced", + "description": "Remote Development window: header of the collapsible section with the proxy jump, timeout and keep-alive fields", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.proxyJump", + "description": "Remote Development window: label of the proxy jump (bastion host) field", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.proxyJumpPlaceholder", + "description": "Remote Development window: placeholder of the proxy jump field", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.proxyJumpHelp", + "description": "Remote Development window: tip of the ⓘ beside the proxy jump field", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.timeout", + "description": "Remote Development window: label of the connect timeout field, in seconds", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.timeoutPlaceholder", + "description": "Remote Development window: placeholder of the connect timeout field while it is empty; 15 is the timeout Lithe applies", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.keepAlive", + "description": "Remote Development window: label of the keep-alive interval field, in seconds", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.keepAlivePlaceholder", + "description": "Remote Development window: placeholder of the keep-alive field while it is empty", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.keepAliveHelp", + "description": "Remote Development window: tip of the ⓘ beside the keep-alive field", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.save", + "description": "Remote Development window: button that saves the form", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.saving", + "description": "Remote Development window: save button while the list is being written", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.delete", + "description": "Remote Development window: button that deletes the selected connection, and the button that confirms it", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.deleteConfirm", + "description": "Remote Development window: question in the footer after Delete was clicked", + "platforms": [ + "desktop" + ], + "parameters": { + "name": "string" + } + }, + { + "id": "desktop.remote.cancel", + "description": "Remote Development window: button that takes back the delete question", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.close", + "description": "Remote Development window: button that closes the window; what was not saved is dropped", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.test", + "description": "Remote Development window: button that connects with what the form holds, saved or not", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.testing", + "description": "Remote Development window: shown while a test connection runs", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.stop", + "description": "Remote Development window: button that stops the running test", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.probe.connected", + "description": "Remote Development window: test result: connected; system and machine are what uname printed on the host", + "platforms": [ + "desktop" + ], + "parameters": { + "system": "string", + "machine": "string" + } + }, + { + "id": "desktop.remote.probe.unsupported", + "description": "Remote Development window: test result: connected, but Lithe has no remote server build for the platform", + "platforms": [ + "desktop" + ], + "parameters": { + "system": "string", + "machine": "string" + } + }, + { + "id": "desktop.remote.probe.authenticationFailed", + "description": "Remote Development window: test result: the server refused the keys or password offered", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.probe.hostKeyRejected", + "description": "Remote Development window: test result: the host key was declined or differs from known_hosts", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.probe.unreachable", + "description": "Remote Development window: test result: no connection could be made", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.probe.failed", + "description": "Remote Development window: test result: any other failure; OpenSSH output follows", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.probe.error", + "description": "Remote Development window: test result: the test could not run; reason is the error", + "platforms": [ + "desktop" + ], + "parameters": { + "reason": "string" + } + }, + { + "id": "desktop.remote.probe.noSSH", + "description": "Remote Development window: test result: no ssh executable was found", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.probe.hostName", + "description": "Remote Development window: test result detail: label of the host name the host reported", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.probe.os", + "description": "Remote Development window: test result detail: label of the operating system and kernel", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.probe.cpu", + "description": "Remote Development window: test result detail: label of the number of CPUs", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.probe.memory", + "description": "Remote Development window: test result detail: label of the total memory", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.probe.disk", + "description": "Remote Development window: test result detail: label of the disk space of the home directory", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.probe.diskSpace", + "description": "Remote Development window: test result detail: free and total disk space, each a formatted size", + "platforms": [ + "desktop" + ], + "parameters": { + "available": "string", + "total": "string" + } + }, + { + "id": "desktop.remote.diagnostics", + "description": "Remote Development window: heading over the OpenSSH output of a failed test", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.error.required", + "description": "Remote Development window: under a field Core refused: it must not be empty", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.error.invalid", + "description": "Remote Development window: under a field Core refused: generic invalid value", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.error.fieldTooLong", + "description": "Remote Development window: under a field Core refused: longer than 1024 bytes", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.error.nameTooLong", + "description": "Remote Development window: under the name field: longer than 128 characters", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.error.duplicate", + "description": "Remote Development window: a value another saved connection already uses", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.error.nameDuplicate", + "description": "Remote Development window: under the name field: another connection has the same name, ignoring letter case", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.error.full", + "description": "Remote Development window: the list already holds 128 connections", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.error.unknown", + "description": "Remote Development window: the connection edited was deleted meanwhile", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.error.hostInvalid", + "description": "Remote Development window: under the host field: it holds a user, a port, a URL or other characters", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.error.portInvalid", + "description": "Remote Development window: under the port field", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.error.userInvalid", + "description": "Remote Development window: under the user field", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.error.proxyJumpInvalid", + "description": "Remote Development window: under the proxy jump field", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.error.timeoutInvalid", + "description": "Remote Development window: under the connect timeout field", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.error.keepAliveInvalid", + "description": "Remote Development window: under the keep-alive field", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.error.textInvalid", + "description": "Remote Development window: under the name or private key field: leading or trailing spaces or control characters", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.damaged", + "description": "Remote Development window: the saved list cannot be read; nothing is saved until it is repaired", + "platforms": [ + "desktop" + ], + "parameters": { + "path": "string" + } + }, + { + "id": "desktop.remote.conflict", + "description": "Remote Development window: the list changed on disk since it was read; it was read again and nothing was written", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.readFailed", + "description": "Remote Development window: the saved list could not be read; reason is the error", + "platforms": [ + "desktop" + ], + "parameters": { + "reason": "string" + } + }, + { + "id": "desktop.remote.saveFailed", + "description": "Remote Development window: the connection could not be saved; reason is the error", + "platforms": [ + "desktop" + ], + "parameters": { + "reason": "string" + } + }, + { + "id": "desktop.remote.deleteFailed", + "description": "Remote Development window: the connection could not be deleted; reason is the error", + "platforms": [ + "desktop" + ], + "parameters": { + "reason": "string" + } + }, + { + "id": "desktop.remote.chooseFailed", + "description": "Remote Development window: the file picker failed; reason is the error", + "platforms": [ + "desktop" + ], + "parameters": { + "reason": "string" + } + }, + { + "id": "desktop.remote.unavailable", + "description": "Remote Development window: there is no preference directory to keep the list in", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remoteAuth.title", + "description": "SSH authentication dialog of a remote connection: title while the SSH client of a remote connection waits for an answer", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remoteAuth.secretHint", + "description": "SSH authentication dialog of a remote connection: note under a password or passphrase field", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remoteAuth.refused", + "description": "SSH authentication dialog of a remote connection: notice when Core refused the answer", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remoteAuth.failed", + "description": "SSH authentication dialog of a remote connection: notice when the answer could not be passed on; reason is the error", + "platforms": [ + "desktop" + ], + "parameters": { + "reason": "string" + } + } + ], + "locales": { + "en-US": { + "desktop.remote.title": "Remote Development", + "desktop.remote.menuItem": "Remote Development…", + "desktop.remote.saved": "Saved Connections", + "desktop.remote.storageHelp": "Kept on this computer in {path}. Passwords and the contents of private keys are never saved.", + "desktop.remote.new": "New Connection", + "desktop.remote.empty": "No saved connections yet. Fill in the form and save it.", + "desktop.remote.name": "Name", + "desktop.remote.namePlaceholder": "Defaults to the host", + "desktop.remote.host": "Host", + "desktop.remote.hostPlaceholder": "build.example.com or an SSH config alias", + "desktop.remote.hostHelp": "A host name, an IP address, or a Host alias from ~/.ssh/config. OpenSSH applies its configuration as usual: a field left empty here does not override it.", + "desktop.remote.port": "Port", + "desktop.remote.portPlaceholder": "Auto (SSH config, otherwise 22)", + "desktop.remote.user": "User", + "desktop.remote.userPlaceholder": "Auto (SSH config, otherwise your local user name)", + "desktop.remote.authentication": "Authentication", + "desktop.remote.authenticationHelp": "Auto: as your SSH config and ssh-agent decide. SSH agent: only keys held by ssh-agent. Private key: only the key file you choose; its passphrase is asked when connecting. Password: asked when connecting. Lithe never saves an answer.", + "desktop.remote.auth.auto": "Auto", + "desktop.remote.auth.agent": "SSH agent", + "desktop.remote.auth.privateKey": "Private key file", + "desktop.remote.auth.password": "Password", + "desktop.remote.identityFile": "Private Key", + "desktop.remote.identityFilePlaceholder": "~/.ssh/id_ed25519", + "desktop.remote.identityFileHelp": "Only the path is saved and handed to OpenSSH; Lithe never reads the key.", + "desktop.remote.choose": "Choose File…", + "desktop.remote.advanced": "Advanced", + "desktop.remote.proxyJump": "Proxy Jump", + "desktop.remote.proxyJumpPlaceholder": "None (or SSH config)", + "desktop.remote.proxyJumpHelp": "Hosts to connect through first, as OpenSSH ProxyJump: [user@]host[:port], several separated by commas.", + "desktop.remote.timeout": "Connect Timeout (s)", + "desktop.remote.timeoutPlaceholder": "Auto (15)", + "desktop.remote.keepAlive": "Keep-Alive (s)", + "desktop.remote.keepAlivePlaceholder": "Auto (SSH config)", + "desktop.remote.keepAliveHelp": "How often OpenSSH checks that the server still answers (ServerAliveInterval), so a dropped network is noticed.", + "desktop.remote.save": "Save", + "desktop.remote.saving": "Saving…", + "desktop.remote.delete": "Delete", + "desktop.remote.deleteConfirm": "Delete “{name}”?", + "desktop.remote.cancel": "Cancel", + "desktop.remote.close": "Close", + "desktop.remote.test": "Test Connection", + "desktop.remote.testing": "Connecting… OpenSSH may ask for a password or to confirm the host key.", + "desktop.remote.stop": "Stop", + "desktop.remote.probe.connected": "Connected: {system} {machine}", + "desktop.remote.probe.unsupported": "Connected to {system} {machine}, but Lithe’s remote server does not run there yet: only x86_64 and arm64 Linux are supported.", + "desktop.remote.probe.authenticationFailed": "Authentication failed: the server did not accept the keys or password offered.", + "desktop.remote.probe.hostKeyRejected": "The host key was not accepted: it was declined, or it differs from the one in known_hosts.", + "desktop.remote.probe.unreachable": "Cannot reach the host: check the host, the port and the network.", + "desktop.remote.probe.failed": "The connection failed.", + "desktop.remote.probe.error": "Cannot test the connection: {reason}", + "desktop.remote.probe.noSSH": "No ssh client found. Install the OpenSSH client first.", + "desktop.remote.probe.hostName": "Host name", + "desktop.remote.probe.os": "System", + "desktop.remote.probe.cpu": "CPUs", + "desktop.remote.probe.memory": "Memory", + "desktop.remote.probe.disk": "Disk (home)", + "desktop.remote.probe.diskSpace": "{available} free of {total}", + "desktop.remote.diagnostics": "OpenSSH Output", + "desktop.remote.error.required": "Required.", + "desktop.remote.error.invalid": "This value is not accepted.", + "desktop.remote.error.fieldTooLong": "Too long: at most 1024 bytes.", + "desktop.remote.error.nameTooLong": "Too long: at most 128 characters.", + "desktop.remote.error.duplicate": "Another saved connection already uses this.", + "desktop.remote.error.nameDuplicate": "Another saved connection already has this name.", + "desktop.remote.error.full": "At most 128 connections can be saved. Delete one first.", + "desktop.remote.error.unknown": "This connection no longer exists.", + "desktop.remote.error.hostInvalid": "Enter only a host name, an IP address or an SSH alias; put the user and the port in their own fields.", + "desktop.remote.error.portInvalid": "Enter a port from 1 to 65535.", + "desktop.remote.error.userInvalid": "This user name has characters SSH does not accept.", + "desktop.remote.error.proxyJumpInvalid": "Use [user@]host[:port], several separated by commas.", + "desktop.remote.error.timeoutInvalid": "Enter 1 to 600 seconds.", + "desktop.remote.error.keepAliveInvalid": "Enter 1 to 3600 seconds.", + "desktop.remote.error.textInvalid": "Remove the spaces at either end and any control characters.", + "desktop.remote.damaged": "The saved connections in {path} cannot be read. Repair or remove the file before saving.", + "desktop.remote.conflict": "The saved connections changed elsewhere and were read again. Save once more.", + "desktop.remote.readFailed": "Cannot read the saved connections: {reason}", + "desktop.remote.saveFailed": "Cannot save the connection: {reason}", + "desktop.remote.deleteFailed": "Cannot delete the connection: {reason}", + "desktop.remote.chooseFailed": "Cannot open the file picker: {reason}", + "desktop.remote.unavailable": "There is no preference folder to keep connections in.", + "desktop.remoteAuth.title": "SSH Authentication", + "desktop.remoteAuth.secretHint": "The answer goes only to this SSH connection. Lithe does not keep it.", + "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.failed": "Cannot pass the answer to SSH: {reason}" + }, + "zh-CN": { + "desktop.remote.title": "远程开发", + "desktop.remote.menuItem": "远程开发…", + "desktop.remote.saved": "已保存的连接", + "desktop.remote.storageHelp": "保存在本机的 {path}。不会保存密码和私钥内容。", + "desktop.remote.new": "新建连接", + "desktop.remote.empty": "还没有保存的连接。填写右侧表单后保存。", + "desktop.remote.name": "名称", + "desktop.remote.namePlaceholder": "默认使用主机名", + "desktop.remote.host": "主机", + "desktop.remote.hostPlaceholder": "build.example.com 或 SSH 配置里的别名", + "desktop.remote.hostHelp": "主机名、IP 地址或 ~/.ssh/config 里的 Host 别名。OpenSSH 照常读取它的配置;这里留空的字段不会覆盖配置里的值。", + "desktop.remote.port": "端口", + "desktop.remote.portPlaceholder": "自动(SSH 配置,否则 22)", + "desktop.remote.user": "用户名", + "desktop.remote.userPlaceholder": "自动(SSH 配置,否则本机用户名)", + "desktop.remote.authentication": "身份验证", + "desktop.remote.authenticationHelp": "自动:按 SSH 配置和 ssh-agent 决定。SSH Agent:只用 ssh-agent 里的密钥。私钥文件:只用选定的私钥,口令在连接时询问。密码:在连接时询问。Lithe 不保存任何回答。", + "desktop.remote.auth.auto": "自动", + "desktop.remote.auth.agent": "SSH Agent", + "desktop.remote.auth.privateKey": "私钥文件", + "desktop.remote.auth.password": "密码", + "desktop.remote.identityFile": "私钥", + "desktop.remote.identityFilePlaceholder": "~/.ssh/id_ed25519", + "desktop.remote.identityFileHelp": "只保存路径并交给 OpenSSH;Lithe 不读取私钥内容。", + "desktop.remote.choose": "选择文件…", + "desktop.remote.advanced": "高级", + "desktop.remote.proxyJump": "跳板机", + "desktop.remote.proxyJumpPlaceholder": "无(或按 SSH 配置)", + "desktop.remote.proxyJumpHelp": "先经过这些主机再连接,等同 OpenSSH 的 ProxyJump:[用户@]主机[:端口],多个用逗号分隔。", + "desktop.remote.timeout": "连接超时(秒)", + "desktop.remote.timeoutPlaceholder": "自动(15)", + "desktop.remote.keepAlive": "保活间隔(秒)", + "desktop.remote.keepAlivePlaceholder": "自动(SSH 配置)", + "desktop.remote.keepAliveHelp": "OpenSSH 每隔多久确认一次服务器仍有响应(ServerAliveInterval),以便发现网络已断开。", + "desktop.remote.save": "保存", + "desktop.remote.saving": "正在保存…", + "desktop.remote.delete": "删除", + "desktop.remote.deleteConfirm": "删除“{name}”?", + "desktop.remote.cancel": "取消", + "desktop.remote.close": "关闭", + "desktop.remote.test": "测试连接", + "desktop.remote.testing": "正在连接…OpenSSH 可能会询问密码或请你确认主机密钥。", + "desktop.remote.stop": "停止", + "desktop.remote.probe.connected": "已连接:{system} {machine}", + "desktop.remote.probe.unsupported": "已连接到 {system} {machine},但 Lithe 远程服务目前不支持该平台:只支持 x86_64 和 arm64 的 Linux。", + "desktop.remote.probe.authenticationFailed": "身份验证失败:服务器没有接受提供的密钥或密码。", + "desktop.remote.probe.hostKeyRejected": "主机密钥没有通过验证:你拒绝了它,或者它与 known_hosts 里记录的不一致。", + "desktop.remote.probe.unreachable": "无法连接到主机:请检查主机、端口和网络。", + "desktop.remote.probe.failed": "连接失败。", + "desktop.remote.probe.error": "无法测试连接:{reason}", + "desktop.remote.probe.noSSH": "找不到 ssh 客户端,请先安装 OpenSSH 客户端。", + "desktop.remote.probe.hostName": "主机名", + "desktop.remote.probe.os": "系统", + "desktop.remote.probe.cpu": "CPU 数", + "desktop.remote.probe.memory": "内存", + "desktop.remote.probe.disk": "磁盘(主目录)", + "desktop.remote.probe.diskSpace": "可用 {available},共 {total}", + "desktop.remote.diagnostics": "OpenSSH 输出", + "desktop.remote.error.required": "必填。", + "desktop.remote.error.invalid": "这个值不被接受。", + "desktop.remote.error.fieldTooLong": "太长:最多 1024 字节。", + "desktop.remote.error.nameTooLong": "太长:最多 128 个字符。", + "desktop.remote.error.duplicate": "另一个已保存的连接已在使用这个值。", + "desktop.remote.error.nameDuplicate": "已有同名的连接(不区分大小写)。", + "desktop.remote.error.full": "最多保存 128 个连接,请先删除一个。", + "desktop.remote.error.unknown": "这个连接已不存在。", + "desktop.remote.error.hostInvalid": "只填主机名、IP 地址或 SSH 别名;用户名和端口请填到各自的字段。", + "desktop.remote.error.portInvalid": "请填 1 到 65535 之间的端口。", + "desktop.remote.error.userInvalid": "用户名含有 SSH 不接受的字符。", + "desktop.remote.error.proxyJumpInvalid": "格式为 [用户@]主机[:端口],多个用逗号分隔。", + "desktop.remote.error.timeoutInvalid": "请填 1 到 600 秒。", + "desktop.remote.error.keepAliveInvalid": "请填 1 到 3600 秒。", + "desktop.remote.error.textInvalid": "请去掉首尾空格和控制字符。", + "desktop.remote.damaged": "无法读取 {path} 里保存的连接。修复或删除这个文件之前不能保存。", + "desktop.remote.conflict": "已保存的连接在别处被修改过,已重新读取,请再保存一次。", + "desktop.remote.readFailed": "无法读取已保存的连接:{reason}", + "desktop.remote.saveFailed": "无法保存连接:{reason}", + "desktop.remote.deleteFailed": "无法删除连接:{reason}", + "desktop.remote.chooseFailed": "无法打开文件选择器:{reason}", + "desktop.remote.unavailable": "没有可以保存连接的偏好设置目录。", + "desktop.remoteAuth.title": "SSH 身份验证", + "desktop.remoteAuth.secretHint": "回答只交给这次 SSH 连接,Lithe 不会保存。", + "desktop.remoteAuth.refused": "SSH 没有接受这个回答:回答最多 8192 字节,且不能包含换行。这个问题已取消。", + "desktop.remoteAuth.failed": "无法把回答交给 SSH:{reason}" + } + } +} diff --git a/shared/platform-feature-matrix/features/remote-connections.json b/shared/platform-feature-matrix/features/remote-connections.json new file mode 100644 index 000000000..c75eaf056 --- /dev/null +++ b/shared/platform-feature-matrix/features/remote-connections.json @@ -0,0 +1,35 @@ +{ + "id": "remote-connections", + "area": "工作区", + "group": "远程开发", + "capability": "保存 SSH 连接并测试连接,在窗口中回答 SSH 的密码和口令询问", + "macos": { + "implementationStatus": "implemented", + "verificationStatus": "pending", + "evidence": [ + "desktop/internal/core/remote.go", + "desktop/internal/core/remote_test.go", + "desktop/internal/remoteconn/remoteconn.go", + "desktop/internal/remoteconn/remoteconn_test.go", + "desktop/internal/workbench/remote.go", + "desktop/internal/workbench/remote_view.go", + "desktop/internal/workbench/remote_test.go", + "desktop/internal/workbench/remote_connections_visual_test.go", + "desktop/internal/workbench/git_auth.go" + ] + }, + "windows": { + "implementationStatus": "implemented", + "verificationStatus": "pending", + "evidence": [ + "desktop/internal/core/remote.go", + "desktop/internal/remoteconn/remoteconn.go", + "desktop/internal/workbench/remote.go", + "desktop/internal/workbench/remote_view.go", + "desktop/internal/workbench/git_auth.go" + ] + }, + "owner": "Remote", + "verification": "从欢迎页“更多”菜单和标题栏项目菜单打开“远程开发”:新建连接只填主机,保存后列表以主机名命名并选中这一行;改名称和端口后保存,列表与偏好目录 remote/connections.json 同步;删除先在底部确认。主机填 user@host、端口填非数字时,错误显示在对应字段下且不写文件。对一台 Linux SSH 主机分别用 SSH Agent、私钥文件和密码测试连接:密码和带口令私钥的询问出现在窗口中,输入以圆点显示,取消或关闭窗口立即停止测试且不再追问;成功后显示系统、架构、CPU、内存和主目录磁盘。首次连接时 OpenSSH 确认主机指纹的询问同样出现在窗口中,由用户回答,Lithe 不替用户接受;拒绝指纹或指纹已改变时测试失败并说明原因。日志只有 remote.connections.open、remote.connection.new/select/save/remove/test/test.stop 和 remote.authentication.answer/cancel 等动作,不含主机、用户名、私钥路径、询问原文或答案。", + "notes": "Viva:连接列表的格式和字段规则在 Core(remote.connections、remote.editConnections),桌面端只读写偏好目录里的 remote/connections.json,按读取时的字节原子写回 Core 返回的文档,文件被改过时不覆盖;测试连接由 Core 运行 PATH 中的 OpenSSH,SSH 询问经 SSH_ASKPASS 指向 lithe 可执行文件的助手模式回到窗口,和 Git 认证共用同一个提问队列。Lithe 只把私钥路径交给 OpenSSH,不读取私钥内容,也不接受粘贴的私钥。macOS 用无头截图和真实 Core 的单元测试覆盖;Windows 上 OpenSSH 调用 GUI 子系统助手读取答案仍待实机验证。打开远程项目、文件夹选择和远端服务部署见 remote-development-workspace,仍未实现。" +}