diff --git a/desktop/internal/core/gitauth.go b/desktop/internal/core/gitauth.go index 484953d28..41dfbc020 100644 --- a/desktop/internal/core/gitauth.go +++ b/desktop/internal/core/gitauth.go @@ -36,6 +36,13 @@ type GitAuthChallenge struct { // Remote says the question comes from the SSH client of a remote connection (RemoteProbe), // not from Git: it is answered with RemoteAuthRespond. Remote bool + // Kind is what a Remote question asks for, one of the RemoteQuestion kinds; Core classifies + // OpenSSH's English wording, so the window can show a fitting form. Empty for Git. + Kind RemoteQuestionKind + // KeyType and Fingerprint name the unknown host key of a RemoteQuestionHostKey question, for + // example "ED25519" and "SHA256:…"; empty when OpenSSH did not print them. + KeyType string + Fingerprint string // Done is closed once the request that asked has returned; no answer reaches it after that. Done <-chan struct{} } @@ -43,6 +50,23 @@ type GitAuthChallenge struct { // GitRetryAnswer is the answer to a Retry challenge that retries the transfer. const GitRetryAnswer = "retry" +// RemoteQuestionKind is what an OpenSSH question of a remote connection asks for. +type RemoteQuestionKind string + +// The kinds Core tells apart. Any other wording is RemoteQuestionOther, shown as asked. +const ( + // RemoteQuestionHostKey asks to accept ("yes") or decline ("no") an unknown host key. + RemoteQuestionHostKey RemoteQuestionKind = "hostKey" + // RemoteQuestionPassword asks for the account's password. + RemoteQuestionPassword RemoteQuestionKind = "password" + // RemoteQuestionPassphrase asks for a private key's passphrase. + RemoteQuestionPassphrase RemoteQuestionKind = "passphrase" + // RemoteQuestionCode asks for a one-time or verification code. + RemoteQuestionCode RemoteQuestionKind = "code" + // RemoteQuestionOther is any other question. + RemoteQuestionOther RemoteQuestionKind = "other" +) + type gitAuthenticationKey struct{} // WithGitAuthentication returns a context whose Git requests may ask the user for credentials: @@ -83,6 +107,9 @@ func gitAuthenticationObserver(prompt func(GitAuthChallenge), done <-chan struct Retry bool `json:"retry"` Attempt int `json:"attempt"` WorkingDirectory string `json:"workingDirectory"` + Kind string `json:"kind"` + KeyType string `json:"keyType"` + Fingerprint string `json:"fingerprint"` } if json.Unmarshal(raw, &event) == nil && event.Type == "authentication" && event.RequestID != "" { prompt(GitAuthChallenge{ @@ -92,6 +119,9 @@ func gitAuthenticationObserver(prompt func(GitAuthChallenge), done <-chan struct Retry: event.Retry, Attempt: event.Attempt, WorkingDirectory: event.WorkingDirectory, + Kind: RemoteQuestionKind(event.Kind), + KeyType: event.KeyType, + Fingerprint: event.Fingerprint, Done: done, }) } diff --git a/desktop/internal/core/remote.go b/desktop/internal/core/remote.go index 8a9898bba..adaddd59a 100644 --- a/desktop/internal/core/remote.go +++ b/desktop/internal/core/remote.go @@ -62,6 +62,9 @@ type SavedRemoteConnection struct { Group string `json:"group,omitempty"` // RecentFolders are the host folders opened over the entry, the latest first. RecentFolders []string `json:"recentFolders,omitempty"` + // LastConnectedAt is when a session last opened over the entry, in seconds since the Unix + // epoch; 0 when none has. Changing the entry's target clears it. + LastConnectedAt int64 `json:"lastConnectedAt,omitempty"` } // RemoteConnectionColor is an accent color Core accepts for a saved connection. The client picks @@ -127,31 +130,60 @@ type RemoteConnectionFolder struct { Path string `json:"path"` } -// RemoteConnectionEdit is exactly one of Save, Remove and RememberFolder. +// RemoteConnectionImport adds Entries in order, each checked as a save without an ID; a name +// already taken gets the first free " (2)" to " (256)" suffix. Fills give saved entries a color +// or a group only where they have none. The first refusal leaves the list as it was. +type RemoteConnectionImport struct { + Entries []RemoteConnectionSave `json:"entries,omitempty"` + Fills []RemoteConnectionFill `json:"fills,omitempty"` +} + +// RemoteConnectionFill gives the entry ID the Color and the Group it lacks. +type RemoteConnectionFill struct { + ID string `json:"id"` + Color RemoteConnectionColor `json:"color,omitempty"` + Group string `json:"group,omitempty"` +} + +// RemoteConnectionEdit is exactly one of its fields. MarkConnected records the current time as +// the entry's LastConnectedAt. type RemoteConnectionEdit struct { Save *RemoteConnectionSave `json:"save,omitempty"` Remove *RemoteConnectionID `json:"remove,omitempty"` RememberFolder *RemoteConnectionFolder `json:"rememberFolder,omitempty"` + MarkConnected *RemoteConnectionID `json:"markConnected,omitempty"` + Import *RemoteConnectionImport `json:"import,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. +// when the edit changed nothing; ID names the entry a save wrote, and IDs the entries an import +// added, in order. type RemoteConnectionsPublication struct { Changed bool `json:"changed"` Document *string `json:"document"` Connections []SavedRemoteConnection `json:"connections"` Sections []RemoteConnectionSection `json:"sections"` ID string `json:"id"` + IDs []string `json:"ids"` } // 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) { + return c.SearchRemoteConnections(ctx, document, "") +} + +// SearchRemoteConnections reads document as RemoteConnections does, keeping in Sections only the +// entries whose name, group and [user@]host[:port] contain every word of query, regardless of +// case; Connections stays the whole list. An empty query keeps every entry; one longer than 256 +// characters fails with CodeInvalidRequest. +func (c *Client) SearchRemoteConnections(ctx context.Context, document *string, query string) (RemoteConnectionsState, error) { var state RemoteConnectionsState err := c.Execute(ctx, "remote.connections", struct { Document *string `json:"document"` - }{document}, &state) + Query string `json:"query,omitempty"` + }{document, query}, &state) return state, err } diff --git a/desktop/internal/core/remote_helpers.go b/desktop/internal/core/remote_helpers.go new file mode 100644 index 000000000..377a73418 --- /dev/null +++ b/desktop/internal/core/remote_helpers.go @@ -0,0 +1,301 @@ +package core + +import ( + "context" + "encoding/json" +) + +// Connection window helpers: Core parses a quick-connect address, asks OpenSSH what it would use +// for a connection (`ssh -G`), lists the hosts of ~/.ssh/config and of Motty that the window can +// import, and keeps the trust decisions of remote workspaces. None of them connects to a host or +// reads a secret; the desktop only presents the results. + +// RemoteAddress is a quick-connect address split into the form's fields; Port is 0 and User +// empty when the address names none. +type RemoteAddress struct { + Host string `json:"host"` + User string `json:"user,omitempty"` + Port uint16 `json:"port,omitempty"` +} + +// RemoteParseAddress splits text, `[ssh://][user@]host[:port]` with an IPv6 host written in +// brackets, into the fields of a connection. A refused address fails with CodeInvalidRequest and +// names host, user or port in RemoteConnectionFieldError. Nothing is resolved or contacted. +func (c *Client) RemoteParseAddress(ctx context.Context, text string) (RemoteAddress, error) { + var address RemoteAddress + err := c.Execute(ctx, "remote.parseAddress", struct { + Text string `json:"text"` + }{text}, &address) + return address, err +} + +// RemoteSettingSource says where an effective value comes from. +type RemoteSettingSource string + +const ( + // RemoteSettingFromConnection is a value the saved connection sets. + RemoteSettingFromConnection RemoteSettingSource = "connection" + // RemoteSettingFromSSHConfig is a value the user's or the system's SSH configuration sets. + RemoteSettingFromSSHConfig RemoteSettingSource = "sshConfig" + // RemoteSettingDefault is OpenSSH's or Lithe's default. + RemoteSettingDefault RemoteSettingSource = "default" +) + +// RemoteEffectiveText is a text value OpenSSH would use and where it comes from. +type RemoteEffectiveText struct { + Value string `json:"value"` + Source RemoteSettingSource `json:"source"` +} + +// RemoteEffectiveNumber is a number OpenSSH would use and where it comes from. +type RemoteEffectiveNumber struct { + Value uint32 `json:"value"` + Source RemoteSettingSource `json:"source"` +} + +// RemoteEffectiveList is a list of paths OpenSSH would use and where it comes from. +type RemoteEffectiveList struct { + Value []string `json:"value"` + Source RemoteSettingSource `json:"source"` +} + +// RemoteEffectiveSettings is what OpenSSH would use for a connection. IdentityFiles are paths as +// the configuration writes them, empty for password authentication; ProxyJump is nil for a +// direct connection. +type RemoteEffectiveSettings struct { + HostName RemoteEffectiveText `json:"hostName"` + Port RemoteEffectiveNumber `json:"port"` + User RemoteEffectiveText `json:"user"` + IdentityFiles RemoteEffectiveList `json:"identityFiles"` + ProxyJump *RemoteEffectiveText `json:"proxyJump"` + ConnectTimeoutSeconds RemoteEffectiveNumber `json:"connectTimeoutSeconds"` + KeepAliveSeconds RemoteEffectiveNumber `json:"keepAliveSeconds"` +} + +// RemoteEffectiveSettings asks OpenSSH what it would use for connection, without connecting. +// Core bounds the run to 10 seconds: CodeRuntimeMissing without ssh, CodeProcessFailed with the +// redacted standard error in Details, CodeTimedOut and CodeParseFailed. +func (c *Client) RemoteEffectiveSettings(ctx context.Context, connection SSHConnection) (RemoteEffectiveSettings, error) { + var settings RemoteEffectiveSettings + err := c.Execute(ctx, "remote.effectiveSettings", struct { + Connection SSHConnection `json:"connection"` + }{connection}, &settings) + return settings, err +} + +// RemoteImportStatus is whether a host of ~/.ssh/config or Motty can be imported. +type RemoteImportStatus string + +const ( + // RemoteImportable is a host the import saves with every setting. + RemoteImportable RemoteImportStatus = "importable" + // RemoteImportPartial is a Motty host saved without some of its settings. + RemoteImportPartial RemoteImportStatus = "partial" + // RemoteImportExists is a host a saved entry probably already reaches. + RemoteImportExists RemoteImportStatus = "exists" + // RemoteImportPattern is a Host line with wildcards or a negation, naming no single host. + RemoteImportPattern RemoteImportStatus = "pattern" + // RemoteImportInvalid is a host name Lithe refuses. + RemoteImportInvalid RemoteImportStatus = "invalid" + // RemoteImportUnreadable is a host `ssh -G` failed or timed out for. + RemoteImportUnreadable RemoteImportStatus = "unreadable" + // RemoteImportUnsupported is a Motty host that is not an SSH host or whose address Lithe + // refuses. + RemoteImportUnsupported RemoteImportStatus = "unsupported" +) + +// RemoteResolvedHost is what `ssh -G` resolved a ~/.ssh/config alias to. +type RemoteResolvedHost struct { + HostName string `json:"hostName"` + User string `json:"user"` + Port uint16 `json:"port"` + ProxyJump string `json:"proxyJump,omitempty"` +} + +// RemoteSSHConfigHost is one Host name of ~/.ssh/config. ExistingID and ExistingName name the +// saved entry of a RemoteImportExists host; UsedAsJumpBy names the aliases that jump through it. +type RemoteSSHConfigHost struct { + Alias string `json:"alias"` + Status RemoteImportStatus `json:"status"` + Resolved *RemoteResolvedHost `json:"resolved"` + ExistingID string `json:"existingId,omitempty"` + ExistingName string `json:"existingName,omitempty"` + UsedAsJumpBy []string `json:"usedAsJumpBy"` +} + +// RemoteSSHConfigHosts lists the Host names of ~/.ssh/config and the files it includes; Files +// are the paths read, and Truncated says more than 256 names were left out. +type RemoteSSHConfigHosts struct { + Files []string `json:"files"` + Hosts []RemoteSSHConfigHost `json:"hosts"` + Truncated bool `json:"truncated"` +} + +// RemoteSSHConfigHosts reads ~/.ssh/config below homeDirectory, an absolute path, and checks each +// host against document, the saved connections or nil. Core runs `ssh -G` for each alias within +// 30 seconds for the whole list; CodeRuntimeMissing without ssh. +func (c *Client) RemoteSSHConfigHosts(ctx context.Context, homeDirectory string, document *string) (RemoteSSHConfigHosts, error) { + var hosts RemoteSSHConfigHosts + err := c.Execute(ctx, "remote.sshConfigHosts", struct { + HomeDirectory string `json:"homeDirectory"` + Document *string `json:"document"` + }{homeDirectory, document}, &hosts) + hosts.Files = nonNil(hosts.Files) + hosts.Hosts = nonNil(hosts.Hosts) + return hosts, err +} + +// RemoteMottyUnavailable says why Motty's hosts cannot be listed. +type RemoteMottyUnavailable string + +const ( + // RemoteMottyMissing means Motty's config.db does not exist. + RemoteMottyMissing RemoteMottyUnavailable = "missing" + // RemoteMottyUnreadable means the database could not be opened or read. + RemoteMottyUnreadable RemoteMottyUnavailable = "unreadable" + // RemoteMottyTooLarge means it is over 64 MiB or 4096 records. + RemoteMottyTooLarge RemoteMottyUnavailable = "tooLarge" + // RemoteMottyUnsupportedFormat means its layout is not the one Core reads. + RemoteMottyUnsupportedFormat RemoteMottyUnavailable = "unsupportedFormat" +) + +// RemoteMottySkip says why a Motty setting is not imported. +type RemoteMottySkip string + +const ( + // RemoteMottySkipSecret is stored in Motty's vault, which Core never opens. + RemoteMottySkipSecret RemoteMottySkip = "secret" + // RemoteMottySkipNoSetting has no connection setting in Lithe. + RemoteMottySkipNoSetting RemoteMottySkip = "noSetting" + // RemoteMottySkipProtocol belongs to a protocol other than SSH. + RemoteMottySkipProtocol RemoteMottySkip = "protocol" + // RemoteMottySkipCommand is a jump route that runs a command. + RemoteMottySkipCommand RemoteMottySkip = "command" + // RemoteMottySkipKerberos is left to the SSH configuration. + RemoteMottySkipKerberos RemoteMottySkip = "kerberos" + // RemoteMottySkipExtraKey is a key file after the first, which alone is imported. + RemoteMottySkipExtraKey RemoteMottySkip = "extraKey" + // RemoteMottySkipInvalid is a value Lithe refuses. + RemoteMottySkipInvalid RemoteMottySkip = "invalid" +) + +// RemoteMottyField is one Motty setting of a host: Lithe names the connection field it becomes, +// or Skip says why it is not imported. Value is Motty's value as the window shows it, empty for +// a secret. +type RemoteMottyField struct { + Motty string `json:"motty"` + Value string `json:"value"` + Lithe string `json:"lithe,omitempty"` + Skip RemoteMottySkip `json:"skip,omitempty"` +} + +// RemoteMottyCandidate is one Motty host. Name is the label an import saves it under, Address +// `[user@]host[:port]` and System Motty's operating system tag. Connection is what the import +// saves, nil for RemoteImportUnsupported; ExistingID names the saved entry of a +// RemoteImportExists host. +type RemoteMottyCandidate struct { + Key string `json:"key"` + Name string `json:"name"` + Address string `json:"address"` + System string `json:"system,omitempty"` + Color RemoteConnectionColor `json:"color,omitempty"` + Group string `json:"group,omitempty"` + Status RemoteImportStatus `json:"status"` + ExistingID string `json:"existingId,omitempty"` + Connection *SSHConnection `json:"connection"` + Fields []RemoteMottyField `json:"fields"` +} + +// RemoteMottyHosts is Motty's database read for an import: either Unavailable, or Format, the +// Groups that have a host, in Motty's order, and the Candidates. +type RemoteMottyHosts struct { + Database string `json:"database"` + Unavailable RemoteMottyUnavailable `json:"unavailable,omitempty"` + Format string `json:"format,omitempty"` + Groups []string `json:"groups"` + Candidates []RemoteMottyCandidate `json:"candidates"` +} + +// RemoteMottyHosts opens motty/config.db below configDirectory, the platform's absolute user +// configuration directory, read only, and checks each host against document, the saved +// connections or nil. Core never opens Motty's vault, so no password or key is read, and writes +// nothing to Motty's files. +func (c *Client) RemoteMottyHosts(ctx context.Context, configDirectory string, document *string) (RemoteMottyHosts, error) { + var hosts RemoteMottyHosts + err := c.Execute(ctx, "remote.mottyHosts", struct { + ConfigDirectory string `json:"configDirectory"` + Document *string `json:"document"` + }{configDirectory, document}, &hosts) + hosts.Groups = nonNil(hosts.Groups) + hosts.Candidates = nonNil(hosts.Candidates) + return hosts, err +} + +// RemoteWorkspaceTrustStorage says where the host keeps the remote trust document: RelativePath +// inside the platform preference directory, at most MaximumBytes long. +type RemoteWorkspaceTrustStorage struct { + RelativePath string `json:"relativePath"` + MaximumBytes int64 `json:"maximumBytes"` +} + +// RemoteWorkspaceTrustOf is one remote workspace's trust: State is WorkspaceTrusted, +// WorkspaceDistrusted or WorkspaceTrustUnset; Workspace is the host's real path of the root, +// Location the trusted folder that trusts it and OfferedLocation the parent folder a prompt may +// offer, nil when that is the host's root. Target is Core's key of the connection. +type RemoteWorkspaceTrustOf struct { + State string `json:"state"` + Workspace string `json:"workspace"` + Location *string `json:"location"` + OfferedLocation *string `json:"offeredLocation"` + Target json.RawMessage `json:"target"` +} + +// RemoteWorkspaceTrustState is the remote trust document as Core reads it, and the trust of the +// workspace the request named. +type RemoteWorkspaceTrustState struct { + Storage RemoteWorkspaceTrustStorage `json:"storage"` + ProjectCodeAllowed bool `json:"projectCodeAllowed"` + WorkspaceTrust *RemoteWorkspaceTrustOf `json:"workspaceTrust"` +} + +// RemoteWorkspaceTrust reads document, the remote trust source or nil, and, when sessionID is +// set, the trust of workspace, an absolute host path opened over the session. Decisions are +// keyed by the connection's target and the workspace's real path, and never mix with local ones. +func (c *Client) RemoteWorkspaceTrust(ctx context.Context, document *string, sessionID, workspace string) (RemoteWorkspaceTrustState, error) { + var state RemoteWorkspaceTrustState + err := c.Execute(ctx, "remote.workspaceTrust", struct { + Document *string `json:"document"` + SessionID string `json:"sessionId,omitempty"` + Workspace string `json:"workspace,omitempty"` + }{document, sessionID, workspace}, &state) + return state, err +} + +// RemoteWorkspaceTrustDecision records one decision on the workspace opened over SessionID: +// Trusted lets its project code run and false keeps it in safe mode; Location also trusts the +// offered parent folder. Label is the connection name shown with the target's decisions. +type RemoteWorkspaceTrustDecision struct { + SessionID string `json:"sessionId"` + Workspace string `json:"workspace"` + Trusted bool `json:"trusted"` + Location bool `json:"location,omitempty"` + Label string `json:"label,omitempty"` +} + +// RemoteWorkspaceTrustPublication is the outcome of a decision. Document is the text to publish, +// nil when the decision changed nothing. +type RemoteWorkspaceTrustPublication struct { + Changed bool `json:"changed"` + Document *string `json:"document"` +} + +// EditRemoteWorkspaceTrust records decision in document, the remote trust source or nil. A +// closed session fails with CodeConnectionClosed. +func (c *Client) EditRemoteWorkspaceTrust(ctx context.Context, document *string, decision RemoteWorkspaceTrustDecision) (RemoteWorkspaceTrustPublication, error) { + var publication RemoteWorkspaceTrustPublication + err := c.Execute(ctx, "remote.editWorkspaceTrust", struct { + Document *string `json:"document"` + Decision RemoteWorkspaceTrustDecision `json:"decision"` + }{document, decision}, &publication) + return publication, err +} diff --git a/desktop/internal/core/remote_helpers_test.go b/desktop/internal/core/remote_helpers_test.go new file mode 100644 index 000000000..6541707f6 --- /dev/null +++ b/desktop/internal/core/remote_helpers_test.go @@ -0,0 +1,178 @@ +package core + +import ( + "encoding/json" + "os" + "path/filepath" + "runtime" + "testing" +) + +// standInSSHConfig puts an ssh on PATH that prints `ssh -G` output: configured with the +// configuration files and baseline with `-F none`, for every destination. +func standInSSHConfig(t *testing.T, configured, baseline string) { + t.Helper() + if runtime.GOOS == "windows" { + t.Skip("the stand-in SSH client is a POSIX shell script") + } + dir := t.TempDir() + script := "#!/bin/sh\ncase \" $* \" in\n*\" -F none \"*) printf '%s\\n' '" + baseline + "';;\n*) printf '%s\\n' '" + configured + "';;\nesac\n" + 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")) +} + +// An import adds every entry in order, renames a clashing name instead of replacing the entry, +// and fills only the missing color or group; markConnected records the time and a query keeps +// only the matching entries in the sections. +func TestRemoteConnectionsImportMarkAndSearch(t *testing.T) { + client := NewClient() + ctx := testContext(t) + saved, err := client.EditRemoteConnections(ctx, nil, RemoteConnectionEdit{Save: &RemoteConnectionSave{ + Name: "Build box", Connection: SSHConnection{Host: "build.example"}, + }}) + if err != nil || saved.ID == "" { + t.Fatalf("save = %+v, err = %v", saved, err) + } + imported, err := client.EditRemoteConnections(ctx, saved.Document, RemoteConnectionEdit{Import: &RemoteConnectionImport{ + Entries: []RemoteConnectionSave{ + {Name: "build box", Connection: SSHConnection{Host: "other.example"}, Group: "Lab"}, + {Name: "Scratch VM", Connection: SSHConnection{Host: "192.0.2.20", User: "dev"}, Color: RemoteConnectionGreen}, + }, + Fills: []RemoteConnectionFill{{ID: saved.ID, Color: RemoteConnectionBlue, Group: "Work"}}, + }}) + if err != nil || !imported.Changed || len(imported.IDs) != 2 { + t.Fatalf("import = %+v, err = %v", imported, err) + } + names := map[string]SavedRemoteConnection{} + for _, entry := range imported.Connections { + names[entry.Name] = entry + } + if _, ok := names["build box (2)"]; !ok || names["Build box"].Color != RemoteConnectionBlue || names["Build box"].Group != "Work" { + t.Fatalf("connections = %+v, want the clashing name renamed and the saved entry filled", imported.Connections) + } + if names["Build box"].LastConnectedAt != 0 { + t.Fatalf("a fresh entry has a last connection: %+v", names["Build box"]) + } + + marked, err := client.EditRemoteConnections(ctx, imported.Document, RemoteConnectionEdit{MarkConnected: &RemoteConnectionID{ID: saved.ID}}) + if err != nil || !marked.Changed { + t.Fatalf("mark = %+v, err = %v", marked, err) + } + for _, entry := range marked.Connections { + if (entry.ID == saved.ID) != (entry.LastConnectedAt > 0) { + t.Fatalf("entry %q last connected at %d", entry.Name, entry.LastConnectedAt) + } + } + _, err = client.EditRemoteConnections(ctx, marked.Document, RemoteConnectionEdit{MarkConnected: &RemoteConnectionID{ID: "absent"}}) + if _, reason, ok := RemoteConnectionFieldError(err); !ok || reason != "unknown" { + t.Fatalf("mark an absent entry: %v", err) + } + + found, err := client.SearchRemoteConnections(ctx, marked.Document, "dev@192") + if err != nil || len(found.Connections) != 3 || len(found.Sections) != 1 || len(found.Sections[0].IDs) != 1 || found.Sections[0].IDs[0] != imported.IDs[1] { + t.Fatalf("search = %+v, err = %v, want only Scratch VM listed", found, err) + } +} + +// A quick-connect address splits into the form's fields, and a refused part names its field. +func TestRemoteParseAddressSplitsTheFields(t *testing.T) { + client := NewClient() + ctx := testContext(t) + address, err := client.RemoteParseAddress(ctx, "dev@build.example:2222") + if err != nil || address != (RemoteAddress{Host: "build.example", User: "dev", Port: 2222}) { + t.Fatalf("address = %+v, err = %v", address, err) + } + bare, err := client.RemoteParseAddress(ctx, "build-box") + if err != nil || bare != (RemoteAddress{Host: "build-box"}) { + t.Fatalf("alias = %+v, err = %v", bare, err) + } + _, err = client.RemoteParseAddress(ctx, "dev@build.example:99999") + if field, _, ok := RemoteConnectionFieldError(err); !ok || field != "port" { + t.Fatalf("port out of range: %v", err) + } +} + +// The effective values name where each comes from: the connection, the SSH configuration or the +// default. +func TestRemoteEffectiveSettingsNameTheirSources(t *testing.T) { + standInSSHConfig(t, + "hostname 192.0.2.10\nuser dev\nport 2222\nidentityfile ~/.ssh/build_key\nconnecttimeout 15\nserveraliveinterval 0\nproxyjump jump-box", + "hostname build-box\nuser localdev\nport 22\nidentityfile ~/.ssh/id_ed25519\nconnecttimeout 15\nserveraliveinterval 0\nproxyjump none", + ) + settings, err := NewClient().RemoteEffectiveSettings(testContext(t), SSHConnection{Host: "build-box", User: "dev"}) + if err != nil { + t.Fatalf("effective settings: %v", err) + } + if settings.HostName != (RemoteEffectiveText{Value: "192.0.2.10", Source: RemoteSettingFromSSHConfig}) || + settings.User != (RemoteEffectiveText{Value: "dev", Source: RemoteSettingFromConnection}) || + settings.Port != (RemoteEffectiveNumber{Value: 2222, Source: RemoteSettingFromSSHConfig}) || + settings.ConnectTimeoutSeconds.Source != RemoteSettingDefault { + t.Fatalf("settings = %+v", settings) + } + if settings.ProxyJump == nil || settings.ProxyJump.Value != "jump-box" || len(settings.IdentityFiles.Value) != 1 { + t.Fatalf("jump and keys = %+v, %+v", settings.ProxyJump, settings.IdentityFiles) + } +} + +// ~/.ssh/config lists each Host once with whether it can be imported; a wildcard is a pattern. +func TestRemoteSSHConfigHostsListTheAliases(t *testing.T) { + standInSSHConfig(t, + "hostname 192.0.2.10\nuser dev\nport 22\nconnecttimeout 15\nserveraliveinterval 0\nproxyjump none", + "hostname 192.0.2.10\nuser dev\nport 22\nconnecttimeout 15\nserveraliveinterval 0\nproxyjump none", + ) + home := t.TempDir() + if err := os.MkdirAll(filepath.Join(home, ".ssh"), 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(home, ".ssh", "config"), []byte("Host build-box\n HostName 192.0.2.10\n\nHost *.lab\n User dev\n"), 0o600); err != nil { + t.Fatal(err) + } + hosts, err := NewClient().RemoteSSHConfigHosts(testContext(t), home, nil) + if err != nil || len(hosts.Files) != 1 || len(hosts.Hosts) != 2 { + t.Fatalf("hosts = %+v, err = %v", hosts, err) + } + status := map[string]RemoteImportStatus{} + for _, host := range hosts.Hosts { + status[host.Alias] = host.Status + } + if status["build-box"] != RemoteImportable || status["*.lab"] != RemoteImportPattern { + t.Fatalf("statuses = %+v", status) + } + if hosts.Hosts[0].Resolved == nil || hosts.Hosts[0].Resolved.HostName != "192.0.2.10" { + t.Fatalf("resolved = %+v", hosts.Hosts[0].Resolved) + } +} + +// Without Motty's database the import is unavailable as a result, not an error. +func TestRemoteMottyHostsReportAMissingDatabase(t *testing.T) { + hosts, err := NewClient().RemoteMottyHosts(testContext(t), t.TempDir(), nil) + if err != nil || hosts.Unavailable != RemoteMottyMissing || hosts.Database == "" || len(hosts.Candidates) != 0 { + t.Fatalf("hosts = %+v, err = %v", hosts, err) + } +} + +// A Remote question carries the kind Core classified and the host key it names. +func TestRemoteQuestionsCarryTheirKindAndHostKey(t *testing.T) { + var asked GitAuthChallenge + var stages []RemoteStage + observe := gitAuthenticationObserver(func(challenge GitAuthChallenge) { asked = challenge }, nil, + remoteStageObserver(WithRemoteStages(testContext(t), func(stage RemoteStage) { stages = append(stages, stage) }))) + for _, event := range []any{ + map[string]any{"type": "authentication", "requestId": "q1", "prompt": "Are you sure?", "kind": "hostKey", "keyType": "ED25519", "fingerprint": "SHA256:ZXhhbXBsZQ"}, + map[string]any{"type": "remoteStage", "stage": "uploading", "sentBytes": 262144, "totalBytes": 1048576}, + } { + raw, err := json.Marshal(event) + if err != nil { + t.Fatal(err) + } + observe(raw) + } + if asked.Kind != RemoteQuestionHostKey || asked.KeyType != "ED25519" || asked.Fingerprint != "SHA256:ZXhhbXBsZQ" { + t.Fatalf("question = %+v", asked) + } + if len(stages) != 1 || stages[0] != (RemoteStage{Stage: RemoteStageUploading, SentBytes: 262144, TotalBytes: 1048576}) { + t.Fatalf("stages = %+v", stages) + } +} diff --git a/desktop/internal/core/remote_session.go b/desktop/internal/core/remote_session.go index e17b976ee..1c9828307 100644 --- a/desktop/internal/core/remote_session.go +++ b/desktop/internal/core/remote_session.go @@ -1,6 +1,7 @@ package core import ( + "bytes" "context" "encoding/json" "errors" @@ -82,9 +83,64 @@ func (c *Client) RemoteConnect(ctx context.Context, request RemoteConnectRequest return result, nil } +// RemoteStageName is a step remote.connect reports while it connects. Stages only move forward. +type RemoteStageName string + +const ( + // RemoteStageAuthenticated means the host's shell printed its first line. + RemoteStageAuthenticated RemoteStageName = "authenticated" + // RemoteStagePlatformChecked means the shell reported the host's platform. + RemoteStagePlatformChecked RemoteStageName = "platformChecked" + // RemoteStageUploading reports the server upload: once when it starts and every 256 KiB. + RemoteStageUploading RemoteStageName = "uploading" + // RemoteStageInstalled means the server is in place; Uploaded says whether it was sent. + RemoteStageInstalled RemoteStageName = "installed" +) + +// RemoteStage is one remoteStage event of remote.connect. +type RemoteStage struct { + Stage RemoteStageName `json:"stage"` + SentBytes uint64 `json:"sentBytes"` + TotalBytes uint64 `json:"totalBytes"` + Uploaded bool `json:"uploaded"` +} + +type remoteStagesKey struct{} + +// WithRemoteStages returns a context whose RemoteConnect hands each stage to observe. observe runs +// on the request's goroutine and must return promptly, posting the stage to the UI thread. +func WithRemoteStages(ctx context.Context, observe func(RemoteStage)) context.Context { + return context.WithValue(ctx, remoteStagesKey{}, observe) +} + +// remoteStageEvent is the execution event of a connection step. +var remoteStageEvent = []byte(`"remoteStage"`) + +// remoteStageObserver hands each remoteStage event to the observer WithRemoteStages put in ctx; +// nil when ctx has none. +func remoteStageObserver(ctx context.Context) func(json.RawMessage) { + observe, _ := ctx.Value(remoteStagesKey{}).(func(RemoteStage)) + if observe == nil { + return nil + } + return func(raw json.RawMessage) { + // Only the few lines naming the event are decoded. + if !bytes.Contains(raw, remoteStageEvent) { + return + } + var event struct { + Type string `json:"type"` + RemoteStage + } + if json.Unmarshal(raw, &event) == nil && event.Type == "remoteStage" && event.Stage != "" { + observe(event.RemoteStage) + } + } +} + // executeRemoteWithPrompts runs a remote request whose OpenSSH questions reach the prompt -// WithGitAuthentication put in ctx as challenges with Remote set. Without a prompt each question -// is cancelled at once. +// WithGitAuthentication put in ctx as challenges with Remote set, and whose stages reach the +// observer WithRemoteStages put there. Without a prompt each question is cancelled at once. func (c *Client) executeRemoteWithPrompts(ctx context.Context, command string, payload, result any) (observationErr, err error) { prompt, _ := ctx.Value(gitAuthenticationKey{}).(func(GitAuthChallenge)) if prompt == nil { @@ -98,7 +154,7 @@ func (c *Client) executeRemoteWithPrompts(ctx context.Context, command string, p observer := gitAuthenticationObserver(func(challenge GitAuthChallenge) { challenge.Remote = true prompt(challenge) - }, returned, nil) + }, returned, remoteStageObserver(ctx)) return c.ExecuteWithEvents(ctx, command, payload, result, observer) } diff --git a/desktop/internal/i18n/shared.generated.go b/desktop/internal/i18n/shared.generated.go index acb7884f9..b1a12b3a8 100644 --- a/desktop/internal/i18n/shared.generated.go +++ b/desktop/internal/i18n/shared.generated.go @@ -1575,6 +1575,7 @@ var sharedCatalogs = map[string]map[string]string{ "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.auto": "Automatic ({value})", "desktop.remote.browse.anchorUnusable": "Cannot prepare the local folder that stands for remote workspaces: {path}", "desktop.remote.browse.back": "Back", "desktop.remote.browse.connected": "Connected to {name}", @@ -1612,11 +1613,16 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.remote.connect": "Connect", "desktop.remote.connect.notBundled": "This build of Lithe has no remote server for the host, so it cannot open a folder there.", "desktop.remote.connect.serverInvalid": "The remote server failed its integrity check and was not started. Reinstall Lithe and try again.", + "desktop.remote.connectedNow": "Connected", + "desktop.remote.connectedWindows": "{count} window(s) open", "desktop.remote.connecting": "Connecting… OpenSSH may ask for a password or to confirm the host key.", + "desktop.remote.copyAsNew": "Duplicate as New", + "desktop.remote.copyName": "{name} copy", "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.deleteNamed": "Delete “{name}”…", "desktop.remote.diagnostics": "OpenSSH Output", "desktop.remote.document.disconnected": "the remote workspace is not connected; try again once it reconnects", "desktop.remote.document.failed": "the host could not read or write it", @@ -1625,7 +1631,16 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.remote.document.timedOut": "the host did not answer in time", "desktop.remote.document.tooLargeToSave": "This file exceeds the {limit} the host takes in one save. Your edits remain open.", "desktop.remote.edit": "Edit", - "desktop.remote.empty": "No saved connections yet. Fill in the form and save it.", + "desktop.remote.editTitle": "Edit {name}", + "desktop.remote.effective": "Effective SSH settings", + "desktop.remote.effectiveFailed": "Could not read the effective settings: {reason}", + "desktop.remote.effectiveHelp": "What OpenSSH will use to connect, as `ssh -G` resolves this connection with your SSH configuration. Each value says whether it comes from this connection, the SSH configuration or OpenSSH's default.", + "desktop.remote.empty": "No saved connections", + "desktop.remote.empty.body": "Open a folder on the host as a workspace. The editor, terminal, Git and search work on the host; only the window runs here.", + "desktop.remote.empty.importMotty": "Import from Motty", + "desktop.remote.empty.importSsh": "Import from ~/.ssh/config", + "desktop.remote.empty.manual": "Fill in the form instead", + "desktop.remote.empty.title": "Connect to a Linux host over SSH", "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.", @@ -1646,22 +1661,70 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.remote.group": "Group", "desktop.remote.group.new": "New Group…", "desktop.remote.group.none": "No Group", + "desktop.remote.groupFold": "Fold or unfold {group}", "desktop.remote.groupHelp": "The list shows connections under their group. Group names that differ only in case are the same group.", "desktop.remote.groupPlaceholder": "Group name", + "desktop.remote.hopAdd": "Add jump host", + "desktop.remote.hopPlaceholder": "user@host:port, then Return", + "desktop.remote.hopRemove": "Remove {host}", "desktop.remote.host": "Host", + "desktop.remote.host.cores": "{count} cores", + "desktop.remote.host.diskOf": "of {total}", "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.hostKey.fingerprint": "Fingerprint", + "desktop.remote.hostKey.hint": "Compare the fingerprint with the one your administrator gave you. Trusting adds the key to ~/.ssh/known_hosts.", + "desktop.remote.hostKey.reject": "Reject", + "desktop.remote.hostKey.title": "Trust the key of {host}?", + "desktop.remote.hostKey.trust": "Trust and Continue", + "desktop.remote.hostKey.type": "Type", "desktop.remote.hostPlaceholder": "build.example.com or an SSH config alias", "desktop.remote.hostSection": "Host", "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.import": "Import", + "desktop.remote.import.apply": "Import", + "desktop.remote.import.applying": "Importing…", + "desktop.remote.import.count": "{count} host(s) to import", + "desktop.remote.import.done": "Imported {count} host(s)", + "desktop.remote.import.empty": "No hosts found here.", + "desktop.remote.import.failed": "Could not import: {reason}", + "desktop.remote.import.footer": "{count} chosen", + "desktop.remote.import.from": "From {path}", + "desktop.remote.import.keepColors": "Keep colors", + "desktop.remote.import.keepGroups": "Keep groups", + "desktop.remote.import.motty": "From Motty…", + "desktop.remote.import.mottyMissing": "Motty's configuration was not found on this computer.", + "desktop.remote.import.mottyTooLarge": "Motty's configuration is too large to read.", + "desktop.remote.import.mottyUnreadable": "Motty's configuration could not be read.", + "desktop.remote.import.mottyUnsupported": "This version of Motty's configuration is not supported.", + "desktop.remote.import.none": "No hosts found", + "desktop.remote.import.source.motty": "Motty", + "desktop.remote.import.source.ssh": "~/.ssh/config", + "desktop.remote.import.ssh": "From ~/.ssh/config…", + "desktop.remote.import.status.exists": "Already saved", + "desktop.remote.import.status.importable": "Ready", + "desktop.remote.import.status.invalid": "Invalid", + "desktop.remote.import.status.partial": "Partial", + "desktop.remote.import.status.pattern": "Pattern", + "desktop.remote.import.status.unreadable": "Unreadable", + "desktop.remote.import.status.unsupported": "Not SSH", + "desktop.remote.import.title": "Import Hosts", "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.listFooter": "{count} saved · on this computer only", "desktop.remote.menuItem": "Remote Development…", + "desktop.remote.more": "More", "desktop.remote.name": "Name", "desktop.remote.namePlaceholder": "Defaults to the host", + "desktop.remote.neverConnected": "Never", "desktop.remote.new": "New Connection", + "desktop.remote.newConnection": "New Connection", + "desktop.remote.noMatch": "No connection matches", + "desktop.remote.noRecentFolders": "No folder opened yet", + "desktop.remote.openFolder": "Open Folder…", + "desktop.remote.openOther": "Open another…", "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.", @@ -1681,12 +1744,33 @@ var sharedCatalogs = map[string]map[string]string{ "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.question.answer": "Answer", + "desktop.remote.question.asks": "OpenSSH asks:", + "desktop.remote.question.continue": "Continue", + "desktop.remote.quick.continue": "Continue", + "desktop.remote.quick.label": "Address", + "desktop.remote.quick.placeholder": "user@host:22", "desktop.remote.readFailed": "Cannot read the saved connections: {reason}", + "desktop.remote.recentFolders": "Recent folders", + "desktop.remote.retest": "Test again", "desktop.remote.save": "Save", "desktop.remote.saveFailed": "Cannot save the connection: {reason}", "desktop.remote.saved": "Saved Connections", "desktop.remote.saving": "Saving…", + "desktop.remote.search": "Search connections", + "desktop.remote.searchPlaceholder": "Search name, host or group", + "desktop.remote.seconds": "{count} s", + "desktop.remote.setting.connectTimeout": "Connect timeout", + "desktop.remote.setting.hostName": "Host name", + "desktop.remote.setting.identityFiles": "Identity files", + "desktop.remote.setting.keepAlive": "Keep-alive", + "desktop.remote.setting.port": "Port", + "desktop.remote.setting.proxyJump": "Jump hosts", + "desktop.remote.setting.user": "User", "desktop.remote.settings": "Connection Settings", + "desktop.remote.source.connection": "This connection", + "desktop.remote.source.default": "Default", + "desktop.remote.source.sshConfig": "SSH config", "desktop.remote.status.connected": "SSH: {name}", "desktop.remote.status.disconnect": "Disconnect and Close", "desktop.remote.status.disconnected": "SSH: {name} · Disconnected", @@ -1695,22 +1779,47 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.remote.status.reconnect": "Reconnect", "desktop.remote.status.reconnecting": "SSH: {name} · Reconnecting…", "desktop.remote.status.unresponsive": "SSH: {name} · Not responding", + "desktop.remote.step.authenticate": "Authenticate", + "desktop.remote.step.config": "Read configuration", + "desktop.remote.step.connect": "Connect to host", + "desktop.remote.step.install": "Install server", + "desktop.remote.step.platform": "Check platform", + "desktop.remote.step.session": "Start session", + "desktop.remote.steps.back": "Back", + "desktop.remote.steps.editConnection": "Edit Connection", + "desktop.remote.steps.failed": "Could not connect to {name}", + "desktop.remote.steps.retry": "Try Again", + "desktop.remote.steps.title": "Connecting to {name}", + "desktop.remote.steps.upload": "{sent} of {total}", "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.terminal.dropOutside": "Only files of this remote workspace can be dropped on its terminal. Files of this computer are not on the host.", "desktop.remote.terminal.notConnected": "the workspace is not connected to the host. Wait for it to connect again, or click Reconnect in the status bar.", "desktop.remote.terminal.tabNumber": "{name} ({number})", "desktop.remote.test": "Test Connection", + "desktop.remote.testedAgo": "Tested {time}", "desktop.remote.testing": "Connecting… OpenSSH may ask for a password or to confirm the host key.", + "desktop.remote.thisComputer": "This computer", "desktop.remote.timeout": "Connect Timeout (s)", "desktop.remote.timeoutPlaceholder": "Auto (15)", "desktop.remote.title": "Remote Development", + "desktop.remote.titleWith": "Remote Development › {crumb}", + "desktop.remote.trust.back": "Back", + "desktop.remote.trust.body": "Do you trust the authors of {folder} on {name}? A trusted folder can run its own code, such as tasks and build tool wrappers.", + "desktop.remote.trust.failed": "Could not save the decision: {reason}", + "desktop.remote.trust.parent": "Trust all folders in {parent}", + "desktop.remote.trust.safe": "In safe mode the folder is only read: nothing in it runs until you trust it.", + "desktop.remote.trust.safeOpen": "Open in Safe Mode", + "desktop.remote.trust.title": "Trust this folder?", + "desktop.remote.trust.trustOpen": "Trust and Open", "desktop.remote.unavailable": "There is no preference folder to keep connections in.", "desktop.remote.ungrouped": "Ungrouped", + "desktop.remote.unsaved": "Unsaved changes", "desktop.remote.untested": "Test the connection to see the host's system, CPUs, memory and disk.", "desktop.remote.user": "User", "desktop.remote.userPlaceholder": "Auto (SSH config, otherwise your local user name)", "desktop.remote.via": "via {jump}", + "desktop.remote.viaHosts": "via {hosts}", "desktop.remote.workspace.banner": "This is a remote workspace. Its files open, edit and save on the host, and terminals run on the host; search, Git and running do not work here yet.", "desktop.remote.workspace.localOnly": "This feature does not work in a remote workspace yet. You can browse, edit and save the host's files and run terminals on the host.", "desktop.remote.workspace.title": "{folder} [SSH: {connection}]", @@ -5052,6 +5161,7 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.remote.auth.privateKey": "私钥文件", "desktop.remote.authentication": "身份验证", "desktop.remote.authenticationHelp": "自动:按 SSH 配置和 ssh-agent 决定。SSH Agent:只用 ssh-agent 里的密钥。私钥文件:只用选定的私钥,口令在连接时询问。密码:在连接时询问。Lithe 不保存任何回答。", + "desktop.remote.auto": "自动({value})", "desktop.remote.browse.anchorUnusable": "无法准备代表远程工作区的本地文件夹:{path}", "desktop.remote.browse.back": "返回", "desktop.remote.browse.connected": "已连接到 {name}", @@ -5089,11 +5199,16 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.remote.connect": "连接", "desktop.remote.connect.notBundled": "此版本的 Lithe 未包含适用于该主机的远端服务,无法打开主机上的文件夹。", "desktop.remote.connect.serverInvalid": "远端服务未通过完整性校验,没有启动。请重新安装 Lithe 后再试。", + "desktop.remote.connectedNow": "已连接", + "desktop.remote.connectedWindows": "{count} 个窗口已打开", "desktop.remote.connecting": "正在连接…OpenSSH 可能会询问密码或请你确认主机密钥。", + "desktop.remote.copyAsNew": "复制为新连接", + "desktop.remote.copyName": "{name} 副本", "desktop.remote.damaged": "无法读取 {path} 里保存的连接。修复或删除这个文件之前不能保存。", "desktop.remote.delete": "删除", "desktop.remote.deleteConfirm": "删除“{name}”?", "desktop.remote.deleteFailed": "无法删除连接:{reason}", + "desktop.remote.deleteNamed": "删除“{name}”…", "desktop.remote.diagnostics": "OpenSSH 输出", "desktop.remote.document.disconnected": "远程工作区未连接,请在重新连接后再试", "desktop.remote.document.failed": "主机无法读取或写入这个文件", @@ -5102,7 +5217,16 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.remote.document.timedOut": "主机没有及时响应", "desktop.remote.document.tooLargeToSave": "文件超过主机单次保存上限 {limit},编辑内容仍保留。", "desktop.remote.edit": "编辑", - "desktop.remote.empty": "还没有保存的连接。填写右侧表单后保存。", + "desktop.remote.editTitle": "编辑 {name}", + "desktop.remote.effective": "生效的 SSH 设置", + "desktop.remote.effectiveFailed": "无法读取生效设置:{reason}", + "desktop.remote.effectiveHelp": "OpenSSH 实际连接时使用的值,由 `ssh -G` 结合你的 SSH 配置解析得出。每个值都标明来自本连接、SSH 配置还是 OpenSSH 默认值。", + "desktop.remote.empty": "还没有保存的连接", + "desktop.remote.empty.body": "把主机上的文件夹作为工作区打开。编辑器、终端、Git 和搜索都在主机上运行,本机只负责显示。", + "desktop.remote.empty.importMotty": "从 Motty 导入", + "desktop.remote.empty.importSsh": "从 ~/.ssh/config 导入", + "desktop.remote.empty.manual": "手动填写", + "desktop.remote.empty.title": "通过 SSH 连接 Linux 主机", "desktop.remote.error.duplicate": "另一个已保存的连接已在使用这个值。", "desktop.remote.error.fieldTooLong": "太长:最多 1024 字节。", "desktop.remote.error.full": "最多保存 128 个连接,请先删除一个。", @@ -5123,22 +5247,70 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.remote.group": "分组", "desktop.remote.group.new": "新建分组…", "desktop.remote.group.none": "不分组", + "desktop.remote.groupFold": "折叠或展开 {group}", "desktop.remote.groupHelp": "左侧列表按分组列出连接。只差大小写的分组名视为同一个分组。", "desktop.remote.groupPlaceholder": "分组名称", + "desktop.remote.hopAdd": "添加跳板机", + "desktop.remote.hopPlaceholder": "user@host:port,按回车添加", + "desktop.remote.hopRemove": "移除 {host}", "desktop.remote.host": "主机", + "desktop.remote.host.cores": "{count} 核", + "desktop.remote.host.diskOf": "共 {total}", "desktop.remote.hostHelp": "主机名、IP 地址或 ~/.ssh/config 里的 Host 别名。OpenSSH 照常读取它的配置;这里留空的字段不会覆盖配置里的值。", + "desktop.remote.hostKey.fingerprint": "指纹", + "desktop.remote.hostKey.hint": "请与管理员提供的指纹核对。信任后,密钥会加入 ~/.ssh/known_hosts。", + "desktop.remote.hostKey.reject": "拒绝", + "desktop.remote.hostKey.title": "信任 {host} 的主机密钥?", + "desktop.remote.hostKey.trust": "信任并继续", + "desktop.remote.hostKey.type": "类型", "desktop.remote.hostPlaceholder": "build.example.com 或 SSH 配置里的别名", "desktop.remote.hostSection": "主机信息", "desktop.remote.identityFile": "私钥", "desktop.remote.identityFileHelp": "只保存路径并交给 OpenSSH;Lithe 不读取私钥内容。", "desktop.remote.identityFilePlaceholder": "~/.ssh/id_ed25519", + "desktop.remote.import": "导入", + "desktop.remote.import.apply": "导入", + "desktop.remote.import.applying": "正在导入…", + "desktop.remote.import.count": "可导入 {count} 台主机", + "desktop.remote.import.done": "已导入 {count} 台主机", + "desktop.remote.import.empty": "这里没有主机。", + "desktop.remote.import.failed": "无法导入:{reason}", + "desktop.remote.import.footer": "已选择 {count} 台", + "desktop.remote.import.from": "来自 {path}", + "desktop.remote.import.keepColors": "保留颜色", + "desktop.remote.import.keepGroups": "保留分组", + "desktop.remote.import.motty": "从 Motty 导入…", + "desktop.remote.import.mottyMissing": "在本机没有找到 Motty 的配置。", + "desktop.remote.import.mottyTooLarge": "Motty 的配置过大,无法读取。", + "desktop.remote.import.mottyUnreadable": "无法读取 Motty 的配置。", + "desktop.remote.import.mottyUnsupported": "不支持这个版本的 Motty 配置。", + "desktop.remote.import.none": "没有找到主机", + "desktop.remote.import.source.motty": "Motty", + "desktop.remote.import.source.ssh": "~/.ssh/config", + "desktop.remote.import.ssh": "从 ~/.ssh/config 导入…", + "desktop.remote.import.status.exists": "已存在", + "desktop.remote.import.status.importable": "可导入", + "desktop.remote.import.status.invalid": "无效", + "desktop.remote.import.status.partial": "部分导入", + "desktop.remote.import.status.pattern": "通配规则", + "desktop.remote.import.status.unreadable": "无法读取", + "desktop.remote.import.status.unsupported": "非 SSH", + "desktop.remote.import.title": "导入主机", "desktop.remote.keepAlive": "保活间隔(秒)", "desktop.remote.keepAliveHelp": "OpenSSH 每隔多久确认一次服务器仍有响应(ServerAliveInterval),以便发现网络已断开。", "desktop.remote.keepAlivePlaceholder": "自动(SSH 配置)", + "desktop.remote.listFooter": "{count} 个连接 · 只保存在本机", "desktop.remote.menuItem": "远程开发…", + "desktop.remote.more": "更多", "desktop.remote.name": "名称", "desktop.remote.namePlaceholder": "默认使用主机名", + "desktop.remote.neverConnected": "从未连接", "desktop.remote.new": "新建连接", + "desktop.remote.newConnection": "新建连接", + "desktop.remote.noMatch": "没有匹配的连接", + "desktop.remote.noRecentFolders": "还没有打开过文件夹", + "desktop.remote.openFolder": "打开文件夹…", + "desktop.remote.openOther": "打开其他…", "desktop.remote.port": "端口", "desktop.remote.portPlaceholder": "自动(SSH 配置,否则 22)", "desktop.remote.probe.authenticationFailed": "身份验证失败:服务器没有接受提供的密钥或密码。", @@ -5158,12 +5330,33 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.remote.proxyJump": "跳板机", "desktop.remote.proxyJumpHelp": "先经过这些主机再连接,等同 OpenSSH 的 ProxyJump:[用户@]主机[:端口],多个用逗号分隔。", "desktop.remote.proxyJumpPlaceholder": "无(或按 SSH 配置)", + "desktop.remote.question.answer": "回答", + "desktop.remote.question.asks": "OpenSSH 询问:", + "desktop.remote.question.continue": "继续", + "desktop.remote.quick.continue": "继续", + "desktop.remote.quick.label": "地址", + "desktop.remote.quick.placeholder": "user@host:22", "desktop.remote.readFailed": "无法读取已保存的连接:{reason}", + "desktop.remote.recentFolders": "最近打开的文件夹", + "desktop.remote.retest": "重新测试", "desktop.remote.save": "保存", "desktop.remote.saveFailed": "无法保存连接:{reason}", "desktop.remote.saved": "已保存的连接", "desktop.remote.saving": "正在保存…", + "desktop.remote.search": "搜索连接", + "desktop.remote.searchPlaceholder": "搜索名称、主机或分组", + "desktop.remote.seconds": "{count} 秒", + "desktop.remote.setting.connectTimeout": "连接超时", + "desktop.remote.setting.hostName": "主机名", + "desktop.remote.setting.identityFiles": "身份文件", + "desktop.remote.setting.keepAlive": "保活间隔", + "desktop.remote.setting.port": "端口", + "desktop.remote.setting.proxyJump": "跳板机", + "desktop.remote.setting.user": "用户", "desktop.remote.settings": "连接设置", + "desktop.remote.source.connection": "本连接", + "desktop.remote.source.default": "默认值", + "desktop.remote.source.sshConfig": "SSH 配置", "desktop.remote.status.connected": "SSH: {name}", "desktop.remote.status.disconnect": "断开并关闭", "desktop.remote.status.disconnected": "SSH: {name} · 已断开", @@ -5172,22 +5365,47 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.remote.status.reconnect": "重新连接", "desktop.remote.status.reconnecting": "SSH: {name} · 正在重新连接…", "desktop.remote.status.unresponsive": "SSH: {name} · 无响应", + "desktop.remote.step.authenticate": "身份验证", + "desktop.remote.step.config": "读取配置", + "desktop.remote.step.connect": "连接主机", + "desktop.remote.step.install": "安装服务端", + "desktop.remote.step.platform": "检查平台", + "desktop.remote.step.session": "启动会话", + "desktop.remote.steps.back": "返回", + "desktop.remote.steps.editConnection": "编辑连接", + "desktop.remote.steps.failed": "无法连接 {name}", + "desktop.remote.steps.retry": "重试", + "desktop.remote.steps.title": "正在连接 {name}", + "desktop.remote.steps.upload": "{sent} / {total}", "desktop.remote.stop": "停止", "desktop.remote.storageHelp": "保存在本机的 {path}。不会保存密码和私钥内容。", "desktop.remote.terminal.dropOutside": "只能把这个远程工作区里的文件拖到它的终端,本机的文件不在主机上。", "desktop.remote.terminal.notConnected": "工作区未连接到主机。请等待重新连接,或点击状态栏中的“重新连接”。", "desktop.remote.terminal.tabNumber": "{name} ({number})", "desktop.remote.test": "测试连接", + "desktop.remote.testedAgo": "{time}测试", "desktop.remote.testing": "正在连接…OpenSSH 可能会询问密码或请你确认主机密钥。", + "desktop.remote.thisComputer": "本机", "desktop.remote.timeout": "连接超时(秒)", "desktop.remote.timeoutPlaceholder": "自动(15)", "desktop.remote.title": "远程开发", + "desktop.remote.titleWith": "远程开发 › {crumb}", + "desktop.remote.trust.back": "返回", + "desktop.remote.trust.body": "你信任 {name} 上 {folder} 的作者吗?受信任的文件夹可以运行其中的代码,例如任务和构建工具包装脚本。", + "desktop.remote.trust.failed": "无法保存决定:{reason}", + "desktop.remote.trust.parent": "信任 {parent} 下的所有文件夹", + "desktop.remote.trust.safe": "在安全模式下只读取文件夹,信任之前不会运行其中的任何代码。", + "desktop.remote.trust.safeOpen": "以安全模式打开", + "desktop.remote.trust.title": "信任此文件夹吗?", + "desktop.remote.trust.trustOpen": "信任并打开", "desktop.remote.unavailable": "没有可以保存连接的偏好设置目录。", "desktop.remote.ungrouped": "未分组", + "desktop.remote.unsaved": "有未保存的修改", "desktop.remote.untested": "测试连接后,这里会显示主机的系统、CPU、内存和磁盘。", "desktop.remote.user": "用户名", "desktop.remote.userPlaceholder": "自动(SSH 配置,否则本机用户名)", "desktop.remote.via": "经 {jump}", + "desktop.remote.viaHosts": "经由 {hosts}", "desktop.remote.workspace.banner": "这是远程工作区。主机上的文件可以打开、编辑和保存,终端在主机上运行;搜索、Git 和运行暂不可用。", "desktop.remote.workspace.localOnly": "远程工作区暂不支持此功能,可以浏览、编辑和保存主机上的文件,也可以在主机上运行终端。", "desktop.remote.workspace.title": "{folder} [SSH: {connection}]", diff --git a/desktop/internal/remoteconn/remoteconn.go b/desktop/internal/remoteconn/remoteconn.go index 635752257..d0e318ff7 100644 --- a/desktop/internal/remoteconn/remoteconn.go +++ b/desktop/internal/remoteconn/remoteconn.go @@ -82,39 +82,55 @@ func Read(ctx context.Context, kernel Kernel, root string) (Source, error) { 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) { +// Document is the text of the source, nil when the file does not exist, for the Core requests +// that check other hosts against the saved list. +func (s Source) Document() (*string, error) { if s.root == "" { - return s, "", false, ErrUnavailable + return nil, ErrUnavailable } text, err := s.file.Text() if err != nil { - return s, "", false, errors.Join(ErrDamaged, err) + return nil, errors.Join(ErrDamaged, err) + } + return text, nil +} + +// Edit applies edit as Apply does and returns the id of the entry a save wrote. +func (s Source) Edit(ctx context.Context, kernel Kernel, edit core.RemoteConnectionEdit) (after Source, id string, committed bool, err error) { + after, publication, committed, err := s.Apply(ctx, kernel, edit) + return after, publication.ID, committed, err +} + +// Apply 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 Core's publication, whose ID and IDs name the entries a +// save or an import 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) Apply(ctx context.Context, kernel Kernel, edit core.RemoteConnectionEdit) (after Source, publication core.RemoteConnectionsPublication, committed bool, err error) { + text, err := s.Document() + if err != nil { + return s, publication, false, err } - publication, err := kernel.EditRemoteConnections(ctx, text, edit) + 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 + return s, publication, false, err } if publication.Changed { if publication.Document == nil { - return s, "", false, errors.New("remoteconn: Core changed the list without a document") + return s, publication, 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 + return s, publication, committed, err } } after, err = Read(ctx, kernel, s.root) - return after, publication.ID, committed, err + return after, publication, committed, err } diff --git a/desktop/internal/remoteconn/trust.go b/desktop/internal/remoteconn/trust.go new file mode 100644 index 000000000..114690ab4 --- /dev/null +++ b/desktop/internal/remoteconn/trust.go @@ -0,0 +1,98 @@ +package remoteconn + +import ( + "context" + "errors" + + "github.com/1lck/Lithe-IDEA/desktop/internal/configfile" + "github.com/1lck/Lithe-IDEA/desktop/internal/core" +) + +// Remote workspace trust lives in /toolchains/remote-trust.json, the path and the +// size limit Core names (remote.workspaceTrust), next to the local trust catalog in the platform +// user preference directory. It is owned by this machine's user, created on the first decision +// and only ever replaced whole, atomically, against the bytes it was read from. It is never written +// to a host, a workspace, the app bundle or the installation directory, so it does not affect code +// signing or Sparkle delta updates, and it is not copied across worktrees. Decisions are keyed by +// Core on the connection's target and the workspace's real path on the host, and never apply to +// local workspaces. + +// TrustKernel is the part of the Core client remote workspace trust uses. +type TrustKernel interface { + RemoteWorkspaceTrust(ctx context.Context, document *string, sessionID, workspace string) (core.RemoteWorkspaceTrustState, error) + EditRemoteWorkspaceTrust(ctx context.Context, document *string, decision core.RemoteWorkspaceTrustDecision) (core.RemoteWorkspaceTrustPublication, error) +} + +// Trust is the remote trust document with the bytes it was read from, and the trust of the +// workspace it was read for. +type Trust struct { + // State is Core's reading, with WorkspaceTrust set for the workspace ReadTrust named. + State core.RemoteWorkspaceTrustState + root string + file configfile.Snapshot +} + +// ReadTrust reads the remote trust document kept under root, the platform preference directory, +// and the trust of workspace opened over the session sessionID. Reading creates nothing. A +// document Core cannot decode fails with ErrDamaged joined to Core's error. +func ReadTrust(ctx context.Context, kernel TrustKernel, root, sessionID, workspace string) (Trust, error) { + if root == "" { + return Trust{}, ErrUnavailable + } + plan, err := kernel.RemoteWorkspaceTrust(ctx, nil, "", "") + if err != nil { + return Trust{}, err + } + file, err := configfile.Capture(ctx, root, plan.Storage.RelativePath, plan.Storage.MaximumBytes) + if errors.Is(err, configfile.ErrTooLarge) || errors.Is(err, configfile.ErrEncoding) { + return Trust{}, errors.Join(ErrDamaged, err) + } + if err != nil { + return Trust{}, err + } + text, err := file.Text() + if err != nil { + return Trust{}, errors.Join(ErrDamaged, err) + } + state, err := kernel.RemoteWorkspaceTrust(ctx, text, sessionID, workspace) + if err != nil { + var coreErr *core.Error + if errors.As(err, &coreErr) && coreErr.Code == core.CodeParseFailed { + err = errors.Join(ErrDamaged, err) + } + return Trust{}, err + } + return Trust{State: state, root: root, file: file}, nil +} + +// Decide records decision against the bytes t was read from and publishes the result. A file +// changed since t was read fails with ErrConflict and writes nothing; committed reports that the +// new document reached the disk even when a later step failed. +func (t Trust) Decide(ctx context.Context, kernel TrustKernel, decision core.RemoteWorkspaceTrustDecision) (committed bool, err error) { + if t.root == "" { + return false, ErrUnavailable + } + text, err := t.file.Text() + if err != nil { + return false, errors.Join(ErrDamaged, err) + } + publication, err := kernel.EditRemoteWorkspaceTrust(ctx, text, decision) + if err != nil { + var coreErr *core.Error + if errors.As(err, &coreErr) && coreErr.Code == core.CodeParseFailed { + err = errors.Join(ErrDamaged, err) + } + return false, err + } + if !publication.Changed { + return false, nil + } + if publication.Document == nil { + return false, errors.New("remoteconn: Core changed the trust decisions without a document") + } + committed, err = t.file.Replace(ctx, []byte(*publication.Document), func() error { return t.file.Verify(ctx) }) + if errors.Is(err, configfile.ErrConflict) { + err = errors.Join(ErrConflict, err) + } + return committed, err +} diff --git a/desktop/internal/remoteconn/trust_test.go b/desktop/internal/remoteconn/trust_test.go new file mode 100644 index 000000000..5d253d52e --- /dev/null +++ b/desktop/internal/remoteconn/trust_test.go @@ -0,0 +1,58 @@ +package remoteconn + +import ( + "errors" + "os" + "path/filepath" + "testing" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" +) + +// An import names the entries it added, in order, and Document hands the stored text to Core. +func TestApplyingAnImportNamesTheAddedEntries(t *testing.T) { + ctx := testContext(t) + kernel := core.NewClient() + source, err := Read(ctx, kernel, t.TempDir()) + if err != nil { + t.Fatal(err) + } + if document, err := source.Document(); err != nil || document != nil { + t.Fatalf("absent document = %v, err = %v", document, err) + } + after, publication, committed, err := source.Apply(ctx, kernel, core.RemoteConnectionEdit{Import: &core.RemoteConnectionImport{ + Entries: []core.RemoteConnectionSave{ + {Name: "Build box", Connection: core.SSHConnection{Host: "build.example"}}, + {Name: "Lab ARM", Connection: core.SSHConnection{Host: "192.0.2.30"}, Group: "Lab"}, + }, + }}) + if err != nil || !committed || len(publication.IDs) != 2 || len(after.Connections) != 2 { + t.Fatalf("import = %+v, committed = %v, err = %v", publication, committed, err) + } + if after.Connections[0].ID != publication.IDs[0] || after.Connections[1].ID != publication.IDs[1] { + t.Fatalf("ids = %v, connections = %+v", publication.IDs, after.Connections) + } + document, err := after.Document() + if err != nil || document == nil { + t.Fatalf("document = %v, err = %v", document, err) + } +} + +// Reading remote trust creates nothing and names the preference file Core keeps it in; a +// decision over a session Core does not know writes nothing. +func TestRemoteTrustReadsWithoutWritingAndRefusesAClosedSession(t *testing.T) { + ctx := testContext(t) + kernel := core.NewClient() + root := filepath.Join(t.TempDir(), "preferences") + trust, err := ReadTrust(ctx, kernel, root, "", "") + if err != nil || trust.State.Storage.RelativePath != "toolchains/remote-trust.json" || trust.State.WorkspaceTrust != nil { + t.Fatalf("trust = %+v, err = %v", trust.State, err) + } + committed, err := trust.Decide(ctx, kernel, core.RemoteWorkspaceTrustDecision{SessionID: "absent", Workspace: "/home/dev/app", Trusted: true}) + if err == nil || committed { + t.Fatalf("decision over an absent session: committed = %v, err = %v", committed, err) + } + if _, err := os.Stat(root); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("a refused decision created %s: %v", root, err) + } +} diff --git a/desktop/internal/workbench/app.go b/desktop/internal/workbench/app.go index abdfc208e..0c76769ab 100644 --- a/desktop/internal/workbench/app.go +++ b/desktop/internal/workbench/app.go @@ -221,6 +221,13 @@ type Kernel interface { RemoteReadFile(ctx context.Context, sessionID, path string) ([]byte, core.RemoteFileVersion, error) RemoteWriteFile(ctx context.Context, sessionID, path string, data []byte, expected *core.RemoteFileVersion) (core.RemoteFileVersion, bool, error) RemoteServerState(ctx context.Context, sessionID string) error + SearchRemoteConnections(ctx context.Context, document *string, query string) (core.RemoteConnectionsState, error) + RemoteParseAddress(ctx context.Context, text string) (core.RemoteAddress, error) + RemoteEffectiveSettings(ctx context.Context, connection core.SSHConnection) (core.RemoteEffectiveSettings, error) + RemoteSSHConfigHosts(ctx context.Context, homeDirectory string, document *string) (core.RemoteSSHConfigHosts, error) + RemoteMottyHosts(ctx context.Context, configDirectory string, document *string) (core.RemoteMottyHosts, error) + RemoteWorkspaceTrust(ctx context.Context, document *string, sessionID, workspace string) (core.RemoteWorkspaceTrustState, error) + EditRemoteWorkspaceTrust(ctx context.Context, document *string, decision core.RemoteWorkspaceTrustDecision) (core.RemoteWorkspaceTrustPublication, error) RemoteRunTerminal(ctx context.Context, sessionID string, open core.RemoteTerminalOpen, events core.RemoteTerminalEvents) (core.RemoteTerminalExit, error) RemoteRunWatch(ctx context.Context, sessionID, root string, excludeNames []string, events core.RemoteWatchEvents) error RemoteTerminalWrite(ctx context.Context, sessionID string, terminalID uint64, data []byte) (bool, error) diff --git a/desktop/internal/workbench/git_auth.go b/desktop/internal/workbench/git_auth.go index e46169d16..d155de6cb 100644 --- a/desktop/internal/workbench/git_auth.go +++ b/desktop/internal/workbench/git_auth.go @@ -76,6 +76,10 @@ func (a *App) gitAuthDialog(c ui.C) { return } head := g.queue[0] + if head.Remote && a.remoteAsksOnPage() { + // The Remote Development window asks it under the step of the connection that asks it. + return + } if g.fieldFor != head.RequestID { g.field, g.fieldFor = ui.Field{}, head.RequestID } diff --git a/desktop/internal/workbench/remote.go b/desktop/internal/workbench/remote.go index 94df1ed1e..6bd28e112 100644 --- a/desktop/internal/workbench/remote.go +++ b/desktop/internal/workbench/remote.go @@ -78,6 +78,35 @@ type remoteState struct { // err is the last failure that names no field of the form; fieldErr names one. err string fieldErr remoteFieldRefusal + + // query filters the list through Core; found is Core's sections for it, nil while the query + // is empty and the list shows the source's. searching counts the searches, so that an older + // answer arriving late is dropped. + query ui.Field + found []core.RemoteConnectionSection + searching uint64 + // collapsed are the groups whose connections the list hides, by heading ("" for none). + collapsed map[string]bool + // importMenu and moreMenu are open while the list's import menu and the overview's menu are. + importMenu, moreMenu bool + // quick is the empty page's user@host:port field, and quickErr why Core refused it. + quick ui.Field + quickErr string + // hop is the form's field that adds a jump host. + hop ui.Field + // effective is what OpenSSH resolves for each saved connection, by the connection as Core + // stores it. It is read once per opening of the window, lives with it and holds no secret. + effective map[core.SSHConnection]*remoteEffective + // steps is the connection in progress with its stages, nil when none runs. + steps *remoteSteps + // trust asks whether the chosen folder's code may run, nil when nothing is asked. + trust *remoteTrustPrompt + // importer is the import page, nil when it is not shown; imports are the counts the empty + // page and the import menu name. + importer *remoteImporter + // log folds OpenSSH's words under a failed test or connection. + log ui.CollapsibleState + imports remoteImportCounts } // remoteForm is what the user types for one connection. @@ -115,7 +144,9 @@ type remoteProbe struct { // 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 + // at is when the test ended, for the overview's "tested 5 minutes ago". + at time.Time + err error } // remoteFieldRefusal is the field of the form Core (or the form's own number check) refused, and @@ -143,6 +174,7 @@ func (a *App) openRemote(surface actionSurface) { r.form.clear() a.performed("remote.connections.open", surface) a.loadRemote(remoteLoadSelectFirst, "") + a.loadRemoteImportCounts() } // closeRemote closes the window, stopping a running test or connection and ending the session a @@ -152,6 +184,7 @@ func (a *App) closeRemote() { r.stopProbe() r.stopConnect() a.leaveRemoteBrowser() + a.leaveRemoteTrust() r.generation++ r.open, r.saving, r.loading = false, false, false r.form = remoteForm{} @@ -219,28 +252,16 @@ func remoteReadFailure(language i18n.Language, source remoteconn.Source, err err // them in, each section headed by its group once any connection has one. func (r *remoteState) setSource(source remoteconn.Source) { r.source, r.rows, r.groups = source, nil, nil - byID := make(map[string]*core.SavedRemoteConnection, len(source.Connections)) - for index := range source.Connections { - byID[source.Connections[index].ID] = &source.Connections[index] - } - headed := slices.ContainsFunc(source.Sections, func(section core.RemoteConnectionSection) bool { return section.Group != nil }) + // A search lists what Core found in the source it searched, so a new one ends it. + r.found = nil + r.searching++ + r.query.SetText("") for _, section := range source.Sections { if section.Group != nil { r.groups = append(r.groups, *section.Group) } - if headed { - heading := remoteListRow{heading: true, count: len(section.IDs)} - if section.Group != nil { - heading.group = *section.Group - } - r.rows = append(r.rows, heading) - } - for _, id := range section.IDs { - if entry := byID[id]; entry != nil { - r.rows = append(r.rows, remoteListRow{entry: entry}) - } - } } + r.buildRows() // Only a saved connection shows a past test, so the others' results go, which bounds probed // by the list. for connection := range r.probed { @@ -265,7 +286,8 @@ func (r *remoteState) entry(id string) *core.SavedRemoteConnection { return nil } -// selectFirst selects the first connection of the list, or starts a new one when there is none. +// selectFirst selects the first connection the list shows, else the first saved one, and shows +// the empty page when nothing is saved. func (r *remoteState) selectFirst() { for _, row := range r.rows { if row.entry != nil { @@ -273,7 +295,14 @@ func (r *remoteState) selectFirst() { return } } - r.selectNew() + if len(r.source.Connections) > 0 { + r.selectEntry(r.source.Connections[0].ID) + return + } + r.resetEditing() + r.selected, r.editing, r.quickErr = "", false, "" + r.form.clear() + r.syncListSelection() } // selectEntry shows the overview of the saved connection id, with the form filled from it, @@ -302,7 +331,7 @@ func (r *remoteState) selectNew() { // editingForm says whether the window shows the form: for a new connection, or for a saved one // once Edit was clicked. func (r *remoteState) editingForm() bool { - return r.editing || r.entry(r.selected) == nil + return r.editing } // newRemote starts a new connection; Cancel goes back to the one selected before. @@ -694,7 +723,9 @@ func (a *App) testRemote() { // and is only shown. a.operationFailed("remote_probe", errors.New("remote probe: "+string(result.Status))) } - r.result = &remoteProbeOutcome{result: result, err: err} + r.result = &remoteProbeOutcome{result: result, err: err, at: a.now()} + // A refusal shows what OpenSSH said at once; a host reached keeps it folded. + r.log.Open = err == nil && result.Status != core.RemoteProbeConnected if err == nil { // What the host is outlives the form; an error that kept the test from // running says nothing about the host and is only shown. diff --git a/desktop/internal/workbench/remote_browse.go b/desktop/internal/workbench/remote_browse.go index fb3c0c274..adbd7afd4 100644 --- a/desktop/internal/workbench/remote_browse.go +++ b/desktop/internal/workbench/remote_browse.go @@ -68,19 +68,29 @@ func (r *remoteState) connectable() bool { r.entry(r.selected) != nil && !r.dirty() } -// connectRemote connects to the selected saved connection's host and, once connected, lists its -// folders. -func (a *App) connectRemote() { +// connectRemote connects to the selected saved connection's host, showing each step and the +// questions OpenSSH asks on the page, then opens folder on it, or lists the host's folders to +// choose one when folder is "". +func (a *App) connectRemote(folder string) { r := &a.remote if !r.connectable() { return } entry := *r.entry(r.selected) - r.result, r.err, r.fieldErr, r.confirmDelete = nil, "", remoteFieldRefusal{}, false + r.result, r.err, r.fieldErr, r.confirmDelete, r.moreMenu = nil, "", remoteFieldRefusal{}, false, false a.performed("remote.connect", surfaceButton) ctx, cancel := context.WithTimeout(a.operationContext(context.Background()), remoteProbeTimeout) attempt := &remoteProbe{cancel: cancel} r.connect = attempt + steps := newRemoteSteps(entry, folder, a.now()) + r.steps = steps + ctx = core.WithRemoteStages(ctx, func(stage core.RemoteStage) { + a.post(func(a *App) { + if a.remote.steps == steps { + steps.observe(a.now(), stage) + } + }) + }) generation, kernel := r.generation, a.kernel a.background(nil, 0, func(context.Context) func(*App) { defer cancel() @@ -96,7 +106,11 @@ func (a *App) connectRemote() { } r.connect = nil if err == nil && result.Status == core.RemoteProbeConnected && result.Session != nil { + r.steps = nil a.browseRemote(entry, *result.Session) + if folder != "" { + a.openRemoteFolderAt(folder) + } return } if result.Session != nil { @@ -104,11 +118,13 @@ func (a *App) connectRemote() { } if field, reason, ok := core.RemoteConnectionFieldError(err); ok { a.operationRejected("remote_connect", "field_refused") + r.steps = nil r.err = remoteRefusalText(a.language(), remoteFieldRefusal{field: field, reason: reason}) return } a.operationFailed("remote_connect", remoteConnectFailure(result, err)) - r.result = remoteConnectOutcome(result, err) + steps.fail(a.now(), remoteConnectOutcome(result, err), a.language()) + r.log.Open = true } }) } @@ -121,6 +137,7 @@ func (a *App) stopRemoteConnect() { } a.performed("remote.connect.stop", surfaceButton) r.stopConnect() + r.steps = nil } // remoteConnectFailureText is the window's text for a connection that could not start for a @@ -300,14 +317,24 @@ func (b *remoteBrowser) openable() bool { // is usable, remembers the folder with the connection, and hands the session to the workspace. // A folder already open over the same connection is shown instead. func (a *App) openRemoteFolder() { + b := a.remote.browser + if !a.remote.open || b == nil || !b.openable() { + return + } + a.performed("remote.workspace.open", surfaceButton) + a.openRemoteFolderAt(b.target()) +} + +// openRemoteFolderNow opens dir once its trust is decided (remote_trust.go). It also marks the +// connection as connected now, for the list's "2 hours ago". +func (a *App) openRemoteFolderNow(dir string) { r := &a.remote b := r.browser - if !r.open || b == nil || !b.openable() { + if !r.open || b == nil { return } - a.performed("remote.workspace.open", surfaceButton) b.opening, b.err = true, "" - dir, entryID := b.target(), b.entryID + entryID := b.entryID generation, kernel, toolRoot := r.generation, a.kernel, a.globalToolchainRoot() a.background(nil, remoteReadTimeout, func(ctx context.Context) func(*App) { anchor, err := a.remotePlaceholderAnchor() @@ -321,7 +348,11 @@ func (a *App) openRemoteFolder() { var source remoteconn.Source source, rememberErr = remoteconn.Read(ctx, kernel, toolRoot) if rememberErr == nil { - _, _, _, rememberErr = source.Edit(ctx, kernel, core.RemoteConnectionEdit{RememberFolder: &core.RemoteConnectionFolder{ID: entryID, Path: dir}}) + source, _, _, rememberErr = source.Edit(ctx, kernel, core.RemoteConnectionEdit{RememberFolder: &core.RemoteConnectionFolder{ID: entryID, Path: dir}}) + } + if rememberErr == nil { + // One edit after the other: each is made over the document the last one wrote. + _, _, _, rememberErr = source.Edit(ctx, kernel, core.RemoteConnectionEdit{MarkConnected: &core.RemoteConnectionID{ID: entryID}}) } } return func(a *App) { diff --git a/desktop/internal/workbench/remote_connections_visual_test.go b/desktop/internal/workbench/remote_connections_visual_test.go index 383a75e56..35b0ef738 100644 --- a/desktop/internal/workbench/remote_connections_visual_test.go +++ b/desktop/internal/workbench/remote_connections_visual_test.go @@ -8,14 +8,17 @@ import ( "testing" "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/remoteconn" "github.com/1lck/Lithe-IDEA/desktop/internal/store" "github.com/vivaui/viva/app" "github.com/vivaui/viva/headless" ) -// TestVisualRemoteConnections captures the Remote Development window: saved connections under -// their groups with the tested one's overview, its form, a new connection whose host Core refused -// under its field, and OpenSSH's password question over the window. +// TestVisualRemoteConnections captures the Remote Development window: the first page with nothing +// saved, saved connections under their groups with the tested one's overview, its form, a new +// connection whose host Core refused under its field, OpenSSH's password question over the window, +// a refused test, the connection steps with OpenSSH's questions on the page and a failure, the +// question whether to trust a folder, and Motty's hosts to import. func TestVisualRemoteConnections(t *testing.T) { out := os.Getenv("LITHE_VISUAL_OUTPUT_DIR") if out == "" { @@ -67,6 +70,10 @@ func TestVisualRemoteConnections(t *testing.T) { h.app.openRemote(surfaceMenu) h.settleChain() r := &h.app.remote + // The counts come from this computer's Motty and ~/.ssh/config; the scenes show fixed + // ones instead. + r.imports = remoteImportCounts{loaded: true, motty: 4, sshConfig: 7} + shot("empty") type saved struct { name, host, port, user, authentication, identityFile, proxyJump, group string @@ -104,6 +111,35 @@ func TestVisualRemoteConnections(t *testing.T) { buildBox = entry.ID } } + // What `ssh -G` resolves comes from this computer's SSH configuration; the scenes show + // fixed values instead. + jump := core.RemoteEffectiveText{Value: "bastion.example", Source: core.RemoteSettingFromConnection} + for _, entry := range r.source.Connections { + user := entry.Connection.User + userSource := core.RemoteSettingFromConnection + if user == "" { + user, userSource = "dev", core.RemoteSettingDefault + } + port, portSource := uint32(entry.Connection.Port), core.RemoteSettingFromConnection + if port == 0 { + port, portSource = 22, core.RemoteSettingDefault + } + settings := core.RemoteEffectiveSettings{ + HostName: core.RemoteEffectiveText{Value: entry.Connection.Host, Source: core.RemoteSettingFromConnection}, + Port: core.RemoteEffectiveNumber{Value: port, Source: portSource}, + User: core.RemoteEffectiveText{Value: user, Source: userSource}, + IdentityFiles: core.RemoteEffectiveList{Value: []string{"~/.ssh/id_ed25519"}, Source: core.RemoteSettingFromSSHConfig}, + ConnectTimeoutSeconds: core.RemoteEffectiveNumber{Value: 10, Source: core.RemoteSettingFromSSHConfig}, + KeepAliveSeconds: core.RemoteEffectiveNumber{Value: 30, Source: core.RemoteSettingDefault}, + } + if entry.Name == "Build box" { + settings.ProxyJump = &jump + } + if r.effective == nil { + r.effective = map[core.SSHConnection]*remoteEffective{} + } + r.effective[remoteStored(entry.Connection)] = &remoteEffective{settings: settings} + } r.selectEntry(buildBox) h.app.testRemote() h.settleChain() @@ -136,6 +172,63 @@ func TestVisualRemoteConnections(t *testing.T) { shot("password") h.app.gitAuth.queue = nil close(done) + + refused := &remoteProbeOutcome{result: core.RemoteProbeResult{ + Status: core.RemoteProbeAuthenticationFailed, + Diagnostics: "dev@build.example: Permission denied (publickey,password).", + }, at: h.app.now()} + r.selectEntry(buildBox) + h.app.editSelectedRemote() + r.result = refused + r.log.Open = true + shot("test-failed") + + // Connecting runs the steps on the page, with OpenSSH's questions under the step that + // asks them. + r.selectEntry(buildBox) + steps := newRemoteSteps(*r.entry(buildBox), "", h.app.now()) + r.steps = steps + asked := make(chan struct{}) + h.app.gitAuth.queue = []core.GitAuthChallenge{{ + RequestID: "visual-key", Prompt: "Are you sure you want to continue connecting (yes/no/[fingerprint])? ", + Remote: true, Kind: core.RemoteQuestionHostKey, KeyType: "ED25519", + Fingerprint: "SHA256:7Yb0QaBf3c1uN0e9kVwq2XrJmZpT4sLhG8dEoUiAy6c", Attempt: 1, Done: asked, + }} + shot("steps-host-key") + steps.advance(h.app.now(), remoteStepAuthenticate) + h.app.gitAuth.queue = []core.GitAuthChallenge{{ + RequestID: "visual-password", Prompt: "dev@build.example's password: ", Secret: true, Remote: true, Attempt: 1, Done: asked, + }} + shot("steps-password") + h.app.gitAuth.queue = nil + close(asked) + steps.fail(h.app.now(), refused, h.app.language()) + r.log.Open = true + shot("steps-failed") + r.steps = nil + + // The first time a folder opens, the window asks whether to trust it. + parent := "/home/dev" + r.trust = &remoteTrustPrompt{browser: &remoteBrowser{name: "Build box"}, dir: "/home/dev/project", trust: remoteconn.Trust{ + State: core.RemoteWorkspaceTrustState{WorkspaceTrust: &core.RemoteWorkspaceTrustOf{ + State: core.WorkspaceTrustUnset, Workspace: "/home/dev/project", OfferedLocation: &parent, + }}, + }} + shot("trust") + r.trust = nil + + r.importer = &remoteImporter{source: remoteImportMotty, keepGroups: true, keepColors: true, + motty: core.RemoteMottyHosts{Database: "~/Library/Application Support/Motty/config.db", Groups: []string{"Production", "Lab"}, + Candidates: []core.RemoteMottyCandidate{ + {Key: "1", Name: "Build box", Address: "dev@build.example:2222", Color: core.RemoteConnectionRed, Group: "Production", Status: core.RemoteImportExists, ExistingID: buildBox}, + {Key: "2", Name: "Staging DB", Address: "postgres@db.staging.example", Color: core.RemoteConnectionBlue, Group: "Production", Status: core.RemoteImportable}, + {Key: "3", Name: "GPU node", Address: "ml@gpu-07.lab.example", Color: core.RemoteConnectionPurple, Group: "Lab", Status: core.RemoteImportPartial}, + {Key: "4", Name: "Router", Address: "admin@192.0.2.1", Group: "Lab", Status: core.RemoteImportUnsupported}, + }}, + mottyChosen: []bool{true, true, true, false}, + } + shot("import") + r.importer = nil h.app.closeRemote() h.settleChain() }) diff --git a/desktop/internal/workbench/remote_detail_view.go b/desktop/internal/workbench/remote_detail_view.go new file mode 100644 index 000000000..195850e10 --- /dev/null +++ b/desktop/internal/workbench/remote_detail_view.go @@ -0,0 +1,575 @@ +package workbench + +import ( + "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 page beside the Remote Development window's list: the first page when no +// connection is saved, a saved connection's overview, and the form that edits one, with the +// footer each of them has. + +// remoteHeroTile is the size of the mark above a connection's overview. +const remoteHeroTile = 44 + +// remoteFolderRowHeight is the height of a folder in a list of folders. +const remoteRecentRowHeight = 32 + +// remotePage declares the page for what the list selected. +func (a *App) remotePage(c ui.C, language i18n.Language) { + r := &a.remote + if r.steps != nil { + a.remoteStepsView(c, language, r.steps) + return + } + entry := r.entry(r.selected) + switch { + case r.editing: + a.remoteFormPage(c, language, entry) + case entry != nil: + a.remoteOverview(c, language, *entry) + case r.loading && !r.loaded: + ui.Column(c).Fill().Center().Children(func() { + ui.Spinner(c.Part("loading")) + }) + default: + a.remoteEmptyPage(c, language) + } +} + +// remoteNotices declares why the connections could not be read or the last change failed. +func (a *App) remoteNotices(c ui.C) { + r := &a.remote + if r.readErr != "" { + a.remoteNotice(c.Part("read-error"), icons.CircleX, a.theme.Danger, r.readErr) + } + if r.err != "" { + a.remoteNotice(c.Part("error"), icons.CircleX, a.theme.Danger, r.err) + } +} + +// remoteSection declares a titled part of a page, with what it offers on the right of its title. +func (a *App) remoteSection(c ui.C, title, help string, actions func(), body func()) { + ui.Column(c).FillWidth().Gap(8).Children(func() { + ui.Row(c.Part("head")).FillWidth().Height(22).Items(ui.Center).Gap(4).Children(func() { + ui.Text(c, title).FontSize(a.theme.Metrics.FontSizeS).Weight(gfx.WeightSemibold).Color(a.colors.Subtle).Shrink(0) + if help != "" { + a.remoteHelp(c.Part("section-help"), help) + } + ui.Spacer(c) + if actions != nil { + actions() + } + }) + body() + }) +} + +// remoteBordered declares the bordered box the overview's lists and tables sit in. +func (a *App) remoteBordered(c ui.C) ui.Box { + return ui.Column(c).FillWidth().Radius(6).Stroke(1, a.colors.Line).Clip() +} + +// remoteEmptyPage is the first page while no connection is saved: an address to start from, the +// hosts other tools already know, and the form for the rest. +func (a *App) remoteEmptyPage(c ui.C, language i18n.Language) { + r := &a.remote + small := a.theme.Metrics.FontSizeS + ui.Scroll(c.Part("empty")).Fill().Children(func() { + ui.Column(c).FillWidth().Items(ui.Center).PadSides(56, 32, 32, 32).Children(func() { + ui.Column(c.Part("card")).Width(420).Gap(16).Children(func() { + a.remoteNotices(c) + ui.Row(c).Size(40, 40).Center().Radius(10).Background(a.colors.Hover).Stroke(1, a.colors.Line).Children(func() { + ui.Icon(c, icons.Server).Size(20, 20).Color(a.colors.Subtle) + }) + ui.Column(c).FillWidth().Gap(6).Children(func() { + ui.Text(c, i18n.Shared(language, "desktop.remote.empty.title")).FontSize(16).Weight(gfx.WeightSemibold) + ui.Paragraph(c, i18n.Shared(language, "desktop.remote.empty.body"), 3).Color(a.colors.Subtle) + }) + ui.Column(c).FillWidth().Gap(6).Children(func() { + ui.Text(c, i18n.Shared(language, "desktop.remote.quick.label")).FontSize(small).Weight(gfx.WeightMedium) + ui.Row(c).FillWidth().Gap(8).Items(ui.Center).Children(func() { + field := ui.TextField(c.Part("quick"), &r.quick, i18n.Shared(language, "desktop.remote.quick.label"), i18n.Shared(language, "desktop.remote.quick.placeholder")). + Mono().Grow(1).Basis(0).MinWidth(0).Disabled(!r.editable()) + if field.Submitted() { + c.After(a.quickRemote) + } + if ui.Button(c.Part("quick-go"), i18n.Shared(language, "desktop.remote.quick.continue")).Disabled(!r.editable() || strings.TrimSpace(r.quick.Text()) == "").Clicked() { + c.After(a.quickRemote) + } + }) + if r.quickErr != "" { + ui.Text(c, r.quickErr).FontSize(small).Color(a.theme.Danger) + } + }) + ui.Row(c).FillWidth().Gap(10).Children(func() { + a.remoteImportCard(c.Part("motty"), language, remoteImportMotty, "M", i18n.Shared(language, "desktop.remote.empty.importMotty"), r.imports.motty) + a.remoteImportCard(c.Part("ssh"), language, remoteImportSSH, "~", i18n.Shared(language, "desktop.remote.empty.importSsh"), r.imports.sshConfig) + }) + if ui.Button(c.Part("manual"), i18n.Shared(language, "desktop.remote.empty.manual")).Link().Disabled(!r.editable()).Clicked() { + c.After(a.newRemote) + } + }) + }) + }) +} + +// remoteImportCard declares a source to import hosts from, with how many it holds. +func (a *App) remoteImportCard(c ui.C, language i18n.Language, source remoteImportSource, mark, title string, count int) { + r := &a.remote + small := a.theme.Metrics.FontSizeS + disabled := !r.editable() + card := ui.Row(c).Grow(1).Basis(0).MinWidth(0).Items(ui.Center).Gap(10).Pad(12).Radius(6).Stroke(1, a.colors.Line). + HitWith(ui.ID(c), title, gfx.HitOptions{Role: gfx.RoleButton, Cursor: gfx.PointerCursorHand, Disabled: disabled}). + Hover(ui.Look{}.Background(a.colors.Hover)).Pressed(ui.Look{}.Background(a.colors.Active)) + card.Children(func() { + ui.Row(c).Size(28, 28).Shrink(0).Center().Radius(6).Background(a.colors.Hover).Stroke(1, a.colors.Line).Children(func() { + ui.Text(c, mark).Mono().Weight(gfx.WeightBold).Color(a.colors.Subtle) + }) + ui.Column(c).Grow(1).Basis(0).MinWidth(0).Gap(2).Children(func() { + ui.Text(c, title).Weight(gfx.WeightMedium).Ellipsis().MinWidth(0) + count := a.remoteImportCountText(language, count) + if !r.imports.loaded { + count = i18n.Shared(language, "native.loading") + } + ui.Text(c, count).FontSize(small).Color(a.colors.Subtle).Ellipsis().MinWidth(0) + }) + }) + if !disabled && card.Clicked() { + c.After(func() { a.openRemoteImport(source) }) + } +} + +// remoteOverview declares a saved connection's page: who it is, the folders opened on it, the +// host it reached and what OpenSSH will use to reach it. +func (a *App) remoteOverview(c ui.C, language i18n.Language, entry core.SavedRemoteConnection) { + r := &a.remote + outcome := r.probedOutcome(entry.Connection) + ui.Scroll(c.Part("overview")).Fill().Children(func() { + ui.Column(c).FillWidth().Gap(22).PadSides(20, 24, 24, 24).Children(func() { + a.remoteNotices(c) + a.remoteHero(c.Part("hero"), language, entry, outcome) + a.remoteRecentSection(c.Part("recent"), language, entry) + a.remoteHostSection(c.Part("host"), language, outcome) + a.remoteEffectiveSection(c.Part("effective"), language, entry) + }) + }) +} + +// remoteHero declares the overview's head: the host's mark, the connection's name, group and +// address, and what can be done with it. +func (a *App) remoteHero(c ui.C, language i18n.Language, entry core.SavedRemoteConnection, outcome *remoteProbeOutcome) { + r := &a.remote + ui.Row(c).FillWidth().Items(ui.Center).Gap(14).Children(func() { + a.remoteTile(c.Part("tile"), remoteSystemMark(outcome), entry.Name, entry.Color, remoteHeroTile, 15) + ui.Column(c).Grow(1).Basis(0).MinWidth(0).Gap(5).Children(func() { + ui.Row(c).FillWidth().Items(ui.Center).Gap(8).Children(func() { + if tint, ok := remoteColor(a.colors.Dark, entry.Color); ok { + a.remoteDot(c.Part("color"), tint, 8) + } + ui.Text(c, entry.Name).FontSize(16).Weight(gfx.WeightSemibold).Ellipsis().Shrink(1).MinWidth(0) + if entry.Group != "" { + a.remotePill(c.Part("group"), entry.Group, a.colors.Subtle) + } + if windows := a.remoteWindows(entry.ID); windows > 0 { + a.remoteStatusPill(c.Part("live"), i18n.SharedFormat(language, "desktop.remote.connectedWindows", map[string]string{"count": strconv.Itoa(windows)}), a.colors.Success) + } + }) + ui.Row(c.Part("address")).FillWidth().Gap(8).Items(ui.Center).Children(func() { + ui.Text(c, remoteAddress(entry.Connection)).Mono().FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Subtle).Ellipsis().Shrink(0).MinWidth(0) + if hops := remoteHopList(entry.Connection.ProxyJump); len(hops) > 0 { + ui.Text(c, "· "+i18n.SharedFormat(language, "desktop.remote.viaHosts", map[string]string{"hosts": strings.Join(hops, " › ")})). + FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Subtle).Ellipsis().Shrink(1).MinWidth(0) + } + }) + }) + if ui.Button(c.Part("edit"), i18n.Shared(language, "desktop.remote.edit")).Icon(icons.Pencil).Outline().Shrink(0).Disabled(!r.editable()).Clicked() { + c.After(a.editSelectedRemote) + } + a.remoteMoreMenu(c.Part("more"), language, entry) + if ui.Button(c.Part("open"), i18n.Shared(language, "desktop.remote.openFolder")).Icon(icons.FolderOpen).Shrink(0).Disabled(!r.connectable()).Clicked() { + c.After(func() { a.connectRemote("") }) + } + }) +} + +// remoteMoreMenu declares the overview's ⋯ button and what it opens. +func (a *App) remoteMoreMenu(c ui.C, language i18n.Language, entry core.SavedRemoteConnection) { + r := &a.remote + anchor, clicked := a.gitToolButton(c, i18n.Shared(language, "desktop.remote.more"), icons.Ellipsis, r.moreMenu, false) + if clicked { + c.After(func() { r.moreMenu = !r.moreMenu }) + } + if !r.moreMenu { + return + } + open := true + ui.Menu(c, anchor, &open, func(menu *ui.MenuItems) { + if menu.Item(i18n.Shared(language, "desktop.remote.test")).Disabled(r.probe != nil).Clicked() { + c.After(a.testRemote) + } + if menu.Item(i18n.Shared(language, "desktop.remote.copyAsNew")).Icon(icons.Copy).Disabled(!r.editable()).Clicked() { + c.After(a.copyRemoteAsNew) + } + menu.Separator() + remove := menu.Item(i18n.SharedFormat(language, "desktop.remote.deleteNamed", map[string]string{"name": entry.Name})). + Icon(icons.Trash2).Destructive().Disabled(!r.editable()) + if remove.Clicked() { + c.After(func() { + a.performed("remote.connection.deleteAsk", surfaceMenu) + r.confirmDelete = true + }) + } + }) + if !open { + r.moreMenu = false + } +} + +// remoteRecentSection declares the folders last opened on the connection; choosing one connects +// and opens it. +func (a *App) remoteRecentSection(c ui.C, language i18n.Language, entry core.SavedRemoteConnection) { + r := &a.remote + small := a.theme.Metrics.FontSizeS + a.remoteSection(c, i18n.Shared(language, "desktop.remote.recentFolders"), "", func() { + if ui.Button(c.Part("other"), i18n.Shared(language, "desktop.remote.openOther")).Link().Disabled(!r.connectable()).Clicked() { + c.After(func() { a.connectRemote("") }) + } + }, func() { + if len(entry.RecentFolders) == 0 { + ui.Text(c, i18n.Shared(language, "desktop.remote.noRecentFolders")).FontSize(small).Color(a.colors.Subtle) + return + } + a.remoteBordered(c.Part("folders")).Children(func() { + for index, folder := range entry.RecentFolders { + k := c.KeyInt(index) + if index > 0 { + ui.Row(k.Part("line")).FillWidth().Height(1).Shrink(0).Background(a.colors.Line) + } + disabled := !r.connectable() + row := ui.Row(k).FillWidth().Height(remoteRecentRowHeight).Items(ui.Center).Gap(8).PadX(10). + HitWith(ui.ID(k), folder, gfx.HitOptions{Role: gfx.RoleButton, Cursor: gfx.PointerCursorHand, Disabled: disabled}). + Hover(ui.Look{}.Background(a.colors.Hover)).Pressed(ui.Look{}.Background(a.colors.Active)) + row.Children(func() { + ui.Icon(k, icons.Folder).Size(14, 14).Shrink(0).Color(a.colors.Subtle) + ui.Text(k, folder).Mono().FontSize(small).Ellipsis().Grow(1).MinWidth(0) + ui.Icon(k, icons.ChevronRight).Size(12, 12).Shrink(0).Color(a.colors.Subtle) + }) + if !disabled && row.Clicked() { + folder := folder + k.After(func() { a.connectRemote(folder) }) + } + } + }) + }) +} + +// remoteHostSection declares what the last test found on the host, and the button that tests it +// again. +func (a *App) remoteHostSection(c ui.C, language i18n.Language, outcome *remoteProbeOutcome) { + r := &a.remote + small := a.theme.Metrics.FontSizeS + a.remoteSection(c, i18n.Shared(language, "desktop.remote.hostSection"), "", func() { + if r.probe != nil { + ui.Spinner(c.Part("testing")).Size(12, 12) + ui.Text(c, i18n.Shared(language, "desktop.remote.testing")).FontSize(small).Color(a.colors.Subtle) + if ui.Button(c.Part("stop"), i18n.Shared(language, "desktop.remote.stop")).Link().Clicked() { + c.After(a.stopRemoteTest) + } + return + } + label := i18n.Shared(language, "desktop.remote.test") + if outcome != nil { + if !outcome.at.IsZero() { + ui.Text(c, i18n.SharedFormat(language, "desktop.remote.testedAgo", map[string]string{"time": relativeGitTime(language, a.now(), outcome.at)})). + FontSize(small).Color(a.colors.Subtle) + } + label = i18n.Shared(language, "desktop.remote.retest") + } + if ui.Button(c.Part("test"), label).Link().Clicked() { + c.After(a.testRemote) + } + }, func() { + switch { + case outcome == nil: + ui.Text(c, i18n.Shared(language, "desktop.remote.untested")).FontSize(small).Color(a.colors.Subtle) + case outcome.err == nil && outcome.result.Status == core.RemoteProbeConnected && outcome.result.Host != nil: + a.remoteHostGrid(c.Part("grid"), language, *outcome.result.Host) + default: + a.remoteOutcomeBox(c.Part("outcome"), language, outcome) + } + }) +} + +// remoteHostGrid declares the host's system, processor, memory and disk side by side. +func (a *App) remoteHostGrid(c ui.C, language i18n.Language, host core.RemoteProbedHost) { + details := host.Details + small := a.theme.Metrics.FontSizeS + type cell struct{ label, value, detail string } + system := strings.TrimSpace(details.OperatingSystem) + if system == "" { + system = host.System + } + // The host name is the machine that answered, which a load balancer or a jump host may pick. + cells := []cell{ + {i18n.Shared(language, "desktop.remote.probe.hostName"), strings.TrimSpace(details.HostName), host.HomeDirectory}, + {i18n.Shared(language, "desktop.remote.probe.os"), system, details.Kernel}, + {i18n.Shared(language, "desktop.remote.probe.cpu"), host.Machine, ""}, + {i18n.Shared(language, "desktop.remote.probe.memory"), "", ""}, + {i18n.Shared(language, "desktop.remote.probe.disk"), "", ""}, + } + if details.CPUCount > 0 { + cells[2].detail = i18n.SharedFormat(language, "desktop.remote.host.cores", map[string]string{"count": strconv.FormatUint(uint64(details.CPUCount), 10)}) + } + if details.MemoryBytes > 0 { + cells[3].value = memorySize(language, details.MemoryBytes) + } + if details.DiskTotalBytes > 0 { + cells[4].value = memorySize(language, details.DiskAvailableBytes) + cells[4].detail = i18n.SharedFormat(language, "desktop.remote.host.diskOf", map[string]string{"total": memorySize(language, details.DiskTotalBytes)}) + } + ui.Row(c).FillWidth().Radius(6).Stroke(1, a.colors.Line).Clip().Children(func() { + for index, item := range cells { + k := c.KeyInt(index) + if index > 0 { + ui.Column(k.Part("line")).Width(1).FillHeight().Shrink(0).Background(a.colors.Line) + } + value := item.value + if value == "" { + value = "—" + } + ui.Column(k).Grow(1).Basis(0).MinWidth(0).Gap(3).PadSides(10, 12, 10, 12).Children(func() { + ui.Text(k, item.label).FontSize(small).Color(a.colors.Subtle).Ellipsis().MinWidth(0) + ui.Text(k, value).Weight(gfx.WeightMedium).Ellipsis().MinWidth(0) + if item.detail != "" { + ui.Text(k, item.detail).FontSize(small).Color(a.colors.Subtle).Ellipsis().MinWidth(0) + } + }) + } + }) +} + +// remoteOutcomeBox declares how a test ended: green with the host when it connected, red with +// why it did not, and OpenSSH's own words under it. +func (a *App) remoteOutcomeBox(c ui.C, language i18n.Language, outcome *remoteProbeOutcome) { + small := a.theme.Metrics.FontSizeS + connected := outcome.err == nil && outcome.result.Status == core.RemoteProbeConnected + tint, icon := a.theme.Danger, icons.CircleX + text := remoteFailureText(language, outcome) + if connected { + tint, icon = a.colors.Success, icons.CircleCheck + var system, machine string + if host := outcome.result.Host; host != nil { + system, machine = host.System, host.Machine + } + text = i18n.SharedFormat(language, "desktop.remote.probe.connected", map[string]string{"system": system, "machine": machine}) + } else if outcome.err == nil && outcome.result.Status == core.RemoteProbeUnsupportedPlatform { + tint, icon = a.colors.Warning, icons.CircleAlert + } + ui.Column(c).FillWidth().Gap(10).Pad(12).Radius(6).Background(tint.WithAlpha(0.08)).Stroke(1, tint.WithAlpha(0.35)).Children(func() { + ui.Row(c).FillWidth().Gap(8).Items(ui.Start).Children(func() { + ui.Icon(c, icon).Size(16, 16).Shrink(0).Color(tint) + ui.Paragraph(c, text, 6).Weight(gfx.WeightMedium).Grow(1).MinWidth(0) + }) + if connected && outcome.result.Host != nil { + a.remoteHostGrid(c.Part("grid"), language, *outcome.result.Host) + } + if diagnostics := strings.TrimSpace(outcome.result.Diagnostics); diagnostics != "" && !connected { + ui.Collapsible(c.Part("diagnostics"), &a.remote.log, i18n.Shared(language, "desktop.remote.diagnostics"), func() { + ui.Column(c).FillWidth().Pad(10).Radius(4).Background(a.colors.Hover).Children(func() { + ui.Paragraph(c.Part("log"), diagnostics, 12).Mono().FontSize(small).Color(a.colors.Subtle) + }) + }) + } + }) +} + +// remoteEffectiveSection declares what OpenSSH will use to reach the host, as `ssh -G` resolves +// it, and where each value comes from. +func (a *App) remoteEffectiveSection(c ui.C, language i18n.Language, entry core.SavedRemoteConnection) { + r := &a.remote + small := a.theme.Metrics.FontSizeS + state, asked := r.effective[entry.Connection] + if !asked { + connection := entry.Connection + c.After(func() { a.loadRemoteEffective(connection) }) + } + a.remoteSection(c, i18n.Shared(language, "desktop.remote.effective"), i18n.Shared(language, "desktop.remote.effectiveHelp"), func() { + if ui.Button(c.Part("edit"), i18n.Shared(language, "desktop.remote.edit")).Link().Disabled(!r.editable()).Clicked() { + c.After(a.editSelectedRemote) + } + }, func() { + switch { + case state == nil: + ui.Text(c, i18n.Shared(language, "native.loading")).FontSize(small).Color(a.colors.Subtle) + case state.err != nil: + a.remoteNotice(c.Part("failed"), icons.CircleX, a.theme.Danger, + i18n.SharedFormat(language, "desktop.remote.effectiveFailed", map[string]string{"reason": remoteLogError(state.err).Error()})) + default: + a.remoteEffectiveTable(c.Part("table"), language, state.settings) + } + }) +} + +// remoteEffectiveTable declares the resolved values, one per row, with their source. +func (a *App) remoteEffectiveTable(c ui.C, language i18n.Language, settings core.RemoteEffectiveSettings) { + type line struct { + key, value string + source core.RemoteSettingSource + words bool + } + number := func(value core.RemoteEffectiveNumber, seconds bool) string { + text := strconv.FormatUint(uint64(value.Value), 10) + if seconds { + text = i18n.SharedFormat(language, "desktop.remote.seconds", map[string]string{"count": text}) + } + return text + } + lines := []line{ + {i18n.Shared(language, "desktop.remote.setting.hostName"), settings.HostName.Value, settings.HostName.Source, false}, + {i18n.Shared(language, "desktop.remote.setting.user"), settings.User.Value, settings.User.Source, false}, + {i18n.Shared(language, "desktop.remote.setting.port"), number(settings.Port, false), settings.Port.Source, false}, + } + if len(settings.IdentityFiles.Value) > 0 { + lines = append(lines, line{i18n.Shared(language, "desktop.remote.setting.identityFiles"), strings.Join(settings.IdentityFiles.Value, ", "), settings.IdentityFiles.Source, false}) + } + if jump := settings.ProxyJump; jump != nil && jump.Value != "" { + lines = append(lines, line{i18n.Shared(language, "desktop.remote.setting.proxyJump"), jump.Value, jump.Source, false}) + } + lines = append(lines, + line{i18n.Shared(language, "desktop.remote.setting.connectTimeout"), number(settings.ConnectTimeoutSeconds, true), settings.ConnectTimeoutSeconds.Source, true}, + line{i18n.Shared(language, "desktop.remote.setting.keepAlive"), number(settings.KeepAliveSeconds, true), settings.KeepAliveSeconds.Source, true}, + ) + small := a.theme.Metrics.FontSizeS + a.remoteBordered(c).Children(func() { + for index, item := range lines { + k := c.KeyInt(index) + if index > 0 { + ui.Row(k.Part("line")).FillWidth().Height(1).Shrink(0).Background(a.colors.Line) + } + ui.Row(k).FillWidth().Height(30).Items(ui.Center).Gap(10).PadX(12).Children(func() { + ui.Text(k, item.key).FontSize(small).Color(a.colors.Subtle).Width(140).Shrink(0).Ellipsis() + value := ui.Text(k, item.value).FontSize(small).Ellipsis().Grow(1).MinWidth(0) + if !item.words { + value.Mono() + } + a.remotePill(k.Part("source"), remoteSourceName(language, item.source), a.colors.Subtle) + }) + } + }) +} + +// remoteSourceName names where an effective value comes from. +func remoteSourceName(language i18n.Language, source core.RemoteSettingSource) string { + switch source { + case core.RemoteSettingFromConnection: + return i18n.Shared(language, "desktop.remote.source.connection") + case core.RemoteSettingFromSSHConfig: + return i18n.Shared(language, "desktop.remote.source.sshConfig") + } + return i18n.Shared(language, "desktop.remote.source.default") +} + +// remoteFormPage declares the form that edits a connection or makes a new one, and the outcome +// of its test. +func (a *App) remoteFormPage(c ui.C, language i18n.Language, entry *core.SavedRemoteConnection) { + r := &a.remote + title := i18n.Shared(language, "desktop.remote.newConnection") + if entry != nil { + title = i18n.SharedFormat(language, "desktop.remote.editTitle", map[string]string{"name": entry.Name}) + } + ui.Scroll(c.Part("form")).Fill().Children(func() { + ui.Column(c).FillWidth().Gap(16).PadSides(18, 24, 24, 24).Children(func() { + ui.Text(c, title).FontSize(16).Weight(gfx.WeightSemibold).Ellipsis().MinWidth(0) + a.remoteNotices(c) + // The test runs from the footer; its outcome goes over the fields, where it is seen + // without scrolling the form. + switch { + case r.probe != nil: + ui.Row(c.Part("testing")).FillWidth().Items(ui.Center).Gap(8).Pad(12).Radius(6).Stroke(1, a.colors.Line).Children(func() { + ui.Spinner(c.Part("spinner")).Size(14, 14) + ui.Text(c, i18n.Shared(language, "desktop.remote.testing")).Color(a.colors.Subtle) + }) + case r.result != nil: + a.remoteOutcomeBox(c.Part("outcome"), language, r.result) + } + a.remoteFields(c) + }) + }) +} + +// remoteFooter declares the buttons under the list and its page. +func (a *App) remoteFooter(c ui.C, language i18n.Language) { + r := &a.remote + entry := r.entry(r.selected) + ui.Row(c).FillWidth().Items(ui.Center).Gap(8).Children(func() { + switch { + case r.editing: + a.remoteFormFooter(c, language, entry) + case entry != nil && r.confirmDelete: + ui.Text(c, i18n.SharedFormat(language, "desktop.remote.deleteConfirm", map[string]string{"name": entry.Name})).Ellipsis().Grow(1).MinWidth(0) + if ui.Button(c.Part("cancel-delete"), i18n.Shared(language, "desktop.remote.cancel")).Outline().Clicked() { + c.After(func() { r.confirmDelete = false }) + } + if ui.Button(c.Part("delete"), i18n.Shared(language, "desktop.remote.delete")).Destructive().Disabled(r.saving).Clicked() { + c.After(a.removeRemote) + } + default: + ui.Spacer(c) + if ui.Button(c.Part("close"), i18n.Shared(language, "desktop.remote.close")).Outline().Clicked() { + c.After(a.closeRemote) + } + } + }) +} + +// remoteFormFooter declares the form's buttons: test it, and save it, or save and connect a saved +// one. +func (a *App) remoteFormFooter(c ui.C, language i18n.Language, entry *core.SavedRemoteConnection) { + r := &a.remote + 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(r.saving || strings.TrimSpace(r.form.host.Text()) == "").Clicked() { + c.After(a.testRemote) + } + dirty := r.dirty() + if dirty && entry != nil { + ui.Text(c, i18n.Shared(language, "desktop.remote.unsaved")).FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Subtle) + } + ui.Spacer(c) + cancel := i18n.Shared(language, "desktop.remote.cancel") + if entry == nil && len(r.source.Connections) == 0 { + cancel = i18n.Shared(language, "desktop.remote.close") + } + if ui.Button(c.Part("cancel"), cancel).Outline().Disabled(r.saving).Clicked() { + if entry == nil && len(r.source.Connections) == 0 { + c.After(a.closeRemote) + } else { + c.After(a.cancelRemoteEdit) + } + } + save := i18n.Shared(language, "desktop.remote.save") + if r.saving { + save = i18n.Shared(language, "desktop.remote.saving") + } + if entry == nil { + if ui.Button(c.Part("save"), save).Disabled(!r.editable() || r.saving).Clicked() { + c.After(a.saveRemote) + } + return + } + if ui.Button(c.Part("save"), save).Outline().Disabled(!r.editable() || r.saving || !dirty).Clicked() { + c.After(a.saveRemote) + } + if ui.Button(c.Part("connect"), i18n.Shared(language, "desktop.remote.connect")).Disabled(!r.connectable() || dirty).Clicked() { + c.After(func() { a.connectRemote("") }) + } +} diff --git a/desktop/internal/workbench/remote_import.go b/desktop/internal/workbench/remote_import.go new file mode 100644 index 000000000..db4fd2cf6 --- /dev/null +++ b/desktop/internal/workbench/remote_import.go @@ -0,0 +1,380 @@ +package workbench + +import ( + "context" + "os" + "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" +) + +// Import saves hosts other tools already know: Motty's (its config.db under the user's +// configuration directory) and the Host names of ~/.ssh/config. Core reads both and says what +// each host would become and why one cannot be imported; Motty's passwords and keys stay in +// Motty, which keeps them apart from config.db, and are never read. The page lists them with the +// importable ones chosen, and one edit saves the chosen ones. A Motty host already saved can +// still give the saved one its color and group. + +// remoteImportSource is where an import reads hosts. +type remoteImportSource int + +const ( + remoteImportMotty remoteImportSource = iota + remoteImportSSH +) + +// remoteImporter is the import the window shows. +type remoteImporter struct { + source remoteImportSource + loading bool + motty core.RemoteMottyHosts + ssh core.RemoteSSHConfigHosts + mottyErr string + sshErr string + // mottyChosen and sshChosen are the hosts chosen to import, by index. + mottyChosen []bool + sshChosen []bool + keepGroups bool + keepColors bool + applying bool + err string +} + +// remoteMottyChoosable says whether a Motty host can be chosen: to import, or to give the saved +// one its color and group. +func remoteMottyChoosable(status core.RemoteImportStatus) bool { + return remoteImportable(status) || status == core.RemoteImportExists +} + +// openRemoteImport shows the hosts source holds. +func (a *App) openRemoteImport(source remoteImportSource) { + r := &a.remote + r.importMenu = false + if !r.open || !r.editable() || r.saving || r.connect != nil || r.browser != nil { + return + } + a.performed("remote.import.open", surfaceButton) + r.stopProbe() + r.steps = nil + m := &remoteImporter{source: source, loading: true, keepGroups: true, keepColors: true} + r.importer = m + document, err := r.source.Document() + if err != nil { + a.operationFailed("remote_import_read", documentLogError(err)) + m.loading = false + m.err = i18n.SharedFormat(a.language(), "desktop.remote.import.failed", map[string]string{"reason": documentLogError(err).Error()}) + return + } + generation, kernel := r.generation, a.kernel + a.background(nil, remoteReadTimeout, func(ctx context.Context) func(*App) { + var motty core.RemoteMottyHosts + var ssh core.RemoteSSHConfigHosts + var mottyErr, sshErr error + if dir, err := os.UserConfigDir(); err == nil { + motty, mottyErr = kernel.RemoteMottyHosts(ctx, dir, document) + } else { + mottyErr = err + } + if home, err := os.UserHomeDir(); err == nil { + ssh, sshErr = kernel.RemoteSSHConfigHosts(ctx, home, document) + } else { + sshErr = err + } + return func(a *App) { + r := &a.remote + if !r.open || r.generation != generation || r.importer != m { + // log-exempt: 用户取消:窗口已关闭或已离开导入。 + return + } + language := a.language() + m.loading, m.motty, m.ssh = false, motty, ssh + if mottyErr != nil { + a.operationFailed("remote_import_motty", documentLogError(mottyErr)) + m.mottyErr = i18n.SharedFormat(language, "desktop.remote.import.failed", map[string]string{"reason": documentLogError(mottyErr).Error()}) + } + if sshErr != nil { + a.operationFailed("remote_import_ssh_config", documentLogError(sshErr)) + m.sshErr = i18n.SharedFormat(language, "desktop.remote.import.failed", map[string]string{"reason": documentLogError(sshErr).Error()}) + } + m.mottyChosen = make([]bool, len(motty.Candidates)) + for index, candidate := range motty.Candidates { + m.mottyChosen[index] = remoteImportable(candidate.Status) + } + m.sshChosen = make([]bool, len(ssh.Hosts)) + for index, host := range ssh.Hosts { + m.sshChosen[index] = remoteImportable(host.Status) + } + } + }) +} + +// leaveRemoteImport goes back to the list. +func (a *App) leaveRemoteImport() { + a.remote.importer = nil +} + +// chosen counts the hosts chosen in the source shown. +func (m *remoteImporter) chosen() int { + chosen := m.mottyChosen + if m.source == remoteImportSSH { + chosen = m.sshChosen + } + count := 0 + for _, on := range chosen { + if on { + count++ + } + } + return count +} + +// edit is the edit that saves the chosen hosts of the source shown. +func (m *remoteImporter) edit() core.RemoteConnectionImport { + var edit core.RemoteConnectionImport + if m.source == remoteImportSSH { + for index, host := range m.ssh.Hosts { + if index < len(m.sshChosen) && m.sshChosen[index] && remoteImportable(host.Status) { + edit.Entries = append(edit.Entries, core.RemoteConnectionSave{Name: host.Alias, Connection: core.SSHConnection{Host: host.Alias}}) + } + } + return edit + } + for index, candidate := range m.motty.Candidates { + if index >= len(m.mottyChosen) || !m.mottyChosen[index] { + continue + } + var color core.RemoteConnectionColor + var group string + if m.keepColors { + color = candidate.Color + } + if m.keepGroups { + group = candidate.Group + } + switch { + case candidate.Status == core.RemoteImportExists && candidate.ExistingID != "": + if color != "" || group != "" { + edit.Fills = append(edit.Fills, core.RemoteConnectionFill{ID: candidate.ExistingID, Color: color, Group: group}) + } + case remoteImportable(candidate.Status) && candidate.Connection != nil: + edit.Entries = append(edit.Entries, core.RemoteConnectionSave{Name: candidate.Name, Connection: *candidate.Connection, Color: color, Group: group}) + } + } + return edit +} + +// applyRemoteImport saves the chosen hosts and shows the first one saved. +func (a *App) applyRemoteImport() { + r := &a.remote + m := r.importer + if m == nil || m.loading || m.applying || !r.editable() { + return + } + edit := m.edit() + if len(edit.Entries) == 0 && len(edit.Fills) == 0 { + return + } + a.performed("remote.import.apply", surfaceButton) + m.applying, m.err = true, "" + r.saving = true + source, generation, kernel := r.source, r.generation, a.kernel + a.background(nil, remoteReadTimeout, func(ctx context.Context) func(*App) { + after, publication, committed, err := source.Apply(ctx, kernel, core.RemoteConnectionEdit{Import: &edit}) + return func(a *App) { + r := &a.remote + if !r.open || r.generation != generation { + // log-exempt: 用户取消:窗口已关闭,导入已按上面的结果写入或放弃。 + return + } + r.saving = false + m.applying = false + if err != nil { + a.operationFailed("remote_import_apply", documentLogError(err)) + m.err = i18n.SharedFormat(a.language(), "desktop.remote.import.failed", map[string]string{"reason": documentLogError(err).Error()}) + return + } + if !committed { + a.operationRejected("remote_import_apply", "not_committed") + } + r.setSource(after) + if r.importer == m { + r.importer = nil + } + if len(publication.IDs) > 0 { + r.selectEntry(publication.IDs[0]) + } else { + r.selectFirst() + } + count := len(edit.Entries) + len(edit.Fills) + a.notifySuccess(i18n.SharedFormat(a.language(), "desktop.remote.import.done", map[string]string{"count": strconv.Itoa(count)})) + } + }) +} + +// remoteImportStatusName names what an import does with a host. +func remoteImportStatusName(language i18n.Language, status core.RemoteImportStatus) string { + switch status { + case core.RemoteImportable: + return i18n.Shared(language, "desktop.remote.import.status.importable") + case core.RemoteImportPartial: + return i18n.Shared(language, "desktop.remote.import.status.partial") + case core.RemoteImportExists: + return i18n.Shared(language, "desktop.remote.import.status.exists") + case core.RemoteImportPattern: + return i18n.Shared(language, "desktop.remote.import.status.pattern") + case core.RemoteImportInvalid: + return i18n.Shared(language, "desktop.remote.import.status.invalid") + case core.RemoteImportUnreadable: + return i18n.Shared(language, "desktop.remote.import.status.unreadable") + } + return i18n.Shared(language, "desktop.remote.import.status.unsupported") +} + +// remoteMottyUnavailableText says why Motty's hosts could not be read. +func remoteMottyUnavailableText(language i18n.Language, unavailable core.RemoteMottyUnavailable) string { + switch unavailable { + case core.RemoteMottyMissing: + return i18n.Shared(language, "desktop.remote.import.mottyMissing") + case core.RemoteMottyTooLarge: + return i18n.Shared(language, "desktop.remote.import.mottyTooLarge") + case core.RemoteMottyUnsupportedFormat: + return i18n.Shared(language, "desktop.remote.import.mottyUnsupported") + } + return i18n.Shared(language, "desktop.remote.import.mottyUnreadable") +} + +// remoteImportView declares the import: where it reads, what it keeps, and the hosts. +func (a *App) remoteImportView(c ui.C, language i18n.Language, m *remoteImporter) { + small := a.theme.Metrics.FontSizeS + ui.Column(c).Fill().Gap(12).PadSides(18, 24, 12, 24).Children(func() { + ui.Row(c.Part("head")).FillWidth().Items(ui.Center).Gap(12).Children(func() { + ui.Text(c, i18n.Shared(language, "desktop.remote.import.title")).FontSize(16).Weight(gfx.WeightSemibold).Grow(1).MinWidth(0).Ellipsis() + ui.Choice(c.Part("source"), &m.source, []remoteImportSource{remoteImportMotty, remoteImportSSH}, func(source remoteImportSource) string { + if source == remoteImportSSH { + return i18n.Shared(language, "desktop.remote.import.source.ssh") + } + return i18n.Shared(language, "desktop.remote.import.source.motty") + }) + }) + from := m.motty.Database + if m.source == remoteImportSSH { + from = strings.Join(m.ssh.Files, ", ") + } + if from != "" { + ui.Text(c, i18n.SharedFormat(language, "desktop.remote.import.from", map[string]string{"path": from})).FontSize(small).Color(a.colors.Subtle).Ellipsis().MinWidth(0) + } + if m.source == remoteImportMotty && m.motty.Unavailable == "" && len(m.motty.Candidates) > 0 { + ui.Row(c.Part("keep")).FillWidth().Gap(18).Children(func() { + ui.Checkbox(c.Part("groups"), &m.keepGroups, i18n.Shared(language, "desktop.remote.import.keepGroups")).Disabled(m.applying) + ui.Checkbox(c.Part("colors"), &m.keepColors, i18n.Shared(language, "desktop.remote.import.keepColors")).Disabled(m.applying) + }) + } + if m.err != "" { + a.remoteNotice(c.Part("error"), icons.CircleX, a.theme.Danger, m.err) + } + switch { + case m.loading: + ui.Column(c.Part("loading")).FillWidth().Grow(1).Center().Children(func() { ui.Spinner(c.Part("spinner")) }) + case m.source == remoteImportMotty && m.mottyErr != "": + a.remoteNotice(c.Part("motty-error"), icons.CircleX, a.theme.Danger, m.mottyErr) + case m.source == remoteImportMotty && m.motty.Unavailable != "": + a.remoteNotice(c.Part("motty-unavailable"), icons.Info, a.colors.Subtle, remoteMottyUnavailableText(language, m.motty.Unavailable)) + case m.source == remoteImportSSH && m.sshErr != "": + a.remoteNotice(c.Part("ssh-error"), icons.CircleX, a.theme.Danger, m.sshErr) + case m.source == remoteImportMotty && len(m.motty.Candidates) == 0, m.source == remoteImportSSH && len(m.ssh.Hosts) == 0: + a.remoteNotice(c.Part("empty"), icons.Info, a.colors.Subtle, i18n.Shared(language, "desktop.remote.import.empty")) + default: + a.remoteImportList(c.Part("hosts"), language, m) + } + }) +} + +// remoteImportList declares the hosts of the source shown, each with its box. +func (a *App) remoteImportList(c ui.C, language i18n.Language, m *remoteImporter) { + type item struct { + name, address, system string + color core.RemoteConnectionColor + status core.RemoteImportStatus + chosen *bool + choosable bool + detail string + } + var items []item + if m.source == remoteImportSSH { + for index, host := range m.ssh.Hosts { + address := "" + if resolved := host.Resolved; resolved != nil { + address = remoteAddress(core.SSHConnection{Host: resolved.HostName, User: resolved.User, Port: resolved.Port}) + } + detail := host.ExistingName + items = append(items, item{name: host.Alias, address: address, status: host.Status, chosen: &m.sshChosen[index], choosable: remoteImportable(host.Status), detail: detail}) + } + } else { + for index, candidate := range m.motty.Candidates { + items = append(items, item{name: candidate.Name, address: candidate.Address, system: candidate.System, color: candidate.Color, status: candidate.Status, + chosen: &m.mottyChosen[index], choosable: remoteMottyChoosable(candidate.Status)}) + } + } + small := a.theme.Metrics.FontSizeS + ui.Scroll(c).FillWidth().Grow(1).Basis(0).MinHeight(0).Radius(6).Stroke(1, a.colors.Line).Children(func() { + ui.Column(c).FillWidth().Children(func() { + for index, host := range items { + k := c.KeyInt(index) + if index > 0 { + ui.Row(k.Part("line")).FillWidth().Height(1).Shrink(0).Background(a.colors.Line) + } + ui.Row(k).FillWidth().Height(remoteRowHeight).Items(ui.Center).Gap(10).PadX(12).Children(func() { + ui.Checkbox(k.Part("pick"), host.chosen, "").Label(host.name).Shrink(0).Disabled(!host.choosable || m.applying) + mark := "" + if host.system != "" { + mark = remoteSystemMark(&remoteProbeOutcome{result: core.RemoteProbeResult{Host: &core.RemoteProbedHost{System: host.system}}}) + } + a.remoteTile(k.Part("tile"), mark, host.name, host.color, 26, 10) + color := a.colors.Text + if !host.choosable { + color = a.colors.Subtle + } + ui.Column(k).Grow(1).Basis(0).MinWidth(0).Gap(2).Children(func() { + ui.Text(k, host.name).Weight(gfx.WeightMedium).Color(color).Ellipsis().MinWidth(0) + if host.address != "" { + ui.Text(k, host.address).Mono().FontSize(small).Color(a.colors.Subtle).Ellipsis().MinWidth(0) + } + }) + statusColor := a.colors.Subtle + switch host.status { + case core.RemoteImportable: + statusColor = a.colors.Success + case core.RemoteImportPartial: + statusColor = a.colors.Warning + } + a.remotePill(k.Part("status"), remoteImportStatusName(language, host.status), statusColor) + }) + } + }) + }) +} + +// remoteImportFooter declares how many hosts are chosen and the buttons that import them or go +// back. +func (a *App) remoteImportFooter(c ui.C, language i18n.Language, m *remoteImporter) { + ui.Row(c).FillWidth().Items(ui.Center).Gap(8).Children(func() { + count := m.chosen() + ui.Text(c, i18n.SharedFormat(language, "desktop.remote.import.footer", map[string]string{"count": strconv.Itoa(count)})). + FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Subtle).Grow(1).MinWidth(0).Ellipsis() + if ui.Button(c.Part("cancel"), i18n.Shared(language, "desktop.remote.cancel")).Outline().Disabled(m.applying).Clicked() { + c.After(a.leaveRemoteImport) + } + label := i18n.Shared(language, "desktop.remote.import.apply") + if m.applying { + label = i18n.Shared(language, "desktop.remote.import.applying") + } + if ui.Button(c.Part("apply"), label).Icon(icons.Download).Disabled(m.loading || m.applying || count == 0).Clicked() { + c.After(a.applyRemoteImport) + } + }) +} diff --git a/desktop/internal/workbench/remote_list.go b/desktop/internal/workbench/remote_list.go new file mode 100644 index 000000000..45863eda7 --- /dev/null +++ b/desktop/internal/workbench/remote_list.go @@ -0,0 +1,419 @@ +package workbench + +import ( + "context" + "os" + "slices" + "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/icons" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +// This file holds what the Remote Development window's list and pages read besides the saved +// connections: the search, the folded groups, the connections open in a window, what OpenSSH +// resolves for a connection, the address typed on the empty page and the counts of the hosts the +// other tools hold to import. All of it is asked of Core; nothing here is written anywhere. + +// remoteEffective is what OpenSSH resolves for a connection, or why it could not tell. +type remoteEffective struct { + settings core.RemoteEffectiveSettings + err error +} + +// remoteImportCounts are how many hosts Motty and ~/.ssh/config hold that can be imported, once +// loaded. +type remoteImportCounts struct { + loaded bool + motty, sshConfig int +} + +// remoteFormValues are the effective values the form's empty fields show as "Auto (value)", "" +// for one not known. +type remoteFormValues struct { + port, user, timeout, keepAlive string +} + +// buildRows lays out the list from the sections Core found for the query while one is typed, else +// from the source's, under a heading for each group when any section names one. A folded group +// keeps its heading only, and a search unfolds every group. +func (r *remoteState) buildRows() { + r.rows = nil + byID := make(map[string]*core.SavedRemoteConnection, len(r.source.Connections)) + for index := range r.source.Connections { + byID[r.source.Connections[index].ID] = &r.source.Connections[index] + } + sections := r.source.Sections + if r.found != nil { + sections = r.found + } + headed := slices.ContainsFunc(r.source.Sections, func(section core.RemoteConnectionSection) bool { return section.Group != nil }) + for _, section := range sections { + group := "" + if section.Group != nil { + group = *section.Group + } + if headed { + r.rows = append(r.rows, remoteListRow{heading: true, group: group, count: len(section.IDs)}) + if r.found == nil && r.collapsed[group] { + continue + } + } + for _, id := range section.IDs { + if entry := byID[id]; entry != nil { + r.rows = append(r.rows, remoteListRow{entry: entry}) + } + } + } +} + +// toggleRemoteGroup folds or unfolds group in the list. +func (a *App) toggleRemoteGroup(group string) { + r := &a.remote + if r.collapsed == nil { + r.collapsed = map[string]bool{} + } + r.collapsed[group] = !r.collapsed[group] + a.performed("remote.connections.group.toggle", surfaceButton) + r.buildRows() + r.syncListSelection() +} + +// searchRemote asks Core for the connections that match the query and lists only them; an empty +// query lists every connection again. +func (a *App) searchRemote() { + r := &a.remote + r.searching++ + query := strings.TrimSpace(r.query.Text()) + if query == "" { + r.found = nil + r.buildRows() + r.syncListSelection() + return + } + document, err := r.source.Document() + if err != nil { + a.backgroundFailed("remote_connections_search", documentLogError(err)) + return + } + search, generation, kernel := r.searching, r.generation, a.kernel + a.background(nil, remoteReadTimeout, func(ctx context.Context) func(*App) { + found, err := kernel.SearchRemoteConnections(ctx, document, query) + return func(a *App) { + r := &a.remote + if !r.open || r.generation != generation || r.searching != search { + // log-exempt: 用户取消:窗口已关闭或又输入了新的查询,旧结果作废。 + return + } + if err != nil { + a.backgroundFailed("remote_connections_search", err) + return + } + r.found = found.Sections + if r.found == nil { + r.found = []core.RemoteConnectionSection{} + } + r.buildRows() + r.syncListSelection() + } + }) +} + +// clearRemoteSearch empties the query and lists every connection again. +func (a *App) clearRemoteSearch() { + a.remote.query.SetText("") + a.searchRemote() +} + +// remoteWindows is how many open windows work in a folder over the saved connection id. +func (a *App) remoteWindows(id string) int { + if a.sessions == nil { + return 0 + } + count := 0 + for _, w := range a.sessions.list { + if w.project != nil && w.project.remote != nil && w.project.remote.connectionID == id && + w.project.remote.session != "" && !w.project.remote.closed { + count++ + } + } + return count +} + +// remoteLastConnected says when the saved connection last connected, relative to now. +func (a *App) remoteLastConnected(language i18n.Language, entry core.SavedRemoteConnection) string { + if entry.LastConnectedAt == 0 { + return i18n.Shared(language, "desktop.remote.neverConnected") + } + return relativeGitTime(language, a.now(), time.Unix(int64(entry.LastConnectedAt), 0)) +} + +// remoteSystemMark is the two letters the list marks a connection's host with, from what its last +// test found ("Ub" for Ubuntu), "" when it was not tested. +func remoteSystemMark(outcome *remoteProbeOutcome) string { + if outcome == nil || outcome.err != nil || outcome.result.Host == nil { + return "" + } + name := strings.TrimSpace(outcome.result.Host.Details.OperatingSystem) + if name == "" { + name = strings.TrimSpace(outcome.result.Host.System) + } + runes := []rune(name) + if len(runes) == 0 { + return "" + } + if len(runes) > 2 { + runes = runes[:2] + } + return strings.ToUpper(string(runes[:1])) + strings.ToLower(string(runes[1:])) +} + +// quickRemote has Core split the empty page's user@host:port and starts a new connection with it. +func (a *App) quickRemote() { + r := &a.remote + text := strings.TrimSpace(r.quick.Text()) + if text == "" { + return + } + a.performed("remote.connection.quick", surfaceButton) + generation, kernel := r.generation, a.kernel + a.background(nil, remoteReadTimeout, func(ctx context.Context) func(*App) { + address, err := kernel.RemoteParseAddress(ctx, text) + return func(a *App) { + r := &a.remote + if !r.open || r.generation != generation { + // log-exempt: 用户取消:窗口已关闭。 + return + } + language := a.language() + if field, reason, ok := core.RemoteConnectionFieldError(err); ok { + a.operationRejected("remote_connection_quick", "field_refused") + r.quickErr = remoteRefusalText(language, remoteFieldRefusal{field: field, reason: reason}) + return + } + if err != nil { + a.operationFailed("remote_connection_quick", err) + r.quickErr = i18n.SharedFormat(language, "desktop.remote.readFailed", map[string]string{"reason": err.Error()}) + return + } + r.quickErr = "" + r.quick.SetText("") + r.previous = r.selected + r.selectNew() + r.form.host.SetText(address.Host) + r.form.user.SetText(address.User) + if address.Port != 0 { + r.form.port.SetText(strconv.Itoa(int(address.Port))) + } + } + }) +} + +// copyRemoteAsNew starts a new connection filled from the selected one. +func (a *App) copyRemoteAsNew() { + r := &a.remote + entry := r.entry(r.selected) + if entry == nil { + return + } + a.performed("remote.connection.copy", surfaceMenu) + copied := *entry + r.previous = r.selected + r.resetEditing() + r.selected, r.editing = "", true + r.form.fill(copied) + r.form.name.SetText(i18n.SharedFormat(a.language(), "desktop.remote.copyName", map[string]string{"name": copied.Name})) + r.syncListSelection() +} + +// loadRemoteEffective asks OpenSSH, through Core, what it resolves for connection, once per +// opening of the window. +func (a *App) loadRemoteEffective(connection core.SSHConnection) { + r := &a.remote + key := remoteStored(connection) + if _, asked := r.effective[key]; asked { + return + } + if r.effective == nil { + r.effective = map[core.SSHConnection]*remoteEffective{} + } + r.effective[key] = nil + generation, kernel := r.generation, a.kernel + a.background(nil, remoteReadTimeout, func(ctx context.Context) func(*App) { + settings, err := kernel.RemoteEffectiveSettings(ctx, key) + return func(a *App) { + r := &a.remote + if !r.open || r.generation != generation { + // log-exempt: 用户取消:窗口已关闭,读到的值不再显示。 + return + } + if err != nil { + a.backgroundFailed("remote_effective_settings", err) + } + r.effective[key] = &remoteEffective{settings: settings, err: err} + } + }) +} + +// remoteFormEffective is what the form's empty fields fall back to: the effective values of the +// saved connection it edits, once OpenSSH named them. +func (a *App) remoteFormEffective() remoteFormValues { + r := &a.remote + entry := r.entry(r.selected) + if entry == nil { + return remoteFormValues{} + } + known := r.effective[remoteStored(entry.Connection)] + if known == nil || known.err != nil { + return remoteFormValues{} + } + s := known.settings + values := remoteFormValues{user: s.User.Value} + if s.Port.Value != 0 { + values.port = strconv.FormatUint(uint64(s.Port.Value), 10) + } + if s.ConnectTimeoutSeconds.Value != 0 { + values.timeout = i18n.SharedFormat(a.language(), "desktop.remote.seconds", map[string]string{"count": strconv.FormatUint(uint64(s.ConnectTimeoutSeconds.Value), 10)}) + } + if s.KeepAliveSeconds.Value != 0 { + values.keepAlive = i18n.SharedFormat(a.language(), "desktop.remote.seconds", map[string]string{"count": strconv.FormatUint(uint64(s.KeepAliveSeconds.Value), 10)}) + } + return values +} + +// remoteAutoPlaceholder is an empty field's "Auto (value)" when the effective value is known, and +// the field's own placeholder otherwise. +func (a *App) remoteAutoPlaceholder(language i18n.Language, value, fallback string) string { + if value == "" { + return fallback + } + return i18n.SharedFormat(language, "desktop.remote.auto", map[string]string{"value": value}) +} + +// loadRemoteImportCounts counts the hosts Motty and ~/.ssh/config hold that can be imported, for +// the empty page's cards and the import menu. +func (a *App) loadRemoteImportCounts() { + generation, kernel := a.remote.generation, a.kernel + a.background(nil, remoteReadTimeout, func(ctx context.Context) func(*App) { + counts := remoteImportCounts{loaded: true} + var failure error + if dir, err := os.UserConfigDir(); err == nil { + hosts, err := kernel.RemoteMottyHosts(ctx, dir, nil) + if err != nil { + failure = err + } + for _, candidate := range hosts.Candidates { + if remoteImportable(candidate.Status) { + counts.motty++ + } + } + } + if home, err := os.UserHomeDir(); err == nil { + hosts, err := kernel.RemoteSSHConfigHosts(ctx, home, nil) + if err != nil { + failure = err + } + for _, host := range hosts.Hosts { + if remoteImportable(host.Status) { + counts.sshConfig++ + } + } + } + return func(a *App) { + if failure != nil { + a.backgroundFailed("remote_import_count", failure) + } + r := &a.remote + if !r.open || r.generation != generation { + // log-exempt: 用户取消:窗口已关闭,计数不再显示。 + return + } + r.imports = counts + } + }) +} + +// remoteImportable says whether an import of status adds a connection. +func remoteImportable(status core.RemoteImportStatus) bool { + return status == core.RemoteImportable || status == core.RemoteImportPartial +} + +// remoteHopList splits the form's ProxyJump into its jump hosts, in order. +func remoteHopList(text string) []string { + var hops []string + for _, hop := range strings.Split(text, ",") { + if hop = strings.TrimSpace(hop); hop != "" { + hops = append(hops, hop) + } + } + return hops +} + +// addRemoteHop adds the jump hosts typed in the hop field after the form's others. +func (a *App) addRemoteHop() { + r := &a.remote + added := remoteHopList(r.hop.Text()) + if len(added) == 0 { + return + } + r.form.proxyJump.SetText(strings.Join(append(remoteHopList(r.form.proxyJump.Text()), added...), ",")) + r.hop.SetText("") +} + +// remoteHops declares the form's jump hosts as chips with a field that adds one, and under them +// the route a connection takes: this computer, each jump host, then the host. +func (a *App) remoteHops(c ui.C, language i18n.Language, disabled bool) { + r := &a.remote + f := &r.form + hops := remoteHopList(f.proxyJump.Text()) + small := a.theme.Metrics.FontSizeS + ui.Column(c).FillWidth().Gap(8).Children(func() { + ui.Flow(c.Part("hops")).FillWidth().Gap(6).Children(func() { + for index, hop := range hops { + k := c.KeyInt(index) + ui.Row(k).Height(a.theme.Metrics.ControlHeight).Shrink(0).Items(ui.Center).Gap(2).PadSides(0, 3, 0, 9). + Radius(a.theme.Metrics.RadiusItem()).Background(a.colors.Hover).Stroke(1, a.colors.TabIdleBorder).Children(func() { + ui.Text(k, hop).Mono().FontSize(small) + remove := ui.Button(k.Part("remove"), i18n.SharedFormat(language, "desktop.remote.hopRemove", map[string]string{"host": hop})). + Icon(icons.X).IconOnly().Ghost().Size(18, 18).Disabled(disabled) + if remove.Clicked() { + at := index + c.After(func() { + f.proxyJump.SetText(strings.Join(slices.Delete(slices.Clone(hops), at, at+1), ",")) + }) + } + }) + } + field := ui.TextField(c.Part("hop"), &r.hop, i18n.Shared(language, "desktop.remote.hopAdd"), i18n.Shared(language, "desktop.remote.hopPlaceholder")). + Width(240).Icon(icons.Plus).Disabled(disabled) + if field.Submitted() { + c.After(a.addRemoteHop) + } + }) + if len(hops) == 0 { + return + } + ui.Row(c.Part("route")).FillWidth().Gap(6).Items(ui.Center).Children(func() { + step := func(k ui.C, text string, color gfx.Color) { + ui.Icon(k, icons.ChevronRight).Size(12, 12).Shrink(0).Color(a.colors.Subtle) + ui.Text(k, text).Mono().FontSize(small).Color(color).Ellipsis().Shrink(1).MinWidth(0) + } + ui.Text(c, i18n.Shared(language, "desktop.remote.thisComputer")).FontSize(small).Color(a.colors.Subtle).Shrink(0) + for index, hop := range hops { + step(c.KeyInt(index), hop, a.colors.Subtle) + } + target := strings.TrimSpace(f.host.Text()) + if user := strings.TrimSpace(f.user.Text()); user != "" && target != "" { + target = user + "@" + target + } + if target != "" { + step(c.Part("target"), target, a.colors.Accent) + } + }) + }) +} diff --git a/desktop/internal/workbench/remote_shell_view.go b/desktop/internal/workbench/remote_shell_view.go new file mode 100644 index 000000000..4b4c9c463 --- /dev/null +++ b/desktop/internal/workbench/remote_shell_view.go @@ -0,0 +1,314 @@ +package workbench + +import ( + "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's frame and its list: the search, import and new +// buttons above the saved connections under their groups, and the line that says where they are +// kept. The pages beside the list are in remote_detail_view.go and remote_steps_view.go; choosing +// a folder, trusting it and importing take the whole window. + +// remoteListFooterHeight is the height of the line under the list. +const remoteListFooterHeight = 30 + +// 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, a.remoteTitle(language), ui.ModalSpec{Width: remoteWindowWidth, Height: remoteWindowHeight}, func() { + k := c.Part("remote") + switch { + case r.importer != nil: + a.remoteImportView(k, language, r.importer) + case r.trust != nil: + a.remoteTrustView(k, language, r.trust) + case r.browser != nil: + a.remoteBrowserView(k, r.browser) + default: + ui.Row(k).Fill().Children(func() { + a.remoteList(k, language) + ui.Column(k).Width(1).FillHeight().Shrink(0).Background(a.colors.Line) + page := k.Part("page") + ui.Column(page).Grow(1).Basis(0).MinWidth(0).FillHeight().Children(func() { a.remotePage(page, language) }) + }) + } + }, func() { + k := c.Part("remote-footer") + switch { + case r.importer != nil: + a.remoteImportFooter(k, language, r.importer) + case r.trust != nil: + a.remoteTrustFooter(k, language, r.trust) + case r.browser != nil: + a.remoteBrowserFooter(k, r.browser) + case r.steps != nil: + a.remoteStepsFooter(k, language, r.steps) + default: + a.remoteFooter(k, language) + } + }) + if !open { + c.After(a.closeRemote) + } +} + +// remoteTitle is the window's title, followed by where in it the user is: the connection shown, +// a new one, or the import. +func (a *App) remoteTitle(language i18n.Language) string { + r := &a.remote + crumb := "" + switch { + case r.importer != nil: + crumb = i18n.Shared(language, "desktop.remote.import.title") + case r.browser != nil: + crumb = r.browser.name + case r.steps != nil: + crumb = r.steps.entry.Name + case r.editing && r.entry(r.selected) == nil: + crumb = i18n.Shared(language, "desktop.remote.newConnection") + case r.entry(r.selected) != nil: + crumb = r.entry(r.selected).Name + } + if crumb == "" { + return i18n.Shared(language, "desktop.remote.title") + } + return i18n.SharedFormat(language, "desktop.remote.titleWith", map[string]string{"crumb": crumb}) +} + +// remoteList declares the list: its tools, the saved connections under their groups, and where +// they are kept. +func (a *App) remoteList(c ui.C, language i18n.Language) { + r := &a.remote + 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("tools")).FillWidth().Shrink(0).Items(ui.Center).Gap(4).PadSides(10, 8, 8, 10).Children(func() { + search := ui.TextField(k.Part("search"), &r.query, i18n.Shared(language, "desktop.remote.search"), i18n.Shared(language, "desktop.remote.searchPlaceholder")). + Icon(icons.Search).Grow(1).Basis(0).MinWidth(0).Disabled(len(r.source.Connections) == 0) + if r.query.Text() != "" { + search = search.Action(icons.X, i18n.Shared(language, "native.clearSearch")) + if search.ActionClicked() { + c.After(a.clearRemoteSearch) + } + } + if search.Changed() { + c.After(a.searchRemote) + } + a.remoteImportMenu(k.Part("import"), language) + if a.gitIconButton(k.Part("new"), i18n.Shared(language, "desktop.remote.new"), icons.Plus, false, r.saving) { + c.After(a.newRemote) + } + }) + rows := r.rows + switch { + case len(rows) == 0 && r.loading: + a.remoteListNote(k.Part("loading"), i18n.Shared(language, "native.loading")) + case len(rows) == 0 && r.found != nil: + a.remoteListNote(k.Part("none"), i18n.Shared(language, "desktop.remote.noMatch")) + case len(rows) == 0: + a.remoteListNote(k.Part("empty"), i18n.Shared(language, "desktop.remote.empty")) + default: + a.remoteRows(k, language, title, rows) + } + ui.Row(k).FillWidth().Height(1).Shrink(0).Background(a.colors.Line) + ui.Row(k.Part("footer")).FillWidth().Height(remoteListFooterHeight).Shrink(0).Items(ui.Center).Gap(4).PadX(8).Children(func() { + if path := r.source.Path(); path != "" { + a.remoteHelp(k.Part("storage"), i18n.SharedFormat(language, "desktop.remote.storageHelp", map[string]string{"path": path})) + } + ui.Text(k, i18n.SharedFormat(language, "desktop.remote.listFooter", map[string]string{"count": strconv.Itoa(len(r.source.Connections))})). + FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Subtle).Ellipsis().Shrink(1).MinWidth(0) + }) + }) +} + +// remoteListNote declares a short line where the list's rows would be. +func (a *App) remoteListNote(c ui.C, text string) { + ui.Column(c).FillWidth().Grow(1).Pad(14).Children(func() { + ui.Paragraph(c, text, 3).FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Subtle) + }) +} + +// remoteRows declares the rows of the list; choosing one shows its overview. +func (a *App) remoteRows(k ui.C, language i18n.Language, title string, rows []remoteListRow) { + r := &a.remote + r.list.Label = func(row int) string { + if row < 0 || row >= len(r.rows) { + return "" + } + if r.rows[row].heading { + return remoteGroupHeading(language, r.rows[row].group) + } + return r.rows[row].entry.Name + } + r.list.Header = func(row int) bool { return row >= 0 && row < len(r.rows) && r.rows[row].heading } + ui.List(k.Part("rows"), &r.list, len(rows), func(row ui.ListRow) { + if item := rows[row.Index]; item.heading { + a.remoteHeadingRow(row, language, item) + } else { + a.remoteEntryRow(row, language, *item.entry) + } + }).Scrollbars().FillWidth().Grow(1).Shrink(1).MinHeight(0).Label(title) + if r.list.Changed() { + if at := r.list.Selected(); at >= 0 && at < len(rows) && rows[at].entry != nil && (rows[at].entry.ID != r.selected || r.editing || r.steps != nil) { + id := rows[at].entry.ID + c := k + 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() + } +} + +// remoteHeadingRow declares a group's heading: the arrow that folds it, its name and how many +// connections it holds. It stays at the top while its connections scroll under it, so it has the +// window's background. +func (a *App) remoteHeadingRow(row ui.ListRow, language i18n.Language, heading remoteListRow) { + r := &a.remote + rc := row.C + name := remoteGroupHeading(language, heading.group) + icon := icons.ChevronDown + if r.found == nil && r.collapsed[heading.group] { + icon = icons.ChevronRight + } + row.Element.Height(remoteHeadingHeight).Items(ui.Center).Gap(2).PadSides(0, 12, 0, 6).Background(a.theme.Popover) + fold := ui.Button(rc.Part("fold"), i18n.SharedFormat(language, "desktop.remote.groupFold", map[string]string{"group": name})). + Icon(icon).IconOnly().Ghost().Size(18, 18).Shrink(0).Disabled(r.found != nil) + if fold.Clicked() { + group := heading.group + rc.After(func() { a.toggleRemoteGroup(group) }) + } + ui.Text(rc, name).FontSize(a.theme.Metrics.FontSizeS).Weight(gfx.WeightSemibold).Color(a.colors.Subtle).Ellipsis().Shrink(1).MinWidth(0) + ui.Text(rc, strconv.Itoa(heading.count)).FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Subtle).Shrink(0).MarginLeft(4) +} + +// remoteEntryRow declares a saved connection: the mark of its host in its color, its name over its +// address, and on the right whether a window has it open or when it last connected. +func (a *App) remoteEntryRow(row ui.ListRow, language i18n.Language, entry core.SavedRemoteConnection) { + r := &a.remote + rc := row.C + small := a.theme.Metrics.FontSizeS + row.Element.Height(remoteRowHeight).Items(ui.Center).Gap(10).PadSides(0, 12, 0, 12) + a.remoteTile(rc.Part("tile"), remoteSystemMark(r.probedOutcome(entry.Connection)), entry.Name, entry.Color, 26, 10) + ui.Column(rc).Grow(1).Basis(0).MinWidth(0).Gap(2).Children(func() { + ui.Text(rc, entry.Name).Weight(gfx.WeightMedium).Ellipsis().MinWidth(0) + ui.Text(rc, remoteAddress(entry.Connection)).Mono().FontSize(small).Color(a.colors.Subtle).Ellipsis().MinWidth(0) + }) + if a.remoteWindows(entry.ID) > 0 { + ui.Row(rc.Part("live")).Shrink(0).Items(ui.Center).Gap(5).Children(func() { + a.remoteDot(rc.Part("dot"), a.colors.Success, 6) + ui.Text(rc, i18n.Shared(language, "desktop.remote.connectedNow")).FontSize(small).Color(a.colors.Success) + }) + return + } + ui.Text(rc, a.remoteLastConnected(language, entry)).FontSize(small).Color(a.colors.Subtle).Shrink(0) +} + +// remoteTile declares the square that marks a connection's host: the first letters of its system +// on the connection's color, as the build tree marks its build systems, or the first letter of its +// name, outlined, while the host was never tested. +func (a *App) remoteTile(c ui.C, mark, name string, color core.RemoteConnectionColor, size, fontSize float32) { + tint, marked := remoteColor(a.colors.Dark, color) + if !marked { + tint = a.colors.Subtle + } + alpha := float32(0.14) + if a.colors.Dark { + alpha = 0.22 + } + text := mark + if text == "" { + text = remoteNameMark(name) + } + tile := ui.Row(c).Size(size, size).Shrink(0).Center().Radius(size / 5).Background(tint.WithAlpha(alpha)) + if mark == "" { + tile = tile.Stroke(1, a.colors.Line) + } + tile.Children(func() { + ui.Text(c, text).FontSize(fontSize).Weight(gfx.WeightBold).Color(tint) + }) +} + +// remoteNameMark is the first letter of name, upper-cased, or "?" for a name without one. +func remoteNameMark(name string) string { + for _, r := range strings.TrimSpace(name) { + return strings.ToUpper(string(r)) + } + return "?" +} + +// remoteDot declares a round mark of color. +func (a *App) remoteDot(c ui.C, color gfx.Color, size float32) { + ui.Row(c).Size(size, size).Shrink(0).Radius(size / 2).Background(color) +} + +// remotePill declares a small tag, as the run window marks a port. +func (a *App) remotePill(c ui.C, text string, color gfx.Color) { + ui.Row(c).Shrink(0).Height(20).Items(ui.Center).PadX(6).Radius(4).Background(a.colors.Hover).Stroke(1, a.colors.TabIdleBorder).Children(func() { + ui.Text(c, text).FontSize(a.theme.Metrics.FontSizeS).Color(color) + }) +} + +// remoteStatusPill declares a tag tinted with color, with a dot before its text. +func (a *App) remoteStatusPill(c ui.C, text string, color gfx.Color) { + ui.Row(c).Shrink(0).Height(20).Items(ui.Center).Gap(5).PadX(7).Radius(10).Background(color.WithAlpha(0.14)).Children(func() { + a.remoteDot(c.Part("dot"), color, 6) + ui.Text(c, text).FontSize(a.theme.Metrics.FontSizeS).Color(color) + }) +} + +// remoteImportMenu declares the list's import button and the menu it opens: Motty's hosts and +// those of ~/.ssh/config, with how many each holds to import. +func (a *App) remoteImportMenu(c ui.C, language i18n.Language) { + r := &a.remote + anchor, clicked := a.gitToolButton(c, i18n.Shared(language, "desktop.remote.import"), icons.Download, r.importMenu, r.saving || !r.editable()) + if clicked { + c.After(func() { r.importMenu = !r.importMenu }) + } + if !r.importMenu { + return + } + open := true + ui.Menu(c, anchor, &open, func(menu *ui.MenuItems) { + motty := menu.Item(i18n.Shared(language, "desktop.remote.import.motty")) + ssh := menu.Item(i18n.Shared(language, "desktop.remote.import.ssh")) + if r.imports.loaded { + motty = motty.Description(a.remoteImportCountText(language, r.imports.motty)) + ssh = ssh.Description(a.remoteImportCountText(language, r.imports.sshConfig)) + } + if motty.Clicked() { + c.After(func() { a.openRemoteImport(remoteImportMotty) }) + } + if ssh.Clicked() { + c.After(func() { a.openRemoteImport(remoteImportSSH) }) + } + }) + if !open { + r.importMenu = false + } +} + +// remoteImportCountText says how many hosts a source holds to import. +func (a *App) remoteImportCountText(language i18n.Language, count int) string { + if count == 0 { + return i18n.Shared(language, "desktop.remote.import.none") + } + return i18n.SharedFormat(language, "desktop.remote.import.count", map[string]string{"count": strconv.Itoa(count)}) +} diff --git a/desktop/internal/workbench/remote_steps.go b/desktop/internal/workbench/remote_steps.go new file mode 100644 index 000000000..e79ccd902 --- /dev/null +++ b/desktop/internal/workbench/remote_steps.go @@ -0,0 +1,341 @@ +package workbench + +import ( + "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/icons" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +// While Connect runs, the page beside the list shows its steps as Core reports them +// (core.WithRemoteStages), how long each took, the upload of the server build, and the questions +// OpenSSH asks, under the step that asks them: the host key under the connection, the rest under +// the authentication. The authentication dialog leaves those questions to the page while it is +// shown. A connection that fails stays on the page, at the step it failed, with why. + +// remoteStep is one step of a connection, in the order they run. +type remoteStep int + +const ( + remoteStepConfig remoteStep = iota + remoteStepConnect + remoteStepAuthenticate + remoteStepPlatform + remoteStepInstall + remoteStepSession + remoteStepCount +) + +// remoteStepName is step's name. +func remoteStepName(language i18n.Language, step remoteStep) string { + switch step { + case remoteStepConfig: + return i18n.Shared(language, "desktop.remote.step.config") + case remoteStepConnect: + return i18n.Shared(language, "desktop.remote.step.connect") + case remoteStepAuthenticate: + return i18n.Shared(language, "desktop.remote.step.authenticate") + case remoteStepPlatform: + return i18n.Shared(language, "desktop.remote.step.platform") + case remoteStepInstall: + return i18n.Shared(language, "desktop.remote.step.install") + default: + return i18n.Shared(language, "desktop.remote.step.session") + } +} + +// remoteSteps is a connection the page shows running, or failed. +type remoteSteps struct { + entry core.SavedRemoteConnection + // folder is what opens once connected, "" to choose one. + folder string + // reached is the step running, or the one that failed. + reached remoteStep + began time.Time + took [remoteStepCount]time.Duration + // sent and total are the bytes of the server build uploaded so far, while one is uploaded. + sent, total uint64 + failed bool + outcome *remoteProbeOutcome +} + +// newRemoteSteps starts showing a connection to entry. The configuration is read before Core +// starts, so the connection itself runs first. +func newRemoteSteps(entry core.SavedRemoteConnection, folder string, now time.Time) *remoteSteps { + return &remoteSteps{entry: entry, folder: folder, reached: remoteStepConnect, began: now} +} + +// advance ends the steps before to. +func (s *remoteSteps) advance(now time.Time, to remoteStep) { + for s.reached < to { + s.took[s.reached] = now.Sub(s.began) + s.began = now + s.reached++ + } +} + +// observe takes a stage Core reported. +func (s *remoteSteps) observe(now time.Time, stage core.RemoteStage) { + switch stage.Stage { + case core.RemoteStageAuthenticated: + s.advance(now, remoteStepPlatform) + case core.RemoteStagePlatformChecked: + s.advance(now, remoteStepInstall) + case core.RemoteStageUploading: + s.advance(now, remoteStepInstall) + s.sent, s.total = stage.SentBytes, stage.TotalBytes + case core.RemoteStageInstalled: + s.advance(now, remoteStepSession) + } +} + +// fail ends the connection with outcome, at the step it says failed. +func (s *remoteSteps) fail(now time.Time, outcome *remoteProbeOutcome, language i18n.Language) { + step := s.reached + switch { + case outcome.err != nil: + if remoteConnectFailureText(language, outcome.err) != "" { + step = remoteStepInstall + } + case outcome.result.Status == core.RemoteProbeUnreachable, outcome.result.Status == core.RemoteProbeHostKeyRejected: + step = remoteStepConnect + case outcome.result.Status == core.RemoteProbeAuthenticationFailed: + step = remoteStepAuthenticate + case outcome.result.Status == core.RemoteProbeUnsupportedPlatform: + step = remoteStepPlatform + } + if step > s.reached { + s.advance(now, step) + } else { + s.reached = step + } + s.failed, s.outcome = true, outcome +} + +// remoteQuestion is the question OpenSSH asks now, nil when none is asked. +func (a *App) remoteQuestion() *core.GitAuthChallenge { + if g := &a.gitAuth; len(g.queue) > 0 && g.queue[0].Remote { + return &g.queue[0] + } + return nil +} + +// remoteAsksOnPage says whether the page shows OpenSSH's questions, so the authentication dialog +// leaves them to it. +func (a *App) remoteAsksOnPage() bool { + r := &a.remote + return r.open && r.steps != nil && !r.steps.failed && r.importer == nil && r.trust == nil && r.browser == nil +} + +// remoteStepsView declares the connection's steps. +func (a *App) remoteStepsView(c ui.C, language i18n.Language, s *remoteSteps) { + question := a.remoteQuestion() + reached := s.reached + if question != nil && question.Kind != core.RemoteQuestionHostKey && reached == remoteStepConnect && !s.failed { + // OpenSSH asks for a password once connected. + reached = remoteStepAuthenticate + } + title := i18n.SharedFormat(language, "desktop.remote.steps.title", map[string]string{"name": s.entry.Name}) + if s.failed { + title = i18n.SharedFormat(language, "desktop.remote.steps.failed", map[string]string{"name": s.entry.Name}) + } + ui.Scroll(c.Part("steps")).Fill().Children(func() { + ui.Column(c).FillWidth().Gap(18).PadSides(20, 24, 24, 24).Children(func() { + ui.Row(c.Part("head")).FillWidth().Items(ui.Center).Gap(14).Children(func() { + a.remoteTile(c.Part("tile"), remoteSystemMark(a.remote.probedOutcome(s.entry.Connection)), s.entry.Name, s.entry.Color, remoteHeroTile, 15) + ui.Column(c).Grow(1).Basis(0).MinWidth(0).Gap(5).Children(func() { + ui.Text(c, title).FontSize(16).Weight(gfx.WeightSemibold).Ellipsis().MinWidth(0) + ui.Text(c, remoteAddress(s.entry.Connection)).Mono().FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Subtle).Ellipsis().MinWidth(0) + }) + }) + a.remoteBordered(c.Part("list")).Children(func() { + for step := remoteStepConfig; step < remoteStepCount; step++ { + k := c.KeyInt(int(step)) + if step > 0 { + ui.Row(k.Part("line")).FillWidth().Height(1).Shrink(0).Background(a.colors.Line) + } + a.remoteStepRow(k, language, s, step, reached, question) + } + }) + if s.failed && s.outcome != nil { + a.remoteOutcomeBox(c.Part("outcome"), language, s.outcome) + } + }) + }) +} + +// remoteStepRow declares a step: done, running, failed or still to come, and the question it +// asks. +func (a *App) remoteStepRow(c ui.C, language i18n.Language, s *remoteSteps, step, reached remoteStep, question *core.GitAuthChallenge) { + small := a.theme.Metrics.FontSizeS + done := step < reached + current := step == reached + ui.Column(c).FillWidth().Gap(10).PadSides(10, 12, 10, 12).Children(func() { + ui.Row(c.Part("head")).FillWidth().Items(ui.Center).Gap(10).Children(func() { + ui.Row(c.Part("mark")).Size(16, 16).Shrink(0).Center().Children(func() { + switch { + case done: + ui.Icon(c, icons.CircleCheck).Size(16, 16).Color(a.colors.Success) + case current && s.failed: + ui.Icon(c, icons.CircleX).Size(16, 16).Color(a.theme.Danger) + case current: + ui.Spinner(c.Part("spinner")).Size(14, 14) + default: + ui.Row(c.Part("todo")).Size(12, 12).Radius(6).Stroke(1, a.colors.TabIdleBorder) + } + }) + color := a.colors.Text + if !done && !current { + color = a.colors.Subtle + } + label := ui.Text(c, remoteStepName(language, step)).Color(color).Grow(1).MinWidth(0).Ellipsis() + if current { + label.Weight(gfx.WeightMedium) + } + if done && s.took[step] >= 100*time.Millisecond { + ui.Text(c, remoteDuration(language, s.took[step])).Mono().FontSize(small).Color(a.colors.Subtle).Shrink(0) + } + }) + if step == remoteStepInstall && current && !s.failed && s.total > 0 { + ui.Column(c.Part("upload")).FillWidth().Gap(4).PadSides(0, 0, 0, 26).Children(func() { + ui.Progress(c.Part("progress"), float32(s.sent)/float32(s.total)).FillWidth() + ui.Text(c, i18n.SharedFormat(language, "desktop.remote.steps.upload", map[string]string{ + "sent": memorySize(language, s.sent), "total": memorySize(language, s.total), + })).Mono().FontSize(small).Color(a.colors.Subtle) + }) + } + if question == nil || s.failed { + return + } + asks := remoteStepAuthenticate + if question.Kind == core.RemoteQuestionHostKey { + asks = remoteStepConnect + } + if step == asks { + a.remoteQuestionCard(c.Part("question"), language, s, *question) + } + }) +} + +// remoteDuration says how long a step took. +func remoteDuration(language i18n.Language, took time.Duration) string { + return i18n.SharedFormat(language, "desktop.remote.seconds", map[string]string{"count": strconv.FormatFloat(took.Seconds(), 'f', 1, 64)}) +} + +// remoteQuestionCard declares OpenSSH's question under the step that asks it: the host's key to +// trust, or a field for the answer. +func (a *App) remoteQuestionCard(c ui.C, language i18n.Language, s *remoteSteps, head core.GitAuthChallenge) { + g := &a.gitAuth + if g.fieldFor != head.RequestID { + g.field, g.fieldFor = ui.Field{}, head.RequestID + } + small := a.theme.Metrics.FontSizeS + id := head.RequestID + answer := func(text string, confirm bool) { + c.After(func() { + if text != "" { + a.gitAuth.field.SetText(text) + } + a.answerGitAuth(id, confirm) + }) + } + ui.Column(c).FillWidth().Gap(10).Pad(12).MarginLeft(26).Radius(6).Background(a.colors.Hover).Stroke(1, a.colors.Line).Children(func() { + switch { + case head.Kind == core.RemoteQuestionHostKey: + ui.Text(c, i18n.SharedFormat(language, "desktop.remote.hostKey.title", map[string]string{"host": s.entry.Connection.Host})).Weight(gfx.WeightMedium).Ellipsis().MinWidth(0) + for index, item := range [][2]string{ + {i18n.Shared(language, "desktop.remote.hostKey.type"), head.KeyType}, + {i18n.Shared(language, "desktop.remote.hostKey.fingerprint"), head.Fingerprint}, + } { + if item[1] == "" { + continue + } + k := c.KeyInt(index) + ui.Row(k).FillWidth().Items(ui.Center).Gap(10).Children(func() { + ui.Text(k, item[0]).FontSize(small).Color(a.colors.Subtle).Width(80).Shrink(0) + ui.Text(k, item[1]).Mono().FontSize(small).Ellipsis().Grow(1).MinWidth(0) + }) + } + ui.Paragraph(c, i18n.Shared(language, "desktop.remote.hostKey.hint"), 3).FontSize(small).Color(a.colors.Subtle) + ui.Row(c.Part("buttons")).FillWidth().Gap(8).Children(func() { + ui.Spacer(c) + if ui.Button(c.Part("reject"), i18n.Shared(language, "desktop.remote.hostKey.reject")).Outline().Clicked() { + answer("no", true) + } + if ui.Button(c.Part("trust"), i18n.Shared(language, "desktop.remote.hostKey.trust")).Clicked() { + answer("yes", true) + } + }) + case head.Retry: + ui.Paragraph(c, i18n.Shared(language, "desktop.gitAuth.retryMessage"), 3).Color(a.theme.Danger) + ui.Row(c.Part("buttons")).FillWidth().Gap(8).Children(func() { + ui.Spacer(c) + if ui.Button(c.Part("cancel"), i18n.Shared(language, "desktop.remote.cancel")).Outline().Clicked() { + answer("", false) + } + if ui.Button(c.Part("retry"), i18n.Shared(language, "desktop.gitAuth.retry")).Clicked() { + answer("", true) + } + }) + default: + ui.Text(c, i18n.Shared(language, "desktop.remote.question.asks")).Weight(gfx.WeightMedium) + if prompt := strings.TrimSpace(head.Prompt); prompt != "" { + ui.Paragraph(c, prompt, 3).Mono().FontSize(small).Color(a.colors.Subtle) + } + field := ui.TextField(c.Part(head.RequestID), &g.field, i18n.Shared(language, "desktop.remote.question.answer"), "").FillWidth().AutoFocus() + if head.Secret { + field = field.Secure() + } + submitted := field.Submitted() + if head.Attempt > 1 { + ui.Text(c, i18n.Shared(language, "desktop.remoteAuth.refused")).FontSize(small).Color(a.theme.Danger) + } + ui.Row(c.Part("buttons")).FillWidth().Gap(8).Children(func() { + ui.Spacer(c) + if ui.Button(c.Part("cancel"), i18n.Shared(language, "desktop.remote.cancel")).Outline().Clicked() { + answer("", false) + } + if ui.Button(c.Part("continue"), i18n.Shared(language, "desktop.remote.question.continue")).Clicked() || submitted { + answer("", true) + } + }) + } + }) +} + +// remoteStepsFooter declares the buttons under a connection: Stop while it runs; back to the +// connection, its form, or again once it failed. +func (a *App) remoteStepsFooter(c ui.C, language i18n.Language, s *remoteSteps) { + r := &a.remote + ui.Row(c).FillWidth().Items(ui.Center).Gap(8).Children(func() { + if !s.failed { + ui.Spacer(c) + if ui.Button(c.Part("stop"), i18n.Shared(language, "desktop.remote.stop")).Outline().Clicked() { + c.After(a.stopRemoteConnect) + } + return + } + if ui.Button(c.Part("back"), i18n.Shared(language, "desktop.remote.steps.back")).Outline().Clicked() { + c.After(func() { r.steps = nil }) + } + ui.Spacer(c) + if ui.Button(c.Part("edit"), i18n.Shared(language, "desktop.remote.steps.editConnection")).Outline().Disabled(!r.editable()).Clicked() { + c.After(func() { + r.steps = nil + a.editSelectedRemote() + }) + } + if ui.Button(c.Part("retry"), i18n.Shared(language, "desktop.remote.steps.retry")).Clicked() { + folder := s.folder + c.After(func() { + r.steps = nil + a.connectRemote(folder) + }) + } + }) +} diff --git a/desktop/internal/workbench/remote_test.go b/desktop/internal/workbench/remote_test.go index 8ef9e2ac2..a3ababa75 100644 --- a/desktop/internal/workbench/remote_test.go +++ b/desktop/internal/workbench/remote_test.go @@ -153,6 +153,7 @@ func TestRemoteConnectionsSaveEditAndDelete(t *testing.T) { t.Fatal("opening the window wrote the list") } r := &h.app.remote + h.clickLabeled(i18n.Shared(h.app.language(), "desktop.remote.new")) r.form.host.SetText("build.example") r.form.user.SetText("dev") h.redraw() @@ -168,7 +169,7 @@ func TestRemoteConnectionsSaveEditAndDelete(t *testing.T) { 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()) } - if r.editingForm() || !h.shows(i18n.Shared(lang, "desktop.remote.settings")) || !h.showsWrapped(i18n.Shared(lang, "desktop.remote.untested")) { + if r.editingForm() || !h.shows(i18n.Shared(lang, "desktop.remote.recentFolders")) || !h.showsWrapped(i18n.Shared(lang, "desktop.remote.untested")) { t.Fatal("a saved connection does not show its overview") } @@ -189,7 +190,9 @@ func TestRemoteConnectionsSaveEditAndDelete(t *testing.T) { t.Fatal("saving the edit does not go back to the overview") } - h.clickLabeled(i18n.Shared(lang, "desktop.remote.delete")) + h.clickLabeled(i18n.Shared(lang, "desktop.remote.more")) + h.settle() + h.clickFront(i18n.SharedFormat(lang, "desktop.remote.deleteNamed", map[string]string{"name": "Build box"})) 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") @@ -202,7 +205,7 @@ func TestRemoteConnectionsSaveEditAndDelete(t *testing.T) { 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.edit", "remote.connection.save", "remote.connection.remove"} + want := []string{"remote.connections.open", "remote.connection.new", "remote.connection.save", "remote.connection.edit", "remote.connection.save", "remote.connection.deleteAsk", "remote.connection.remove"} if got := remoteActions(logger); !slices.Equal(got, want) { t.Fatalf("performed %q, want %q", got, want) } @@ -246,6 +249,7 @@ func TestRemoteConnectionsColorAndGroup(t *testing.T) { h, logger := remoteHarness(t) lang := h.app.language() r := &h.app.remote + h.clickLabeled(i18n.Shared(h.app.language(), "desktop.remote.new")) r.form.host.SetText("lab-arm.internal") h.redraw() h.clickLabeled(i18n.Shared(lang, "desktop.remote.color.green")) @@ -308,10 +312,8 @@ func TestRemoteCancelGoesBackToTheSavedConnection(t *testing.T) { h, logger := remoteHarness(t) lang := h.app.language() r := &h.app.remote - for index, host := range []string{"lab-arm.internal", "build.example"} { - if index > 0 { - h.clickLabeled(i18n.Shared(lang, "desktop.remote.new")) - } + 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")) @@ -345,7 +347,7 @@ func TestRemoteCancelGoesBackToTheSavedConnection(t *testing.T) { t.Fatalf("saved %+v, want both connections as saved", got) } want := []string{ - "remote.connections.open", "remote.connection.save", "remote.connection.new", "remote.connection.save", + "remote.connections.open", "remote.connection.new", "remote.connection.save", "remote.connection.new", "remote.connection.save", "remote.connection.edit", "remote.connection.edit.cancel", "remote.connection.new", "remote.connection.edit.cancel", } if got := remoteActions(logger); !slices.Equal(got, want) { @@ -368,6 +370,7 @@ func TestRemoteOverviewShowsTheTestedHost(t *testing.T) { h, _ := remoteHarnessWith(t, kernel) lang := h.app.language() r := &h.app.remote + h.clickLabeled(i18n.Shared(h.app.language(), "desktop.remote.new")) r.form.host.SetText("build.example") r.form.user.SetText(" dev ") h.redraw() @@ -411,6 +414,7 @@ func TestRemoteConnectionRefusedFieldsAreShownUnderTheField(t *testing.T) { h, logger := remoteHarness(t) lang := h.app.language() r := &h.app.remote + h.clickLabeled(i18n.Shared(h.app.language(), "desktop.remote.new")) r.form.host.SetText("dev@box") h.redraw() h.clickLabeled(i18n.Shared(lang, "desktop.remote.save")) @@ -488,6 +492,7 @@ func TestRemoteTestAsksInTheWindowAndReportsTheHost(t *testing.T) { h, logger := remoteHarness(t) lang := h.app.language() r := &h.app.remote + h.clickLabeled(i18n.Shared(h.app.language(), "desktop.remote.new")) r.form.host.SetText("devbox") r.form.user.SetText("dev") h.redraw() @@ -533,7 +538,7 @@ func TestRemoteTestAsksInTheWindowAndReportsTheHost(t *testing.T) { 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"} + want := []string{"remote.connections.open", "remote.connection.new", "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) } @@ -548,6 +553,7 @@ func TestRemoteTestStopsWithTheWindow(t *testing.T) { h, _ := remoteHarness(t) lang := h.app.language() r := &h.app.remote + h.clickLabeled(i18n.Shared(h.app.language(), "desktop.remote.new")) r.form.host.SetText("devbox") h.redraw() h.pressTest() diff --git a/desktop/internal/workbench/remote_trust.go b/desktop/internal/workbench/remote_trust.go new file mode 100644 index 000000000..cb0a11a9e --- /dev/null +++ b/desktop/internal/workbench/remote_trust.go @@ -0,0 +1,168 @@ +package workbench + +import ( + "context" + + "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/1lck/Lithe-IDEA/desktop/internal/remoteconn" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +// Before a remote folder opens the first time, the window asks whether to trust it, as the +// editor asks of a local folder: trusted, the folder's own code may run (its tasks, its build +// tools' wrappers); in safe mode it is only read. Core keeps the answers, per connection and +// folder, in the preference file remoteconn.ReadTrust names (toolchains/remote-trust.json under +// the toolchain preference root), never on the host or in the app's bundle. A folder already +// trusted or distrusted opens at once. Opening in safe mode records nothing, so the question +// comes back the next time. + +// remoteTrustPrompt is the question asked before dir opens over browser's session. +type remoteTrustPrompt struct { + browser *remoteBrowser + dir string + trust remoteconn.Trust + // parent is set to trust the folder above dir as well, so that its other folders open + // trusted. + parent bool + deciding bool + err string +} + +// openRemoteFolderAt opens dir over the browser's session, asking first whether to trust it +// when that was never decided. +func (a *App) openRemoteFolderAt(dir string) { + r := &a.remote + b := r.browser + if !r.open || b == nil || b.opening { + return + } + b.opening, b.err = true, "" + generation, kernel, root, session := r.generation, a.kernel, a.globalToolchainRoot(), b.session.ID + a.background(nil, remoteReadTimeout, func(ctx context.Context) func(*App) { + trust, err := remoteconn.ReadTrust(ctx, kernel, root, session, dir) + return func(a *App) { + r := &a.remote + if !r.open || r.generation != generation || r.browser != b { + // log-exempt: 用户取消:窗口已关闭或已返回,会话已随之结束。 + return + } + b.opening = false + if err != nil { + // The folder opens in safe mode: a remote workspace runs none of its code until + // it is trusted, and the question comes back the next time. + a.backgroundFailed("remote_trust_read", documentLogError(err)) + } else if of := trust.State.WorkspaceTrust; of != nil && of.State == core.WorkspaceTrustUnset { + r.trust = &remoteTrustPrompt{browser: b, dir: dir, trust: trust} + return + } + a.openRemoteFolderNow(dir) + } + }) +} + +// leaveRemoteTrust goes back from the question to the folders. +func (a *App) leaveRemoteTrust() { + a.remote.trust = nil +} + +// decideRemoteTrust opens the folder asked about, trusting it first when trusted is set. +func (a *App) decideRemoteTrust(trusted bool) { + r := &a.remote + t := r.trust + if t == nil || t.deciding || r.browser != t.browser { + return + } + if !trusted { + a.performed("remote.workspace.safeMode", surfaceButton) + r.trust = nil + a.openRemoteFolderNow(t.dir) + return + } + a.performed("remote.workspace.trust", surfaceButton) + of := t.trust.State.WorkspaceTrust + workspace := t.dir + if of != nil && of.Workspace != "" { + workspace = of.Workspace + } + decision := core.RemoteWorkspaceTrustDecision{ + SessionID: t.browser.session.ID, Workspace: workspace, Trusted: true, + Location: t.parent && of != nil && of.OfferedLocation != nil, Label: t.browser.name, + } + t.deciding, t.err = true, "" + generation, kernel, trust := r.generation, a.kernel, t.trust + a.background(nil, remoteReadTimeout, func(ctx context.Context) func(*App) { + _, err := trust.Decide(ctx, kernel, decision) + return func(a *App) { + r := &a.remote + if !r.open || r.generation != generation || r.trust != t { + // log-exempt: 用户取消:窗口已关闭或已返回。 + return + } + t.deciding = false + if err != nil { + a.operationFailed("remote_workspace_trust", documentLogError(err)) + t.err = i18n.SharedFormat(a.language(), "desktop.remote.trust.failed", map[string]string{"reason": documentLogError(err).Error()}) + return + } + r.trust = nil + a.openRemoteFolderNow(t.dir) + } + }) +} + +// remoteTrustView declares the question. +func (a *App) remoteTrustView(c ui.C, language i18n.Language, t *remoteTrustPrompt) { + small := a.theme.Metrics.FontSizeS + of := t.trust.State.WorkspaceTrust + notice, border := gfx.RGB24(0xFFF6E9), gfx.RGB24(0xF4CD9A) + if a.colors.Dark { + notice, border = gfx.RGB24(0x44321D), gfx.RGB24(0x694820) + } + ui.Scroll(c.Part("trust")).Fill().Children(func() { + ui.Column(c).FillWidth().Items(ui.Center).PadSides(48, 32, 32, 32).Children(func() { + ui.Column(c.Part("card")).Width(520).Gap(16).Children(func() { + ui.Row(c).Size(40, 40).Center().Radius(10).Background(a.colors.Accent.WithAlpha(0.14)).Children(func() { + ui.Icon(c, icons.ShieldCheck).Size(20, 20).Color(a.colors.Accent) + }) + ui.Column(c).FillWidth().Gap(6).Children(func() { + ui.Text(c, i18n.Shared(language, "desktop.remote.trust.title")).FontSize(16).Weight(gfx.WeightSemibold) + ui.Paragraph(c, i18n.SharedFormat(language, "desktop.remote.trust.body", map[string]string{"folder": t.dir, "name": t.browser.name}), 4).Color(a.colors.Subtle) + }) + ui.Row(c.Part("folder")).FillWidth().Items(ui.Center).Gap(8).Pad(10).Radius(6).Stroke(1, a.colors.Line).Children(func() { + ui.Icon(c, icons.Folder).Size(14, 14).Shrink(0).Color(a.colors.Subtle) + ui.Text(c, t.dir).Mono().FontSize(small).Ellipsis().Grow(1).MinWidth(0) + }) + ui.Row(c.Part("safe")).FillWidth().Gap(8).Pad(10).Radius(6).Background(notice).Stroke(1, border).Children(func() { + ui.Icon(c, icons.Info).Size(14, 14).Shrink(0).Color(a.colors.Warning) + ui.Paragraph(c, i18n.Shared(language, "desktop.remote.trust.safe"), 4).FontSize(small).Grow(1).MinWidth(0) + }) + if of != nil && of.OfferedLocation != nil { + ui.Checkbox(c.Part("parent"), &t.parent, i18n.SharedFormat(language, "desktop.remote.trust.parent", map[string]string{"parent": *of.OfferedLocation})). + Disabled(t.deciding) + } + if t.err != "" { + a.remoteNotice(c.Part("error"), icons.CircleX, a.theme.Danger, t.err) + } + }) + }) + }) +} + +// remoteTrustFooter declares the question's answers. +func (a *App) remoteTrustFooter(c ui.C, language i18n.Language, t *remoteTrustPrompt) { + ui.Row(c).FillWidth().Items(ui.Center).Gap(8).Children(func() { + if ui.Button(c.Part("back"), i18n.Shared(language, "desktop.remote.trust.back")).Outline().Disabled(t.deciding).Clicked() { + c.After(a.leaveRemoteTrust) + } + ui.Spacer(c) + if ui.Button(c.Part("safe"), i18n.Shared(language, "desktop.remote.trust.safeOpen")).Outline().Disabled(t.deciding).Clicked() { + c.After(func() { a.decideRemoteTrust(false) }) + } + if ui.Button(c.Part("trust"), i18n.Shared(language, "desktop.remote.trust.trustOpen")).Icon(icons.ShieldCheck).Disabled(t.deciding).Clicked() { + c.After(func() { a.decideRemoteTrust(true) }) + } + }) +} diff --git a/desktop/internal/workbench/remote_view.go b/desktop/internal/workbench/remote_view.go index 3944d8fb2..2657b71fd 100644 --- a/desktop/internal/workbench/remote_view.go +++ b/desktop/internal/workbench/remote_view.go @@ -37,101 +37,6 @@ const ( // remoteColorChoices are the form's color choices in their order: none, then Core's colors. var remoteColorChoices = append([]core.RemoteConnectionColor{""}, core.RemoteConnectionColors...) -// 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") - if b := r.browser; b != nil { - a.remoteBrowserView(k, b) - return - } - 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() { - if b := r.browser; b != nil { - a.remoteBrowserFooter(c.Part("remote-browser-footer"), b) - return - } - a.remoteFooter(c.Part("remote-footer")) - }) - if !open { - c.After(a.closeRemote) - } -} - -// remoteList declares the saved connections under their groups, below 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, 12).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(a.newRemote) - } - }) - ui.Row(k).FillWidth().Height(1).Shrink(0).Background(a.colors.Line) - rows := r.rows - if len(rows) == 0 { - text := i18n.Shared(language, "desktop.remote.empty") - if r.loading { - text = i18n.Shared(language, "native.loading") - } - ui.Row(k.Part("empty")).FillWidth().Pad(12).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.rows) { - return "" - } - if r.rows[row].heading { - return remoteGroupHeading(language, r.rows[row].group) - } - return r.rows[row].entry.Name - } - r.list.Header = func(row int) bool { return row >= 0 && row < len(r.rows) && r.rows[row].heading } - ui.List(k.Part("rows"), &r.list, len(rows), func(row ui.ListRow) { - if item := rows[row.Index]; item.heading { - a.remoteHeadingRow(row, language, item) - } else { - a.remoteEntryRow(row, *item.entry) - } - }).Scrollbars().FillWidth().Grow(1).Shrink(1).MinHeight(0).Label(title) - if r.list.Changed() { - if at := r.list.Selected(); at >= 0 && at < len(rows) && rows[at].entry != nil && rows[at].entry.ID != r.selected { - id := rows[at].entry.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() - } - }) -} - // remoteGroupHeading is the heading of group in the list, "" being the connections without one. func remoteGroupHeading(language i18n.Language, group string) string { if group == "" { @@ -140,40 +45,6 @@ func remoteGroupHeading(language i18n.Language, group string) string { return group } -// remoteHeadingRow declares a group's heading with the number of its connections. It stays at the -// top while its connections scroll under it, so it has the window's background. -func (a *App) remoteHeadingRow(row ui.ListRow, language i18n.Language, heading remoteListRow) { - rc := row.C - row.Element.Height(remoteHeadingHeight).PadSides(0, 12, 0, 12).Gap(6).Items(ui.Center).Background(a.theme.Popover).Children(func() { - ui.Text(rc, remoteGroupHeading(language, heading.group)).FontSize(a.theme.Metrics.FontSizeS).Weight(gfx.WeightSemibold). - Color(a.colors.Subtle).Ellipsis().Shrink(1).MinWidth(0) - ui.Text(rc, strconv.Itoa(heading.count)).FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Subtle).Shrink(0) - }) -} - -// remoteEntryRow declares a saved connection's row: its color's bar, its name and its address. -func (a *App) remoteEntryRow(row ui.ListRow, entry core.SavedRemoteConnection) { - r := &a.remote - rc := row.C - row.Element.Height(remoteRowHeight).PadSides(0, 10, 0, 4).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() { - bar := ui.Row(rc).Width(3).Height(remoteRowHeight - 16).Shrink(0).Radius(1.5) - if color, ok := remoteColor(a.colors.Dark, entry.Color); ok { - bar.Background(color) - } - 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() - }) - }) -} - // remoteColor is the color a connection is marked with in the light or dark look, false for none. // The pairs are the ones the repository marks use, readable on either background. func remoteColor(dark bool, color core.RemoteConnectionColor) (gfx.Color, bool) { @@ -230,144 +101,6 @@ func remoteAddress(connection core.SSHConnection) string { return address } -// remoteDetail declares the selected connection's overview, or the form with what the last test -// found under it. -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("content")).FillWidth().PadSides(18, 22, 18, 22).Gap(14).Children(func() { - if r.readErr != "" { - a.remoteNotice(k.Part("read"), icons.CircleAlert, a.theme.Danger, r.readErr) - } - if entry := r.entry(r.selected); entry != nil && !r.editingForm() { - a.remoteOverview(k.Part("overview"), language, *entry) - } else { - a.remoteFields(k.Part("form")) - } - if r.err != "" { - ui.Paragraph(k.Part("error"), r.err, 4).FontSize(a.theme.Metrics.FontSizeS).Color(a.theme.Danger) - } - if r.editingForm() { - a.remoteFormResult(k.Part("result"), language) - } - }) - }) -} - -// remoteOverview declares a saved connection: its mark, name, group and address with Edit, what -// the running or last test or connection found about the host, and its settings. -func (a *App) remoteOverview(c ui.C, language i18n.Language, entry core.SavedRemoteConnection) { - r := &a.remote - connection := entry.Connection - ui.Row(c.Part("header")).FillWidth().Gap(12).Items(ui.Center).Children(func() { - mark := ui.Row(c.Part("mark")).Size(40, 40).Shrink(0).Radius(8).Center() - markIcon := a.colors.Subtle - if color, ok := remoteColor(a.colors.Dark, entry.Color); ok { - mark.Background(color) - markIcon = gfx.RGB24(0xFFFFFF) - } else { - mark.Background(a.colors.Hover) - } - mark.Children(func() { - ui.Icon(c, icons.Server).Size(20, 20).Color(markIcon) - }) - ui.Column(c.Part("title")).Grow(1).Shrink(1).MinWidth(0).Gap(4).Children(func() { - ui.Row(c.Part("name")).FillWidth().Gap(8).Items(ui.Center).Children(func() { - ui.Text(c, entry.Name).FontSize(16).Weight(gfx.WeightSemibold).Ellipsis().Shrink(1).MinWidth(0) - if entry.Group != "" { - ui.Badge(c, entry.Group).Shrink(0) - } - }) - ui.Row(c.Part("address")).FillWidth().Gap(8).Items(ui.Center).Children(func() { - ui.Text(c, remoteAddress(connection)).Mono().FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Subtle).Ellipsis().Shrink(1).MinWidth(0) - if jump := strings.TrimSpace(connection.ProxyJump); jump != "" { - ui.Text(c, i18n.SharedFormat(language, "desktop.remote.via", map[string]string{"jump": jump})).FontSize(a.theme.Metrics.FontSizeS). - Color(a.colors.Subtle).Ellipsis().Shrink(1).MinWidth(0) - } - }) - }) - if ui.Button(c.Part("edit"), i18n.Shared(language, "desktop.remote.edit")).Icon(icons.Pencil).Outline().Disabled(r.saving || r.connect != nil).Clicked() { - c.After(a.editSelectedRemote) - } - }) - ui.Row(c.Part("header-line")).FillWidth().Height(1).Shrink(0).Background(a.colors.Line) - - a.remoteSectionHeading(c.Part("host-heading"), i18n.Shared(language, "desktop.remote.hostSection")) - outcome := r.result - if outcome == nil { - outcome = r.probedOutcome(connection) - } - switch { - case r.probe != nil: - a.remoteNotice(c.Part("testing"), icons.LoaderCircle, a.colors.Subtle, i18n.Shared(language, "desktop.remote.testing")) - case r.connect != nil: - a.remoteNotice(c.Part("connecting"), icons.LoaderCircle, a.colors.Subtle, i18n.Shared(language, "desktop.remote.connecting")) - case outcome == nil: - ui.Paragraph(c.Part("untested"), i18n.Shared(language, "desktop.remote.untested"), 3).FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Subtle) - default: - a.remoteOutcome(c.Part("outcome"), language, outcome) - } - - a.remoteSectionHeading(c.Part("settings-heading"), i18n.Shared(language, "desktop.remote.settings")) - a.remoteSettings(c.Part("settings"), language, connection) -} - -// remoteSectionHeading declares the heading of a part of the overview. -func (a *App) remoteSectionHeading(c ui.C, title string) { - ui.Text(c, title).FontSize(a.theme.Metrics.FontSizeS).Weight(gfx.WeightSemibold).PadTop(4) -} - -// remoteSettings declares a saved connection's settings, one a line. A setting left to OpenSSH -// says what it falls back to, as the form's placeholder does. -func (a *App) remoteSettings(c ui.C, language i18n.Language, connection core.SSHConnection) { - type setting struct { - label, value string - // fallback says the value is what an unset setting falls back to. - fallback bool - } - set := func(label, value string) setting { return setting{label: label, value: value} } - // optional is a setting that falls back to unset when value is "". - optional := func(label, value, unset string) setting { - if value == "" { - return setting{label: label, value: unset, fallback: true} - } - return set(label, value) - } - settings := []setting{ - set(i18n.Shared(language, "desktop.remote.host"), connection.Host), - optional(i18n.Shared(language, "desktop.remote.port"), optionalNumber(uint64(connection.Port)), i18n.Shared(language, "desktop.remote.portPlaceholder")), - optional(i18n.Shared(language, "desktop.remote.user"), connection.User, i18n.Shared(language, "desktop.remote.userPlaceholder")), - set(i18n.Shared(language, "desktop.remote.authentication"), remoteAuthenticationLabel(language, connection.Authentication)), - } - if connection.Authentication == core.RemoteAuthenticationPrivateKey { - settings = append(settings, set(i18n.Shared(language, "desktop.remote.identityFile"), connection.IdentityFile)) - } - settings = append(settings, - optional(i18n.Shared(language, "desktop.remote.proxyJump"), connection.ProxyJump, i18n.Shared(language, "desktop.remote.proxyJumpPlaceholder")), - optional(i18n.Shared(language, "desktop.remote.timeout"), optionalNumber(uint64(connection.ConnectTimeoutSeconds)), - i18n.Shared(language, "desktop.remote.timeoutPlaceholder")), - optional(i18n.Shared(language, "desktop.remote.keepAlive"), optionalNumber(uint64(connection.KeepAliveSeconds)), - i18n.Shared(language, "desktop.remote.keepAlivePlaceholder")), - ) - ui.Column(c).FillWidth().Border(1, a.colors.Line).Radius(6).Children(func() { - for index, entry := range settings { - k := c.KeyInt(index) - if index > 0 { - ui.Row(k.Part("line")).FillWidth().Height(1).Shrink(0).Background(a.colors.Line) - } - ui.Row(k).FillWidth().MinHeight(32).PadX(12).Gap(12).Items(ui.Center).Children(func() { - ui.Text(k, entry.label).Color(a.colors.Subtle).Width(remoteSettingWidth).Shrink(0).Ellipsis() - value := ui.Text(k, entry.value).Ellipsis().Grow(1).Shrink(1).MinWidth(0) - if entry.fallback { - value.Color(a.colors.Subtle) - } - }) - } - }) -} - // remoteFields declares the form: two or three fields a line, each under its label, with the // advanced options folded below. func (a *App) remoteFields(c ui.C) { @@ -375,6 +108,7 @@ func (a *App) remoteFields(c ui.C) { f := &r.form language := a.language() disabled := r.saving + effective := a.remoteFormEffective() text := func(k ui.C, label, placeholder string, field *ui.Field) { ui.TextField(k, field, label, placeholder).FillWidth().MinWidth(0).Disabled(disabled) } @@ -399,13 +133,13 @@ func (a *App) remoteFields(c ui.C) { }) label = i18n.Shared(language, "desktop.remote.port") a.remoteCell(k.Part("port"), "port", label, "", remotePortWidth, func(k ui.C) { - text(k, label, i18n.Shared(language, "desktop.remote.portPlaceholder"), &f.port) + text(k, label, a.remoteAutoPlaceholder(language, effective.port, i18n.Shared(language, "desktop.remote.portPlaceholder")), &f.port) }) }) line("line-user", func(k ui.C) { label := i18n.Shared(language, "desktop.remote.user") a.remoteCell(k.Part("user"), "user", label, "", 0, func(k ui.C) { - text(k, label, i18n.Shared(language, "desktop.remote.userPlaceholder"), &f.user) + text(k, label, a.remoteAutoPlaceholder(language, effective.user, i18n.Shared(language, "desktop.remote.userPlaceholder")), &f.user) }) authLabel := i18n.Shared(language, "desktop.remote.authentication") a.remoteCell(k.Part("authentication"), "authentication", authLabel, i18n.Shared(language, "desktop.remote.authenticationHelp"), 0, func(k ui.C) { @@ -428,21 +162,23 @@ func (a *App) remoteFields(c ui.C) { }) }) line("line-group", func(k ui.C) { a.remoteGroupCells(k, language, disabled) }) + line("line-jump", func(k ui.C) { + label := i18n.Shared(language, "desktop.remote.proxyJump") + a.remoteCell(k.Part("proxyJump"), "proxyJump", label, i18n.Shared(language, "desktop.remote.proxyJumpHelp"), 0, func(k ui.C) { + a.remoteHops(k, language, disabled) + }) + }) ui.Collapsible(c.Part("advanced"), &f.advanced, i18n.Shared(language, "desktop.remote.advanced"), func() { k := c.Part("advanced-fields") ui.Column(k).FillWidth().Gap(14).PadTop(4).Children(func() { - label := i18n.Shared(language, "desktop.remote.proxyJump") - a.remoteCell(k.Part("proxyJump"), "proxyJump", label, i18n.Shared(language, "desktop.remote.proxyJumpHelp"), 0, func(k ui.C) { - text(k, label, i18n.Shared(language, "desktop.remote.proxyJumpPlaceholder"), &f.proxyJump) - }) ui.Row(k.Part("line-timing")).FillWidth().Gap(14).Items(ui.Start).Children(func() { label := i18n.Shared(language, "desktop.remote.timeout") a.remoteCell(k.Part("connectTimeoutSeconds"), "connectTimeoutSeconds", label, "", 0, func(k ui.C) { - text(k, label, i18n.Shared(language, "desktop.remote.timeoutPlaceholder"), &f.timeout) + text(k, label, a.remoteAutoPlaceholder(language, effective.timeout, i18n.Shared(language, "desktop.remote.timeoutPlaceholder")), &f.timeout) }) label = i18n.Shared(language, "desktop.remote.keepAlive") a.remoteCell(k.Part("keepAliveSeconds"), "keepAliveSeconds", label, i18n.Shared(language, "desktop.remote.keepAliveHelp"), 0, func(k ui.C) { - text(k, label, i18n.Shared(language, "desktop.remote.keepAlivePlaceholder"), &f.keepAlive) + text(k, label, a.remoteAutoPlaceholder(language, effective.keepAlive, i18n.Shared(language, "desktop.remote.keepAlivePlaceholder")), &f.keepAlive) }) }) }) @@ -557,57 +293,6 @@ func (a *App) remoteNotice(c ui.C, icon gfx.Icon, color gfx.Color, text string) }) } -// remoteFormResult declares, under the form, what the running or last test of what it holds -// found. -func (a *App) remoteFormResult(c ui.C, language i18n.Language) { - r := &a.remote - if r.probe == nil && r.result == nil { - return - } - ui.Column(c).FillWidth().Gap(10).PadTop(2).Children(func() { - ui.Row(c).FillWidth().Height(1).Shrink(0).Background(a.colors.Line) - if r.probe != nil { - a.remoteNotice(c.Part("testing"), icons.LoaderCircle, a.colors.Subtle, i18n.Shared(language, "desktop.remote.testing")) - return - } - a.remoteOutcome(c.Part("outcome"), language, r.result) - }) -} - -// remoteOutcome declares what a 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) remoteOutcome(c ui.C, language i18n.Language, outcome *remoteProbeOutcome) { - ui.Column(c).FillWidth().Gap(8).Children(func() { - if outcome.err != nil { - a.remoteNotice(c.Part("status"), icons.CircleX, a.theme.Danger, remoteFailureText(language, outcome)) - return - } - result := outcome.result - host := result.Host - switch result.Status { - case core.RemoteProbeConnected: - var system, machine string - if host != nil { - system, machine = host.System, host.Machine - } - 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, remoteFailureText(language, outcome)) - default: - a.remoteNotice(c.Part("status"), icons.CircleX, a.theme.Danger, remoteFailureText(language, outcome)) - } - 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) - } - }) -} - // remoteFailureText says why outcome did not connect, and is "" when it connected. The Remote // Development window shows it under the host, and the status bar's menu for the last attempt to // connect a workspace again. @@ -641,116 +326,3 @@ func remoteFailureText(language i18n.Language, outcome *remoteProbeOutcome) stri } return i18n.Shared(language, "desktop.remote.probe.failed") } - -// 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(remoteSettingWidth - 24).Shrink(0).Ellipsis() - ui.Text(k, entry.value).FontSize(a.theme.Metrics.FontSizeS).Ellipsis().Grow(1).MinWidth(0) - }) - } - }) -} - -// remoteFooter declares the footer. The overview has Delete, or the question whether to delete, -// then Test Connection (Stop while a connection runs), Close and Connect; the form has Test -// Connection, then Cancel (Close while nothing is saved to go back to) and Save. Only a saved -// connection connects, so the form saves what was typed first. -func (a *App) remoteFooter(c ui.C) { - r := &a.remote - language := a.language() - entry := r.entry(r.selected) - if !r.editingForm() { - if r.confirmDelete { - 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 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.connect != nil { - if ui.Button(c.Part("stop"), i18n.Shared(language, "desktop.remote.stop")).Outline().Clicked() { - c.After(a.stopRemoteConnect) - } - } else { - a.remoteTestButton(c, language) - } - if ui.Button(c.Part("close"), i18n.Shared(language, "desktop.remote.close")).Outline().Clicked() { - c.After(a.closeRemote) - } - label := i18n.Shared(language, "desktop.remote.connect") - if r.connect != nil { - label = i18n.Shared(language, "desktop.remote.connecting") - } - if ui.Button(c.Part("connect"), label).Disabled(!r.connectable()).Clicked() { - c.After(a.connectRemote) - } - return - } - a.remoteTestButton(c, language) - ui.Spacer(c) - if entry != nil || len(r.rows) > 0 { - if ui.Button(c.Part("cancel"), i18n.Shared(language, "desktop.remote.cancel")).Outline().Disabled(r.saving).Clicked() { - c.After(a.cancelRemoteEdit) - } - } else 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) - } -} - -// remoteTestButton declares Test Connection, or Stop while a test runs. -func (a *App) remoteTestButton(c ui.C, language i18n.Language) { - r := &a.remote - if r.probe != nil { - if ui.Button(c.Part("stop"), i18n.Shared(language, "desktop.remote.stop")).Outline().Clicked() { - c.After(a.stopRemoteTest) - } - return - } - 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) - } -} diff --git a/desktop/internal/workbench/remote_workspace_test.go b/desktop/internal/workbench/remote_workspace_test.go index 6442d67f1..52873e7e0 100644 --- a/desktop/internal/workbench/remote_workspace_test.go +++ b/desktop/internal/workbench/remote_workspace_test.go @@ -258,6 +258,7 @@ func remoteWorkspaceHarness(t *testing.T) (*harness, *remoteHostKernel, *remoteT h.settle() h.settle() r := &h.app.remote + h.clickLabeled(i18n.Shared(h.app.language(), "desktop.remote.new")) r.form.host.SetText(remoteTestHost) r.form.user.SetText("dev") h.redraw() @@ -280,7 +281,7 @@ func (h *harness) clickFront(label string) { // connectAndBrowse presses Connect and waits for the home folder's listing. func (h *harness) connectAndBrowse(t *testing.T) *remoteBrowser { t.Helper() - h.clickFront(i18n.Shared(h.app.language(), "desktop.remote.connect")) + h.clickFront(i18n.Shared(h.app.language(), "desktop.remote.openFolder")) h.await("the home folder's listing", func() bool { b := h.app.remote.browser return b != nil && !b.loading @@ -364,7 +365,7 @@ func TestRemoteWorkspaceOpensTheChosenFolder(t *testing.T) { if slices.ContainsFunc(h.app.recent, func(recent core.RecentProject) bool { return recent.Path == p.root }) { t.Fatal("the placeholder was added to the recent projects") } - want := []string{"remote.connections.open", "remote.connection.save", "remote.connect", "remote.workspace.open"} + want := []string{"remote.connections.open", "remote.connection.new", "remote.connection.save", "remote.connect", "remote.workspace.open"} if got := remoteActions(logger); !slices.Equal(got, want) { t.Fatalf("performed %q, want %q", got, want) } @@ -555,7 +556,7 @@ func TestRemoteBrowserBackEndsTheSession(t *testing.T) { if h.app.remote.browser != nil || !h.app.remote.open || !slices.Contains(k.closed, "session-1") { t.Fatalf("browser %v, closed %q: Back did not end the session", h.app.remote.browser, k.closed) } - if !h.shows(i18n.Shared(lang, "desktop.remote.connect")) { + if !h.shows(i18n.Shared(lang, "desktop.remote.openFolder")) { t.Fatal("Back does not show the form again") } if event := loggedAny(t, logger, remoteTestHome); event != "" { diff --git a/docs/assets/remote-connections/README.md b/docs/assets/remote-connections/README.md index 85d0a493a..d1decbea6 100644 --- a/docs/assets/remote-connections/README.md +++ b/docs/assets/remote-connections/README.md @@ -1,21 +1,50 @@ # 远程开发连接窗口(#2231)无头测试截图 -来自生产 Viva Page 的无头渲染。连接列表由真实 Core 写入测试临时偏好目录,颜色、分组和分组顺序都由 Core 保存和给出;“测试连接”的结果由测试替换的内核直接返回固定的主机信息,不启动 OpenSSH,密码询问由测试直接放入提问队列。截图里的主机、用户和路径都是虚构的。截图覆盖深色与浅色主题、中文与英文界面,用于确认: +截图来自生产 Viva Page 的无头渲染。连接列表由真实 Core 写入测试的临时偏好目录,颜色、分组和分组顺序都由 Core 保存并返回。下列内容都由测试直接给出固定值,不读取本机配置,也不启动 OpenSSH: -- 左侧列表按 Core 给出的分组列出连接,分组标题带数量,没有分组的连接排在最后的“未分组”下;每个连接左侧是它的颜色条; -- 选中已保存的连接时右侧显示概览:颜色图标、名称、分组标签、地址和跳板机,“主机信息”显示这次运行中最近一次测试得到的系统、CPU、内存和磁盘,“连接设置”逐项列出设置,未填写的项显示它的回退规则,例如“自动(SSH 配置,否则 22)”;底部是“删除”“测试连接”“关闭”和“连接”,连接后的文件夹选择见 `docs/assets/remote-workspace`; -- 点“编辑”后右侧换成表单:名称与颜色、主机与端口、用户名、身份验证与私钥、分组各占一行,高级选项折叠在下方; -- 新建连接时可以选“新建分组…”并在旁边输入分组名;主机字段填了 `user@host` 时,Core 拒绝的原因显示在主机字段下方,没有写入列表; -- OpenSSH 询问密码时,窗口上方弹出“SSH 身份验证”,提示原文照搬,输入框为密码框,说明答案只交给这次连接、不会保存。 +- “测试连接”的结果:由测试替换的内核返回固定的主机信息; +- `ssh -G` 解析出的生效设置; +- 空页面上 Motty 和 `~/.ssh/config` 的可导入数量; +- 导入页的 Motty 主机; +- OpenSSH 的主机密钥和密码询问。 -截图不代表 macOS/Windows 原生窗口验收。 +截图里的主机、用户、指纹和路径都是虚构的。截图覆盖深色与浅色主题、中文与英文界面,用于确认: + +- **空页面:** 左侧只有搜索、导入、新建和“还没有保存的连接”。右侧是“通过 SSH 连接 Linux 主机”: + - 一个 `user@host:22` 地址框,交给 Core 解析后填入新连接; + - “从 Motty 导入”和“从 ~/.ssh/config 导入”两张卡片,各显示可导入的主机数; + - “手动填写”。 +- **列表与概览:** 连接按 Core 给出的分组列出,分组可以折叠。每行显示: + - 图标:测过的主机显示系统名的前两个字母(Ubuntu 显示“Ub”),没测过的显示名称首字母,都用连接的颜色; + - 名称、地址和上次连接时间。 +- **概览页:** 选中连接后右侧显示: + - 顶部:图标、颜色点、名称、分组标签,地址后跟跳板机; + - 按钮:“编辑”、“⋯”和“打开文件夹…”; + - 各区块:“最近打开的文件夹”、“主机信息”(主机名、系统、CPU、内存、磁盘,以及测试时间和“重新测试”)、“生效的 SSH 设置”。生效设置逐项列出 `ssh -G` 解析出的值和来源(本连接 / SSH 配置 / 默认值)。 +- **编辑与新建:** 在表单中编辑连接,高级选项可以展开。主机字段填了 `user@host` 时,Core 拒绝的原因显示在主机字段下方,连接不会写入列表。测试失败时,结果显示在表单顶部,OpenSSH 的原始诊断默认展开。 +- **连接步骤:** 依次为读取配置、连接主机、身份验证、检查平台、安装服务端、启动会话: + - OpenSSH 的主机密钥询问显示在“连接主机”下方,带密钥类型和指纹,按钮为“拒绝”和“信任并继续”; + - 密码询问显示在“身份验证”下方; + - 失败时标出失败的步骤并展开诊断。 +- **SSH 密码询问(弹窗):** 窗口上方弹出“SSH 身份验证”,提示原样显示。 +- **信任文件夹:** 第一次打开远程文件夹时询问是否信任,可以选择只信任这个文件夹或信任它的上级目录。 +- **导入:** 页面右上角在 Motty 和 `~/.ssh/config` 之间切换,并显示数据来源路径。可以选择保留分组和保留颜色。每台主机标出状态(可导入 / 部分导入 / 已存在 / 非 SSH),不能导入的主机不能勾选。底部显示已选择的数量。 + +截图不能代替 macOS/Windows 原生窗口验收。 | 场景 | 浅色英文 | 深色中文 | | --- | --- | --- | +| 空页面 | [浅色英文](remote-connections-empty-light-en-US.png) | [深色中文](remote-connections-empty-dark-zh-CN.png) | | 已测试连接的概览 | [浅色英文](remote-connections-overview-light-en-US.png) | [深色中文](remote-connections-overview-dark-zh-CN.png) | | 编辑已保存的连接(展开高级选项) | [浅色英文](remote-connections-edit-light-en-US.png) | [深色中文](remote-connections-edit-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) | +| SSH 密码询问(弹窗) | [浅色英文](remote-connections-password-light-en-US.png) | [深色中文](remote-connections-password-dark-zh-CN.png) | +| 测试失败,诊断展开 | [浅色英文](remote-connections-test-failed-light-en-US.png) | [深色中文](remote-connections-test-failed-dark-zh-CN.png) | +| 连接步骤:主机密钥询问 | [浅色英文](remote-connections-steps-host-key-light-en-US.png) | [深色中文](remote-connections-steps-host-key-dark-zh-CN.png) | +| 连接步骤:密码询问 | [浅色英文](remote-connections-steps-password-light-en-US.png) | [深色中文](remote-connections-steps-password-dark-zh-CN.png) | +| 连接步骤:失败 | [浅色英文](remote-connections-steps-failed-light-en-US.png) | [深色中文](remote-connections-steps-failed-dark-zh-CN.png) | +| 是否信任远程文件夹 | [浅色英文](remote-connections-trust-light-en-US.png) | [深色中文](remote-connections-trust-dark-zh-CN.png) | +| 从 Motty 导入 | [浅色英文](remote-connections-import-light-en-US.png) | [深色中文](remote-connections-import-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` 生成。 +复验方法:在仓库根目录把 `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 300s`。 diff --git a/docs/assets/remote-connections/remote-connections-edit-dark-zh-CN.png b/docs/assets/remote-connections/remote-connections-edit-dark-zh-CN.png index c11e76917..19125778e 100644 Binary files a/docs/assets/remote-connections/remote-connections-edit-dark-zh-CN.png and b/docs/assets/remote-connections/remote-connections-edit-dark-zh-CN.png differ diff --git a/docs/assets/remote-connections/remote-connections-edit-light-en-US.png b/docs/assets/remote-connections/remote-connections-edit-light-en-US.png index 4b92a1d54..cfd20b232 100644 Binary files a/docs/assets/remote-connections/remote-connections-edit-light-en-US.png and b/docs/assets/remote-connections/remote-connections-edit-light-en-US.png differ diff --git a/docs/assets/remote-connections/remote-connections-empty-dark-zh-CN.png b/docs/assets/remote-connections/remote-connections-empty-dark-zh-CN.png new file mode 100644 index 000000000..14f060b9a Binary files /dev/null and b/docs/assets/remote-connections/remote-connections-empty-dark-zh-CN.png differ diff --git a/docs/assets/remote-connections/remote-connections-empty-light-en-US.png b/docs/assets/remote-connections/remote-connections-empty-light-en-US.png new file mode 100644 index 000000000..18b4a6a31 Binary files /dev/null and b/docs/assets/remote-connections/remote-connections-empty-light-en-US.png differ diff --git a/docs/assets/remote-connections/remote-connections-import-dark-zh-CN.png b/docs/assets/remote-connections/remote-connections-import-dark-zh-CN.png new file mode 100644 index 000000000..8a8bca300 Binary files /dev/null and b/docs/assets/remote-connections/remote-connections-import-dark-zh-CN.png differ diff --git a/docs/assets/remote-connections/remote-connections-import-light-en-US.png b/docs/assets/remote-connections/remote-connections-import-light-en-US.png new file mode 100644 index 000000000..d05854da1 Binary files /dev/null and b/docs/assets/remote-connections/remote-connections-import-light-en-US.png differ diff --git a/docs/assets/remote-connections/remote-connections-overview-dark-zh-CN.png b/docs/assets/remote-connections/remote-connections-overview-dark-zh-CN.png index 12d3a54d3..7781b3fac 100644 Binary files a/docs/assets/remote-connections/remote-connections-overview-dark-zh-CN.png and b/docs/assets/remote-connections/remote-connections-overview-dark-zh-CN.png differ diff --git a/docs/assets/remote-connections/remote-connections-overview-light-en-US.png b/docs/assets/remote-connections/remote-connections-overview-light-en-US.png index 50be006b8..3b8c287d5 100644 Binary files a/docs/assets/remote-connections/remote-connections-overview-light-en-US.png and b/docs/assets/remote-connections/remote-connections-overview-light-en-US.png differ 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 index 292cfda6a..8cad61045 100644 Binary files a/docs/assets/remote-connections/remote-connections-password-dark-zh-CN.png 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 index 66c7485ef..78d873884 100644 Binary files a/docs/assets/remote-connections/remote-connections-password-light-en-US.png 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 index 21acd4c8e..6115811f1 100644 Binary files a/docs/assets/remote-connections/remote-connections-refused-dark-zh-CN.png 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 index 80d32baf2..176fdb33f 100644 Binary files a/docs/assets/remote-connections/remote-connections-refused-light-en-US.png and b/docs/assets/remote-connections/remote-connections-refused-light-en-US.png differ diff --git a/docs/assets/remote-connections/remote-connections-steps-failed-dark-zh-CN.png b/docs/assets/remote-connections/remote-connections-steps-failed-dark-zh-CN.png new file mode 100644 index 000000000..b25da7e31 Binary files /dev/null and b/docs/assets/remote-connections/remote-connections-steps-failed-dark-zh-CN.png differ diff --git a/docs/assets/remote-connections/remote-connections-steps-failed-light-en-US.png b/docs/assets/remote-connections/remote-connections-steps-failed-light-en-US.png new file mode 100644 index 000000000..314c7094f Binary files /dev/null and b/docs/assets/remote-connections/remote-connections-steps-failed-light-en-US.png differ diff --git a/docs/assets/remote-connections/remote-connections-steps-host-key-dark-zh-CN.png b/docs/assets/remote-connections/remote-connections-steps-host-key-dark-zh-CN.png new file mode 100644 index 000000000..c8b2f9fd4 Binary files /dev/null and b/docs/assets/remote-connections/remote-connections-steps-host-key-dark-zh-CN.png differ diff --git a/docs/assets/remote-connections/remote-connections-steps-host-key-light-en-US.png b/docs/assets/remote-connections/remote-connections-steps-host-key-light-en-US.png new file mode 100644 index 000000000..be69a1e53 Binary files /dev/null and b/docs/assets/remote-connections/remote-connections-steps-host-key-light-en-US.png differ diff --git a/docs/assets/remote-connections/remote-connections-steps-password-dark-zh-CN.png b/docs/assets/remote-connections/remote-connections-steps-password-dark-zh-CN.png new file mode 100644 index 000000000..65a6f91fc Binary files /dev/null and b/docs/assets/remote-connections/remote-connections-steps-password-dark-zh-CN.png differ diff --git a/docs/assets/remote-connections/remote-connections-steps-password-light-en-US.png b/docs/assets/remote-connections/remote-connections-steps-password-light-en-US.png new file mode 100644 index 000000000..73bc3a22d Binary files /dev/null and b/docs/assets/remote-connections/remote-connections-steps-password-light-en-US.png differ diff --git a/docs/assets/remote-connections/remote-connections-test-failed-dark-zh-CN.png b/docs/assets/remote-connections/remote-connections-test-failed-dark-zh-CN.png new file mode 100644 index 000000000..aa2b2e061 Binary files /dev/null and b/docs/assets/remote-connections/remote-connections-test-failed-dark-zh-CN.png differ diff --git a/docs/assets/remote-connections/remote-connections-test-failed-light-en-US.png b/docs/assets/remote-connections/remote-connections-test-failed-light-en-US.png new file mode 100644 index 000000000..be8a2bb57 Binary files /dev/null and b/docs/assets/remote-connections/remote-connections-test-failed-light-en-US.png differ diff --git a/docs/assets/remote-connections/remote-connections-trust-dark-zh-CN.png b/docs/assets/remote-connections/remote-connections-trust-dark-zh-CN.png new file mode 100644 index 000000000..1b7ae231c Binary files /dev/null and b/docs/assets/remote-connections/remote-connections-trust-dark-zh-CN.png differ diff --git a/docs/assets/remote-connections/remote-connections-trust-light-en-US.png b/docs/assets/remote-connections/remote-connections-trust-light-en-US.png new file mode 100644 index 000000000..2606c7f97 Binary files /dev/null and b/docs/assets/remote-connections/remote-connections-trust-light-en-US.png differ diff --git a/scripts/desktop/build-desktop-core.sh b/scripts/desktop/build-desktop-core.sh index 3bcfc8a44..3538e0775 100755 --- a/scripts/desktop/build-desktop-core.sh +++ b/scripts/desktop/build-desktop-core.sh @@ -317,7 +317,11 @@ PINNED_CORE_REPOSITORY="https://github.com/Lithe-IDEA/Lithe-core-rust.git" # Lithe-core-rust main at 66a1476: #147 starts, stops and lists port forwards # (remote.startForward, remote.stopForward, remote.forwards) and names the process of each # listening port (S28/S29, #2231). -PINNED_CORE_REVISION="68a69a6d9e300576f98c630a85fbf890ad0686b9" +# Lithe-core-rust #154 at 2304b57 (on main 68a69a6): remote.parseAddress, remote.effectiveSettings, +# remote.sshConfigHosts and remote.mottyHosts; the connections query, import and markConnected; +# remoteStage events and classified authentication questions (#2231). Move to the main commit once +# #154 merges. +PINNED_CORE_REVISION="72ad095a0fc1302712775ca21ac26b3cc1de4515" PROFILE="debug" CHECKOUT_ONLY="no" while [[ $# -gt 0 ]]; do diff --git a/shared/i18n/features/remote-connections.json b/shared/i18n/features/remote-connections.json index da4f0f101..50d501af0 100644 --- a/shared/i18n/features/remote-connections.json +++ b/shared/i18n/features/remote-connections.json @@ -1137,6 +1137,852 @@ "platforms": [ "desktop" ] + }, + { + "id": "desktop.remote.titleWith", + "description": "Remote Development window: title while a connection, a new one or the import is shown; crumb names it", + "platforms": [ + "desktop" + ], + "parameters": { + "crumb": "string" + } + }, + { + "id": "desktop.remote.newConnection", + "description": "Remote Development window: what a new, unsaved connection is called in the title and over its form", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.search", + "description": "Remote Development window: accessible name of the field that searches the saved connections", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.searchPlaceholder", + "description": "Remote Development window: placeholder of the search field above the list", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.noMatch", + "description": "Remote Development window: in the list when no saved connection matches the search", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.listFooter", + "description": "Remote Development window: line under the list: how many connections are saved, and that they stay on this computer", + "platforms": [ + "desktop" + ], + "parameters": { + "count": "string" + } + }, + { + "id": "desktop.remote.neverConnected", + "description": "Remote Development window: right of a list row: the connection never opened a folder", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.connectedNow", + "description": "Remote Development window: right of a list row: a window has a folder of the connection open", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.connectedWindows", + "description": "Remote Development window: tag beside a connection's name: how many windows have one of its folders open", + "platforms": [ + "desktop" + ], + "parameters": { + "count": "string" + } + }, + { + "id": "desktop.remote.groupFold", + "description": "Remote Development window: accessible name of the arrow that folds or unfolds a group of the list", + "platforms": [ + "desktop" + ], + "parameters": { + "group": "string" + } + }, + { + "id": "desktop.remote.import", + "description": "Remote Development window: tool button above the list that opens the import menu", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.import.motty", + "description": "Remote Development window: import menu item: Motty's hosts", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.import.ssh", + "description": "Remote Development window: import menu item: the hosts of ~/.ssh/config", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.import.count", + "description": "Remote Development window: under an import menu item or card: how many hosts it can import", + "platforms": [ + "desktop" + ], + "parameters": { + "count": "string" + } + }, + { + "id": "desktop.remote.import.none", + "description": "Remote Development window: under an import menu item or card: nothing to import", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.copyName", + "description": "Remote Development window: name of a connection copied as a new one", + "platforms": [ + "desktop" + ], + "parameters": { + "name": "string" + } + }, + { + "id": "desktop.remote.copyAsNew", + "description": "Remote Development window: ⋯ menu item: open the form for a new connection filled from this one", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.more", + "description": "Remote Development window: accessible name of the ⋯ button beside Edit", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.deleteNamed", + "description": "Remote Development window: ⋯ menu item that asks to delete the connection", + "platforms": [ + "desktop" + ], + "parameters": { + "name": "string" + } + }, + { + "id": "desktop.remote.openFolder", + "description": "Remote Development window: primary button of a connection's overview: connect and choose a folder", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.openOther", + "description": "Remote Development window: link beside Recent folders: connect and choose another folder", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.recentFolders", + "description": "Remote Development window: overview section: folders last opened on the connection", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.noRecentFolders", + "description": "Remote Development window: overview, Recent folders: none yet", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.testedAgo", + "description": "Remote Development window: overview, Host section: when the last test ended; time is relative, such as 5 minutes ago", + "platforms": [ + "desktop" + ], + "parameters": { + "time": "string" + } + }, + { + "id": "desktop.remote.retest", + "description": "Remote Development window: overview, Host section: link that tests the connection again", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.viaHosts", + "description": "Remote Development window: after a connection's address: the hosts it jumps through", + "platforms": [ + "desktop" + ], + "parameters": { + "hosts": "string" + } + }, + { + "id": "desktop.remote.effective", + "description": "Remote Development window: overview section: what OpenSSH uses to reach the host, as ssh -G resolves it", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.effectiveHelp", + "description": "Remote Development window: tip of the ⓘ beside Effective SSH settings", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.effectiveFailed", + "description": "Remote Development window: overview: the effective settings could not be read; reason is the error", + "platforms": [ + "desktop" + ], + "parameters": { + "reason": "string" + } + }, + { + "id": "desktop.remote.setting.hostName", + "description": "Remote Development window: effective settings row: the host name OpenSSH connects to", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.setting.user", + "description": "Remote Development window: effective settings row: the user", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.setting.port", + "description": "Remote Development window: effective settings row: the port", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.setting.identityFiles", + "description": "Remote Development window: effective settings row: the identity files OpenSSH tries", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.setting.proxyJump", + "description": "Remote Development window: effective settings row: the jump hosts", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.setting.connectTimeout", + "description": "Remote Development window: effective settings row: the connection timeout", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.setting.keepAlive", + "description": "Remote Development window: effective settings row: the keep-alive interval", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.source.connection", + "description": "Remote Development window: tag of an effective value set by the saved connection", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.source.sshConfig", + "description": "Remote Development window: tag of an effective value set by the SSH configuration", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.source.default", + "description": "Remote Development window: tag of an effective value that is OpenSSH's default", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.seconds", + "description": "Remote Development window: a number of seconds", + "platforms": [ + "desktop" + ], + "parameters": { + "count": "string" + } + }, + { + "id": "desktop.remote.auto", + "description": "Remote Development window: placeholder of a field left empty: OpenSSH then uses value", + "platforms": [ + "desktop" + ], + "parameters": { + "value": "string" + } + }, + { + "id": "desktop.remote.hopAdd", + "description": "Remote Development window: accessible name of the field that adds a jump host", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.hopPlaceholder", + "description": "Remote Development window: placeholder of the field that adds a jump host", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.hopRemove", + "description": "Remote Development window: accessible name of the button that removes a jump host", + "platforms": [ + "desktop" + ], + "parameters": { + "host": "string" + } + }, + { + "id": "desktop.remote.thisComputer", + "description": "Remote Development window: first stop of the route under the jump hosts", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.unsaved", + "description": "Remote Development window: beside the form's buttons: the form has changes not saved", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.editTitle", + "description": "Remote Development window: heading over the form that edits a saved connection", + "platforms": [ + "desktop" + ], + "parameters": { + "name": "string" + } + }, + { + "id": "desktop.remote.empty.title", + "description": "Remote Development window: first page while no connection is saved: heading", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.empty.body", + "description": "Remote Development window: first page while no connection is saved: what the window does", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.quick.label", + "description": "Remote Development window: first page: label of the field that starts a connection from an address", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.quick.placeholder", + "description": "Remote Development window: first page: placeholder of the address field", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.quick.continue", + "description": "Remote Development window: first page: button that fills the form from the address", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.empty.manual", + "description": "Remote Development window: first page: link that opens an empty form", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.empty.importMotty", + "description": "Remote Development window: first page: card that imports Motty's hosts", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.empty.importSsh", + "description": "Remote Development window: first page: card that imports the hosts of ~/.ssh/config", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.host.cores", + "description": "Remote Development window: host grid, processor cell: how many cores", + "platforms": [ + "desktop" + ], + "parameters": { + "count": "string" + } + }, + { + "id": "desktop.remote.host.diskOf", + "description": "Remote Development window: host grid, disk cell: the disk's size under what is free", + "platforms": [ + "desktop" + ], + "parameters": { + "total": "string" + } + }, + { + "id": "desktop.remote.step.config", + "description": "Remote Development window: connection step: reading the configuration", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.step.connect", + "description": "Remote Development window: connection step: reaching the host", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.step.authenticate", + "description": "Remote Development window: connection step: logging in", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.step.platform", + "description": "Remote Development window: connection step: checking the host's system", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.step.install", + "description": "Remote Development window: connection step: installing the server on the host", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.step.session", + "description": "Remote Development window: connection step: starting the session", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.steps.title", + "description": "Remote Development window: heading while connecting", + "platforms": [ + "desktop" + ], + "parameters": { + "name": "string" + } + }, + { + "id": "desktop.remote.steps.failed", + "description": "Remote Development window: heading once a connection failed", + "platforms": [ + "desktop" + ], + "parameters": { + "name": "string" + } + }, + { + "id": "desktop.remote.steps.upload", + "description": "Remote Development window: under the install step: bytes of the server uploaded", + "platforms": [ + "desktop" + ], + "parameters": { + "sent": "string", + "total": "string" + } + }, + { + "id": "desktop.remote.steps.retry", + "description": "Remote Development window: button after a failed connection: connect again", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.steps.back", + "description": "Remote Development window: button after a failed connection: back to the overview", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.steps.editConnection", + "description": "Remote Development window: button after a failed connection: edit it", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.hostKey.title", + "description": "Remote Development window: question under the connect step: the host's key is not known", + "platforms": [ + "desktop" + ], + "parameters": { + "host": "string" + } + }, + { + "id": "desktop.remote.hostKey.type", + "description": "Remote Development window: host key question: label of the key's type", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.hostKey.fingerprint", + "description": "Remote Development window: host key question: label of the key's fingerprint", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.hostKey.hint", + "description": "Remote Development window: host key question: what trusting does", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.hostKey.reject", + "description": "Remote Development window: host key question: refuse the key", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.hostKey.trust", + "description": "Remote Development window: host key question: trust the key and go on", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.question.asks", + "description": "Remote Development window: question under the authenticate step: OpenSSH asks something", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.question.answer", + "description": "Remote Development window: accessible name of the answer field", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.question.continue", + "description": "Remote Development window: question under the authenticate step: send the answer", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.trust.title", + "description": "Remote Development window: before a remote folder first opens: heading", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.trust.body", + "description": "Remote Development window: before a remote folder first opens: what trusting means", + "platforms": [ + "desktop" + ], + "parameters": { + "folder": "string", + "name": "string" + } + }, + { + "id": "desktop.remote.trust.safe", + "description": "Remote Development window: before a remote folder first opens: what safe mode does", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.trust.parent", + "description": "Remote Development window: checkbox: trust the folder above as well", + "platforms": [ + "desktop" + ], + "parameters": { + "parent": "string" + } + }, + { + "id": "desktop.remote.trust.back", + "description": "Remote Development window: trust question: back to the folders", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.trust.safeOpen", + "description": "Remote Development window: trust question: open without trusting", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.trust.trustOpen", + "description": "Remote Development window: trust question: trust and open", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.trust.failed", + "description": "Remote Development window: trust question: the decision could not be saved; reason is the error", + "platforms": [ + "desktop" + ], + "parameters": { + "reason": "string" + } + }, + { + "id": "desktop.remote.import.title", + "description": "Remote Development window: import page: heading", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.import.source.motty", + "description": "Remote Development window: import page: choice of Motty's hosts", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.import.source.ssh", + "description": "Remote Development window: import page: choice of the hosts of ~/.ssh/config", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.import.from", + "description": "Remote Development window: import page: the file the hosts are read from", + "platforms": [ + "desktop" + ], + "parameters": { + "path": "string" + } + }, + { + "id": "desktop.remote.import.keepGroups", + "description": "Remote Development window: import page: checkbox that keeps Motty's groups", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.import.keepColors", + "description": "Remote Development window: import page: checkbox that keeps Motty's colors", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.import.status.importable", + "description": "Remote Development window: import row tag: the host is imported with all its settings", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.import.status.partial", + "description": "Remote Development window: import row tag: some settings stay behind, such as a saved password", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.import.status.exists", + "description": "Remote Development window: import row tag: the host is already saved; importing only adds its color and group", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.import.status.pattern", + "description": "Remote Development window: import row tag: a Host pattern, not a host", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.import.status.invalid", + "description": "Remote Development window: import row tag: the host's settings are not valid", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.import.status.unreadable", + "description": "Remote Development window: import row tag: the host could not be read", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.import.status.unsupported", + "description": "Remote Development window: import row tag: not an SSH host", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.import.footer", + "description": "Remote Development window: import page footer: how many hosts are chosen", + "platforms": [ + "desktop" + ], + "parameters": { + "count": "string" + } + }, + { + "id": "desktop.remote.import.apply", + "description": "Remote Development window: import page: button that saves the chosen hosts", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.import.applying", + "description": "Remote Development window: import page: the button while saving", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.import.done", + "description": "Remote Development window: notification after an import: how many hosts were saved or updated", + "platforms": [ + "desktop" + ], + "parameters": { + "count": "string" + } + }, + { + "id": "desktop.remote.import.empty", + "description": "Remote Development window: import page: the source has no host", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.import.mottyMissing", + "description": "Remote Development window: import page: Motty is not installed or has no configuration", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.import.mottyUnreadable", + "description": "Remote Development window: import page: Motty's configuration could not be read", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.import.mottyTooLarge", + "description": "Remote Development window: import page: Motty's configuration is too large to read", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.import.mottyUnsupported", + "description": "Remote Development window: import page: Motty's configuration is in a format not known", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.remote.import.failed", + "description": "Remote Development window: import page: reading or saving failed; reason is the error", + "platforms": [ + "desktop" + ], + "parameters": { + "reason": "string" + } } ], "locales": { @@ -1146,7 +1992,7 @@ "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.empty": "No saved connections", "desktop.remote.name": "Name", "desktop.remote.namePlaceholder": "Defaults to the host", "desktop.remote.host": "Host", @@ -1280,6 +2126,115 @@ "desktop.remote.status.reconnect": "Reconnect", "desktop.remote.status.disconnect": "Disconnect and Close", "desktop.remote.workspace.title": "{folder} [SSH: {connection}]", + "desktop.remote.titleWith": "Remote Development › {crumb}", + "desktop.remote.newConnection": "New Connection", + "desktop.remote.search": "Search connections", + "desktop.remote.searchPlaceholder": "Search name, host or group", + "desktop.remote.noMatch": "No connection matches", + "desktop.remote.listFooter": "{count} saved · on this computer only", + "desktop.remote.neverConnected": "Never", + "desktop.remote.connectedNow": "Connected", + "desktop.remote.connectedWindows": "{count} window(s) open", + "desktop.remote.groupFold": "Fold or unfold {group}", + "desktop.remote.import": "Import", + "desktop.remote.import.motty": "From Motty…", + "desktop.remote.import.ssh": "From ~/.ssh/config…", + "desktop.remote.import.count": "{count} host(s) to import", + "desktop.remote.import.none": "No hosts found", + "desktop.remote.copyName": "{name} copy", + "desktop.remote.copyAsNew": "Duplicate as New", + "desktop.remote.more": "More", + "desktop.remote.deleteNamed": "Delete “{name}”…", + "desktop.remote.openFolder": "Open Folder…", + "desktop.remote.openOther": "Open another…", + "desktop.remote.recentFolders": "Recent folders", + "desktop.remote.noRecentFolders": "No folder opened yet", + "desktop.remote.testedAgo": "Tested {time}", + "desktop.remote.retest": "Test again", + "desktop.remote.viaHosts": "via {hosts}", + "desktop.remote.effective": "Effective SSH settings", + "desktop.remote.effectiveHelp": "What OpenSSH will use to connect, as `ssh -G` resolves this connection with your SSH configuration. Each value says whether it comes from this connection, the SSH configuration or OpenSSH's default.", + "desktop.remote.effectiveFailed": "Could not read the effective settings: {reason}", + "desktop.remote.setting.hostName": "Host name", + "desktop.remote.setting.user": "User", + "desktop.remote.setting.port": "Port", + "desktop.remote.setting.identityFiles": "Identity files", + "desktop.remote.setting.proxyJump": "Jump hosts", + "desktop.remote.setting.connectTimeout": "Connect timeout", + "desktop.remote.setting.keepAlive": "Keep-alive", + "desktop.remote.source.connection": "This connection", + "desktop.remote.source.sshConfig": "SSH config", + "desktop.remote.source.default": "Default", + "desktop.remote.seconds": "{count} s", + "desktop.remote.auto": "Automatic ({value})", + "desktop.remote.hopAdd": "Add jump host", + "desktop.remote.hopPlaceholder": "user@host:port, then Return", + "desktop.remote.hopRemove": "Remove {host}", + "desktop.remote.thisComputer": "This computer", + "desktop.remote.unsaved": "Unsaved changes", + "desktop.remote.editTitle": "Edit {name}", + "desktop.remote.empty.title": "Connect to a Linux host over SSH", + "desktop.remote.empty.body": "Open a folder on the host as a workspace. The editor, terminal, Git and search work on the host; only the window runs here.", + "desktop.remote.quick.label": "Address", + "desktop.remote.quick.placeholder": "user@host:22", + "desktop.remote.quick.continue": "Continue", + "desktop.remote.empty.manual": "Fill in the form instead", + "desktop.remote.empty.importMotty": "Import from Motty", + "desktop.remote.empty.importSsh": "Import from ~/.ssh/config", + "desktop.remote.host.cores": "{count} cores", + "desktop.remote.host.diskOf": "of {total}", + "desktop.remote.step.config": "Read configuration", + "desktop.remote.step.connect": "Connect to host", + "desktop.remote.step.authenticate": "Authenticate", + "desktop.remote.step.platform": "Check platform", + "desktop.remote.step.install": "Install server", + "desktop.remote.step.session": "Start session", + "desktop.remote.steps.title": "Connecting to {name}", + "desktop.remote.steps.failed": "Could not connect to {name}", + "desktop.remote.steps.upload": "{sent} of {total}", + "desktop.remote.steps.retry": "Try Again", + "desktop.remote.steps.back": "Back", + "desktop.remote.steps.editConnection": "Edit Connection", + "desktop.remote.hostKey.title": "Trust the key of {host}?", + "desktop.remote.hostKey.type": "Type", + "desktop.remote.hostKey.fingerprint": "Fingerprint", + "desktop.remote.hostKey.hint": "Compare the fingerprint with the one your administrator gave you. Trusting adds the key to ~/.ssh/known_hosts.", + "desktop.remote.hostKey.reject": "Reject", + "desktop.remote.hostKey.trust": "Trust and Continue", + "desktop.remote.question.asks": "OpenSSH asks:", + "desktop.remote.question.answer": "Answer", + "desktop.remote.question.continue": "Continue", + "desktop.remote.trust.title": "Trust this folder?", + "desktop.remote.trust.body": "Do you trust the authors of {folder} on {name}? A trusted folder can run its own code, such as tasks and build tool wrappers.", + "desktop.remote.trust.safe": "In safe mode the folder is only read: nothing in it runs until you trust it.", + "desktop.remote.trust.parent": "Trust all folders in {parent}", + "desktop.remote.trust.back": "Back", + "desktop.remote.trust.safeOpen": "Open in Safe Mode", + "desktop.remote.trust.trustOpen": "Trust and Open", + "desktop.remote.trust.failed": "Could not save the decision: {reason}", + "desktop.remote.import.title": "Import Hosts", + "desktop.remote.import.source.motty": "Motty", + "desktop.remote.import.source.ssh": "~/.ssh/config", + "desktop.remote.import.from": "From {path}", + "desktop.remote.import.keepGroups": "Keep groups", + "desktop.remote.import.keepColors": "Keep colors", + "desktop.remote.import.status.importable": "Ready", + "desktop.remote.import.status.partial": "Partial", + "desktop.remote.import.status.exists": "Already saved", + "desktop.remote.import.status.pattern": "Pattern", + "desktop.remote.import.status.invalid": "Invalid", + "desktop.remote.import.status.unreadable": "Unreadable", + "desktop.remote.import.status.unsupported": "Not SSH", + "desktop.remote.import.footer": "{count} chosen", + "desktop.remote.import.apply": "Import", + "desktop.remote.import.applying": "Importing…", + "desktop.remote.import.done": "Imported {count} host(s)", + "desktop.remote.import.empty": "No hosts found here.", + "desktop.remote.import.mottyMissing": "Motty's configuration was not found on this computer.", + "desktop.remote.import.mottyUnreadable": "Motty's configuration could not be read.", + "desktop.remote.import.mottyTooLarge": "Motty's configuration is too large to read.", + "desktop.remote.import.mottyUnsupported": "This version of Motty's configuration is not supported.", + "desktop.remote.import.failed": "Could not import: {reason}", "desktop.remote.workspace.banner": "This is a remote workspace. Its files open, edit and save on the host, and terminals run on the host; search, Git and running do not work here yet.", "desktop.remote.workspace.localOnly": "This feature does not work in a remote workspace yet. You can browse, edit and save the host's files and run terminals on the host.", "desktop.remote.document.disconnected": "the remote workspace is not connected; try again once it reconnects", @@ -1298,7 +2253,7 @@ "desktop.remote.saved": "已保存的连接", "desktop.remote.storageHelp": "保存在本机的 {path}。不会保存密码和私钥内容。", "desktop.remote.new": "新建连接", - "desktop.remote.empty": "还没有保存的连接。填写右侧表单后保存。", + "desktop.remote.empty": "还没有保存的连接", "desktop.remote.name": "名称", "desktop.remote.namePlaceholder": "默认使用主机名", "desktop.remote.host": "主机", @@ -1432,6 +2387,115 @@ "desktop.remote.status.reconnect": "重新连接", "desktop.remote.status.disconnect": "断开并关闭", "desktop.remote.workspace.title": "{folder} [SSH: {connection}]", + "desktop.remote.titleWith": "远程开发 › {crumb}", + "desktop.remote.newConnection": "新建连接", + "desktop.remote.search": "搜索连接", + "desktop.remote.searchPlaceholder": "搜索名称、主机或分组", + "desktop.remote.noMatch": "没有匹配的连接", + "desktop.remote.listFooter": "{count} 个连接 · 只保存在本机", + "desktop.remote.neverConnected": "从未连接", + "desktop.remote.connectedNow": "已连接", + "desktop.remote.connectedWindows": "{count} 个窗口已打开", + "desktop.remote.groupFold": "折叠或展开 {group}", + "desktop.remote.import": "导入", + "desktop.remote.import.motty": "从 Motty 导入…", + "desktop.remote.import.ssh": "从 ~/.ssh/config 导入…", + "desktop.remote.import.count": "可导入 {count} 台主机", + "desktop.remote.import.none": "没有找到主机", + "desktop.remote.copyName": "{name} 副本", + "desktop.remote.copyAsNew": "复制为新连接", + "desktop.remote.more": "更多", + "desktop.remote.deleteNamed": "删除“{name}”…", + "desktop.remote.openFolder": "打开文件夹…", + "desktop.remote.openOther": "打开其他…", + "desktop.remote.recentFolders": "最近打开的文件夹", + "desktop.remote.noRecentFolders": "还没有打开过文件夹", + "desktop.remote.testedAgo": "{time}测试", + "desktop.remote.retest": "重新测试", + "desktop.remote.viaHosts": "经由 {hosts}", + "desktop.remote.effective": "生效的 SSH 设置", + "desktop.remote.effectiveHelp": "OpenSSH 实际连接时使用的值,由 `ssh -G` 结合你的 SSH 配置解析得出。每个值都标明来自本连接、SSH 配置还是 OpenSSH 默认值。", + "desktop.remote.effectiveFailed": "无法读取生效设置:{reason}", + "desktop.remote.setting.hostName": "主机名", + "desktop.remote.setting.user": "用户", + "desktop.remote.setting.port": "端口", + "desktop.remote.setting.identityFiles": "身份文件", + "desktop.remote.setting.proxyJump": "跳板机", + "desktop.remote.setting.connectTimeout": "连接超时", + "desktop.remote.setting.keepAlive": "保活间隔", + "desktop.remote.source.connection": "本连接", + "desktop.remote.source.sshConfig": "SSH 配置", + "desktop.remote.source.default": "默认值", + "desktop.remote.seconds": "{count} 秒", + "desktop.remote.auto": "自动({value})", + "desktop.remote.hopAdd": "添加跳板机", + "desktop.remote.hopPlaceholder": "user@host:port,按回车添加", + "desktop.remote.hopRemove": "移除 {host}", + "desktop.remote.thisComputer": "本机", + "desktop.remote.unsaved": "有未保存的修改", + "desktop.remote.editTitle": "编辑 {name}", + "desktop.remote.empty.title": "通过 SSH 连接 Linux 主机", + "desktop.remote.empty.body": "把主机上的文件夹作为工作区打开。编辑器、终端、Git 和搜索都在主机上运行,本机只负责显示。", + "desktop.remote.quick.label": "地址", + "desktop.remote.quick.placeholder": "user@host:22", + "desktop.remote.quick.continue": "继续", + "desktop.remote.empty.manual": "手动填写", + "desktop.remote.empty.importMotty": "从 Motty 导入", + "desktop.remote.empty.importSsh": "从 ~/.ssh/config 导入", + "desktop.remote.host.cores": "{count} 核", + "desktop.remote.host.diskOf": "共 {total}", + "desktop.remote.step.config": "读取配置", + "desktop.remote.step.connect": "连接主机", + "desktop.remote.step.authenticate": "身份验证", + "desktop.remote.step.platform": "检查平台", + "desktop.remote.step.install": "安装服务端", + "desktop.remote.step.session": "启动会话", + "desktop.remote.steps.title": "正在连接 {name}", + "desktop.remote.steps.failed": "无法连接 {name}", + "desktop.remote.steps.upload": "{sent} / {total}", + "desktop.remote.steps.retry": "重试", + "desktop.remote.steps.back": "返回", + "desktop.remote.steps.editConnection": "编辑连接", + "desktop.remote.hostKey.title": "信任 {host} 的主机密钥?", + "desktop.remote.hostKey.type": "类型", + "desktop.remote.hostKey.fingerprint": "指纹", + "desktop.remote.hostKey.hint": "请与管理员提供的指纹核对。信任后,密钥会加入 ~/.ssh/known_hosts。", + "desktop.remote.hostKey.reject": "拒绝", + "desktop.remote.hostKey.trust": "信任并继续", + "desktop.remote.question.asks": "OpenSSH 询问:", + "desktop.remote.question.answer": "回答", + "desktop.remote.question.continue": "继续", + "desktop.remote.trust.title": "信任此文件夹吗?", + "desktop.remote.trust.body": "你信任 {name} 上 {folder} 的作者吗?受信任的文件夹可以运行其中的代码,例如任务和构建工具包装脚本。", + "desktop.remote.trust.safe": "在安全模式下只读取文件夹,信任之前不会运行其中的任何代码。", + "desktop.remote.trust.parent": "信任 {parent} 下的所有文件夹", + "desktop.remote.trust.back": "返回", + "desktop.remote.trust.safeOpen": "以安全模式打开", + "desktop.remote.trust.trustOpen": "信任并打开", + "desktop.remote.trust.failed": "无法保存决定:{reason}", + "desktop.remote.import.title": "导入主机", + "desktop.remote.import.source.motty": "Motty", + "desktop.remote.import.source.ssh": "~/.ssh/config", + "desktop.remote.import.from": "来自 {path}", + "desktop.remote.import.keepGroups": "保留分组", + "desktop.remote.import.keepColors": "保留颜色", + "desktop.remote.import.status.importable": "可导入", + "desktop.remote.import.status.partial": "部分导入", + "desktop.remote.import.status.exists": "已存在", + "desktop.remote.import.status.pattern": "通配规则", + "desktop.remote.import.status.invalid": "无效", + "desktop.remote.import.status.unreadable": "无法读取", + "desktop.remote.import.status.unsupported": "非 SSH", + "desktop.remote.import.footer": "已选择 {count} 台", + "desktop.remote.import.apply": "导入", + "desktop.remote.import.applying": "正在导入…", + "desktop.remote.import.done": "已导入 {count} 台主机", + "desktop.remote.import.empty": "这里没有主机。", + "desktop.remote.import.mottyMissing": "在本机没有找到 Motty 的配置。", + "desktop.remote.import.mottyUnreadable": "无法读取 Motty 的配置。", + "desktop.remote.import.mottyTooLarge": "Motty 的配置过大,无法读取。", + "desktop.remote.import.mottyUnsupported": "不支持这个版本的 Motty 配置。", + "desktop.remote.import.failed": "无法导入:{reason}", "desktop.remote.workspace.banner": "这是远程工作区。主机上的文件可以打开、编辑和保存,终端在主机上运行;搜索、Git 和运行暂不可用。", "desktop.remote.workspace.localOnly": "远程工作区暂不支持此功能,可以浏览、编辑和保存主机上的文件,也可以在主机上运行终端。", "desktop.remote.document.disconnected": "远程工作区未连接,请在重新连接后再试",